<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
require_admin($conn);

/* ===============================
   LOAD USER
================================ */
$userId = (int)($_GET['user_id'] ?? 0);
if ($userId < 1) {
    flash('err','Invalid user.');
    redirect('customers.php');
}

$st = $conn->prepare("
    SELECT id, full_name, email
    FROM users
    WHERE id = ?
    LIMIT 1
");
$st->bind_param("i", $userId);
$st->execute();
$user = $st->get_result()->fetch_assoc();

if (!$user) {
    flash('err','User not found.');
    redirect('customers.php');
}

/* ===============================
   LOAD USER WALLETS
================================ */
$wallets = [];
$st = $conn->prepare("
    SELECT 
        cw.asset_id,
        cw.balance,
        cw.locked_balance,
        ca.symbol,
        ca.name
    FROM crypto_wallets cw
    JOIN crypto_assets ca ON ca.id = cw.asset_id
    WHERE cw.user_id = ?
    ORDER BY ca.symbol ASC
");
$st->bind_param("i", $userId);
$st->execute();
$res = $st->get_result();
while ($r = $res->fetch_assoc()) {
    $wallets[] = $r;
}

/* ===============================
   LOAD TRANSACTIONS
================================ */
$txns = [];
$st = $conn->prepare("
    SELECT 
        ct.ref,
        ct.type,
        ct.amount,
        ct.fee,
        ct.total_debit,
        ct.status,
        ct.destination,
        ct.created_at,
        ca.symbol
    FROM crypto_txn ct
    JOIN crypto_assets ca ON ca.id = ct.asset_id
    WHERE ct.user_id = ?
    ORDER BY ct.id DESC
    LIMIT 50
");
$st->bind_param("i", $userId);
$st->execute();
$res = $st->get_result();
while ($r = $res->fetch_assoc()) {
    $txns[] = $r;
}

$title = 'User Crypto Wallet';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/admin_sidebar.php';
?>

<main class="flex-grow-1" style="margin-left:240px; min-height:100vh;">
<div class="container-fluid py-4">

  <!-- HEADER -->
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <h3 class="fw-bold mb-0">Crypto Wallet</h3>
      <div class="ab-muted">
        <?= e($user['full_name'] ?? $user['email']) ?> (ID <?= (int)$user['id'] ?>)
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="crypto_wallet_credit_form.php?user_id=<?= (int)$user['id'] ?>"
         class="btn btn-success btn-sm">
        <i class="bi bi-plus-circle"></i> Credit
      </a>
      <a href="crypto_wallet_debit_form.php?user_id=<?= (int)$user['id'] ?>"
         class="btn btn-danger btn-sm">
        <i class="bi bi-fire"></i> Burn
      </a>
      <a href="customers.php" class="btn btn-outline-secondary btn-sm">
        ← Back
      </a>
    </div>
  </div>

  <!-- WALLET CARDS -->
  <div class="row g-4 mb-4">
    <?php foreach ($wallets as $w):
      $available = (float)$w['balance'] - (float)$w['locked_balance'];
    ?>
      <div class="col-md-4">
        <div class="card ab-card p-4 h-100">
          <div class="fw-bold fs-5"><?= e($w['symbol']) ?></div>
          <div class="ab-muted"><?= e($w['name']) ?></div>

          <div class="mt-3">
            <div class="ab-muted">Available</div>
            <div class="fs-4 fw-bold"><?= number_format($available, 8) ?></div>
          </div>

          <div class="mt-2">
            <div class="ab-muted">Locked</div>
            <div class="fw-semibold text-warning">
              <?= number_format((float)$w['locked_balance'], 8) ?>
            </div>
          </div>

          <hr>
          <div>
            <div class="ab-muted">Total Balance</div>
            <div class="fw-bold">
              <?= number_format((float)$w['balance'], 8) ?>
            </div>
          </div>
        </div>
      </div>
    <?php endforeach; ?>

    <?php if (!$wallets): ?>
      <div class="col-12">
        <div class="card ab-card p-4 text-center ab-muted">
          No crypto wallets for this user.
        </div>
      </div>
    <?php endif; ?>
  </div>

  <!-- TRANSACTIONS -->
  <div class="card ab-card p-4">
    <div class="fw-bold mb-3">Recent Crypto Transactions</div>

    <div class="table-responsive">
      <table class="table align-middle mb-0">
        <thead>
          <tr>
            <th>Ref</th>
            <th>Type</th>
            <th>Asset</th>
            <th>Amount</th>
            <th>Fee</th>
            <th>Total</th>
            <th>Status</th>
            <th>Destination</th>
            <th>Date</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($txns as $t):
          $badge = match ($t['status']) {
            'approved'         => 'success',
            'awaiting_admin'   => 'warning',
            'awaiting_multisig'=> 'info',
            'rejected'         => 'danger',
            default            => 'secondary'
          };
        ?>
          <tr>
            <td class="fw-bold"><?= e($t['ref']) ?></td>
            <td><?= e($t['type']) ?></td>
            <td><?= e($t['symbol']) ?></td>
            <td><?= number_format((float)$t['amount'], 8) ?></td>
            <td><?= number_format((float)$t['fee'], 8) ?></td>
            <td><?= number_format((float)$t['total_debit'], 8) ?></td>
            <td>
              <span class="badge bg-<?= $badge ?>">
                <?= e($t['status']) ?>
              </span>
            </td>
            <td style="max-width:220px;word-break:break-all">
              <?= e($t['destination']) ?>
            </td>
            <td><?= e($t['created_at']) ?></td>
          </tr>
        <?php endforeach; ?>

        <?php if (!$txns): ?>
          <tr>
            <td colspan="9" class="text-center ab-muted py-4">
              No crypto transactions found.
            </td>
          </tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>
</main>

<?php include __DIR__ . '/../../views/partials/foot.php'; ?>
