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

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

/* ===============================
   ADD ADDRESS
================================ */
if (is_post()) {
  csrf_verify();

  $assetId = (int)($_POST['asset_id'] ?? 0);
  $label   = trim($_POST['label'] ?? '');
  $addr    = trim($_POST['address'] ?? '');

  if ($assetId < 1 || !$label || !$addr) {
    flash('err','All fields required.');
    redirect('crypto_addresses.php');
  }

  try {
    $conn->begin_transaction();

    // First address becomes default
    $st = $conn->prepare("
      SELECT COUNT(*) c FROM crypto_addresses
      WHERE user_id=? AND asset_id=?
    ");
    $st->bind_param("ii", $u['id'], $assetId);
    $st->execute();
    $count = (int)$st->get_result()->fetch_assoc()['c'];

    $isDefault = ($count === 0) ? 1 : 0;

    $st = $conn->prepare("
      INSERT INTO crypto_addresses
        (user_id, asset_id, label, address, is_default)
      VALUES (?,?,?,?,?)
    ");
    $st->bind_param("iissi", $u['id'], $assetId, $label, $addr, $isDefault);
    $st->execute();

    $conn->commit();
    flash('msg','Wallet address added.');

  } catch(Throwable $e) {
    $conn->rollback();
    flash('err',$e->getMessage());
  }

  redirect('crypto_addresses.php');
}

/* ===============================
   LOAD DATA
================================ */
$assets = [];
$res = $conn->query("SELECT id,symbol,name FROM crypto_assets WHERE enabled=1 ORDER BY symbol ASC");
while($r=$res->fetch_assoc()) $assets[]=$r;

$rows = [];
$st = $conn->prepare("
  SELECT ca.id, ca.label, ca.address, ca.is_default, a.symbol
  FROM crypto_addresses ca
  JOIN crypto_assets a ON a.id=ca.asset_id
  WHERE ca.user_id=?
  ORDER BY a.symbol ASC, ca.is_default DESC, ca.id DESC
");
$st->bind_param("i", $u['id']);
$st->execute();
$res = $st->get_result();
while($r=$res->fetch_assoc()) $rows[]=$r;

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

<main class="flex-grow-1" style="margin-left:240px">
<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">My Wallet Addresses</h3>
      <div class="ab-muted">Save and manage your external crypto addresses.</div>
    </div>
    <a class="btn btn-outline-secondary" href="crypto_wallet.php">Back</a>
  </div>

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

  <!-- ADD FORM -->
  <div class="card ab-card p-4 mb-4" style="max-width:520px">
    <form method="post">
      <?= csrf_field() ?>

      <label class="form-label">Asset</label>
      <select name="asset_id" class="form-select mb-2" required>
        <?php foreach($assets as $a): ?>
          <option value="<?= (int)$a['id'] ?>">
            <?= e($a['symbol']) ?> — <?= e($a['name']) ?>
          </option>
        <?php endforeach; ?>
      </select>

      <label class="form-label">Label</label>
      <input name="label" class="form-control mb-2" placeholder="e.g. My Binance BTC" required>

      <label class="form-label">Wallet Address</label>
      <input name="address" class="form-control mb-3" placeholder="Paste wallet address" required>

      <button class="btn ab-btn text-white w-100">Add Address</button>
    </form>
  </div>

  <!-- LIST -->
  <div class="card ab-card p-4">
    <h6 class="fw-bold mb-2">Saved Addresses</h6>

    <div class="table-responsive">
      <table class="table align-middle mb-0">
        <thead>
          <tr>
            <th>Asset</th>
            <th>Label</th>
            <th>Address</th>
            <th>Default</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($rows as $r): ?>
          <tr>
            <td class="fw-bold"><?= e($r['symbol']) ?></td>
            <td><?= e($r['label']) ?></td>
            <td style="max-width:300px;word-break:break-all"><?= e($r['address']) ?></td>
            <td>
              <?php if($r['is_default']): ?>
                <span class="badge bg-success">Yes</span>
              <?php else: ?>
                <span class="badge bg-secondary">No</span>
              <?php endif; ?>
            </td>
          </tr>
        <?php endforeach; ?>

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

</div>
</main>

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