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

$conn = require __DIR__ . '/../../app/config/database.php';
require_login();
$u = current_user();

$wallets = [];
$st = $conn->prepare("
  SELECT cw.user_id, 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", $u['id']);
$st->execute();
$res = $st->get_result();
while($r=$res->fetch_assoc()) $wallets[]=$r;

$rows = [];
$st = $conn->prepare("
  SELECT ct.ref, ct.type, ct.amount, ct.fee, ct.total_debit, ct.status, 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 20
");
$st->bind_param("i", $u['id']);
$st->execute();
$res = $st->get_result();
while($r=$res->fetch_assoc()) $rows[]=$r;

$faucet = faucet_settings($conn);

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

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

  <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">Balances, fiat value (USD/GHS), faucet demo, and activity.</div>
    </div>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-secondary" href="dashboard.php"><i class="bi bi-arrow-left"></i></a>
      <a class="btn ab-btn text-white" href="crypto.php"><i class="bi bi-send me-1"></i>Send Crypto</a>
    </div>
  </div>

  <?php if($m=flash('msg')): ?><div class="alert alert-success ab-card"><?= e($m) ?></div><?php endif; ?>
  <?php if($m=flash('err')): ?><div class="alert alert-danger ab-card"><?= e($m) ?></div><?php endif; ?>

  <div class="row g-4">
    <?php foreach($wallets as $w):
      $available = (float)$w['balance'] - (float)$w['locked_balance'];
      $rate = crypto_rate($conn, (int)$w['asset_id']);
      $usdVal = $available * (float)$rate['usd'];
      $ghsVal = $available * (float)$rate['ghs'];
    ?>
      <div class="col-md-4">
        <div class="card ab-card p-4 h-100">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <div class="fw-bold fs-5"><?= e($w['symbol']) ?></div>
              <div class="ab-muted"><?= e($w['name']) ?></div>
            </div>
            <i class="bi bi-currency-bitcoin fs-2" style="color:var(--ab-accent)"></i>
          </div>

          <div class="mt-3">
            <div class="ab-muted">Available</div>
            <div class="fs-4 fw-bold"><?= number_format($available,8) ?></div>
            <div class="ab-muted" style="font-size:12px;">
              ≈ $<?= number_format($usdVal,2) ?> • ₵<?= number_format($ghsVal,2) ?>
            </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 class="d-flex gap-2 flex-wrap">
            <?php if($faucet['enabled']): ?>
              <form method="post" action="crypto_faucet.php" class="m-0">
                <?= csrf_field() ?>
                <input type="hidden" name="asset_id" value="<?= (int)$w['asset_id'] ?>">
                <button class="btn btn-outline-primary btn-sm">
                  <i class="bi bi-droplet me-1"></i>Faucet
                </button>
              </form>
            <?php endif; ?>
            <a class="btn btn-outline-secondary btn-sm" href="crypto.php">Send</a>
          </div>

        </div>
      </div>
    <?php endforeach; ?>

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

  <div class="card ab-card p-4 mt-4">
    <div class="fw-bold mb-2">Recent Activity</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>Status</th><th>Date</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($rows as $r):
          $badge = match ($r['status']) {
            'approved' => 'success',
            'awaiting_admin' => 'warning',
            'otp_pending' => 'info',
            'rejected' => 'danger',
            default => 'secondary'
          };
        ?>
          <tr>
            <td class="fw-bold"><?= e($r['ref']) ?></td>
            <td><?= e($r['type']) ?></td>
            <td><?= e($r['symbol']) ?></td>
            <td><?= number_format((float)$r['amount'],8) ?></td>
            <td><?= number_format((float)$r['fee'],8) ?></td>
            <td><span class="badge bg-<?= $badge ?>"><?= e($r['status']) ?></span></td>
            <td><?= e($r['created_at']) ?></td>
          </tr>
        <?php endforeach; ?>

        <?php if(!$rows): ?>
          <tr><td colspan="7" class="text-center ab-muted py-4">No activity yet.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>
</main>

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