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

if (is_post()) {
  csrf_verify();
  $assetId = (int)($_POST['asset_id'] ?? 0);
  $usd = (float)($_POST['rate_usd'] ?? 0);
  $ghs = (float)($_POST['rate_ghs'] ?? 0);

  $st = $conn->prepare("
    INSERT INTO crypto_rates (asset_id, rate_usd, rate_ghs)
    VALUES (?, ?, ?)
    ON DUPLICATE KEY UPDATE rate_usd=VALUES(rate_usd), rate_ghs=VALUES(rate_ghs), updated_at=NOW()
  ");
  $st->bind_param("idd", $assetId, $usd, $ghs);
  $st->execute();

  flash('msg','Rates updated.');
  redirect('crypto_rates.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 AS asset_id, a.symbol, a.name, r.rate_usd, r.rate_ghs, r.updated_at
  FROM crypto_assets a
  LEFT JOIN crypto_rates r ON r.asset_id=a.id
  WHERE a.enabled=1
  ORDER BY a.symbol ASC
");
while ($r = $res->fetch_assoc()) $rows[] = $r;

$title='Crypto Rates';
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">Exchange Rates</h3>
      <div class="ab-muted">Set asset value in USD and GHS.</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; ?>

  <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">Rate (USD)</label>
        <input name="rate_usd" type="number" step="0.00000001" class="form-control" required>
      </div>
      <div class="col-md-4">
        <label class="form-label">Rate (GHS)</label>
        <input name="rate_ghs" type="number" step="0.00000001" class="form-control" required>
      </div>
      <div class="col-12">
        <button class="btn ab-btn text-white">Save Rates</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>USD</th><th>GHS</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><?= e((string)($r['rate_usd'] ?? 0)) ?></td>
              <td><?= e((string)($r['rate_ghs'] ?? 0)) ?></td>
              <td><?= e($r['updated_at'] ?? '-') ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>
</main>

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