<?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();

if (is_post()) {
  csrf_verify();
  $assetId = (int)($_POST['asset_id'] ?? 0);
  $amount  = (float)($_POST['amount'] ?? 0);
  $mode    = trim($_POST['mode'] ?? 'add'); // add|remove

  cold_reserve_ensure($conn, $assetId);

  try {
    $conn->begin_transaction();
    $st = $conn->prepare("SELECT balance FROM crypto_cold_reserve WHERE asset_id=? FOR UPDATE");
    $st->bind_param("i", $assetId);
    $st->execute();
    $r = $st->get_result()->fetch_assoc();
    $bal = (float)($r['balance'] ?? 0);

    if ($mode === 'remove' && $bal < $amount) {
      $conn->rollback();
      throw new Exception('Not enough reserve to remove.');
    }

    $newBal = ($mode === 'add') ? ($bal + $amount) : ($bal - $amount);

    $up = $conn->prepare("UPDATE crypto_cold_reserve SET balance=? WHERE asset_id=?");
    $up->bind_param("di", $newBal, $assetId);
    $up->execute();

    $conn->commit();
    flash('msg','Reserve updated.');
  } catch(Throwable $e) {
    $conn->rollback();
    flash('err',$e->getMessage());
  }

  redirect('crypto_reserve.php');
}

$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 = [];
$res = $conn->query("
  SELECT a.id asset_id, a.symbol, a.name, cr.balance, cr.updated_at
  FROM crypto_assets a
  LEFT JOIN crypto_cold_reserve cr ON cr.asset_id=a.id
  WHERE a.enabled=1
  ORDER BY a.symbol ASC
");
while($r=$res->fetch_assoc()) $rows[]=$r;

$title='Cold Reserve';
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">

  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <h3 class="fw-bold mb-0">Cold Wallet Reserve</h3>
      <div class="ab-muted">Platform reserve per asset.</div>
    </div>
    <a class="btn btn-outline-secondary" href="crypto_admin_dashboard.php">Back</a>
  </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="card ab-card p-4 mb-4">
    <form method="post" class="row g-3">
      <?= csrf_field() ?>
      <div class="col-md-4">
        <label class="form-label">Asset</label>
        <select name="asset_id" class="form-select" required>
          <?php foreach($assets as $a): ?>
            <option value="<?= (int)$a['id'] ?>"><?= e($a['symbol']) ?> — <?= e($a['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">Mode</label>
        <select name="mode" class="form-select">
          <option value="add">Add</option>
          <option value="remove">Remove</option>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">Amount</label>
        <input name="amount" type="number" step="0.00000001" class="form-control" required>
      </div>
      <div class="col-12">
        <button class="btn ab-btn text-white">Update Reserve</button>
      </div>
    </form>
  </div>

  <div class="card ab-card p-3">
    <div class="table-responsive">
      <table class="table align-middle mb-0">
        <thead><tr><th>Asset</th><th>Reserve Balance</th><th>Updated</th></tr></thead>
        <tbody>
          <?php foreach($rows as $r): ?>
            <tr>
              <td class="fw-bold"><?= e($r['symbol']) ?> <span class="ab-muted"><?= e($r['name']) ?></span></td>
              <td><?= number_format((float)($r['balance'] ?? 0), 8) ?></td>
              <td><?= e($r['updated_at'] ?? '-') ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>
</main>

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