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

session_boot();
require_login();

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

$admin = current_user();

/* ===============================
   HANDLE APPROVE / REJECT
================================ */
if (is_post()) {
    csrf_verify();

    $txId   = (int)($_POST['tx_id'] ?? 0);
    $action = $_POST['action'] ?? '';

    /* Load transaction awaiting admin */
    $st = $conn->prepare("
        SELECT *
        FROM crypto_txn
        WHERE id = ?
          AND status = 'pending_admin'
        LIMIT 1
    ");
    $st->bind_param("i", $txId);
    $st->execute();
    $tx = $st->get_result()->fetch_assoc();

    if (!$tx) {
        flash('err', 'Transaction not found or already reviewed');
        redirect('crypto_approvals.php');
    }

    /* ---------- APPROVE ---------- */
    if ($action === 'approve') {

        $conn->begin_transaction();

        try {
            /* Lock wallet */
            $st = $conn->prepare("
                SELECT *
                FROM crypto_wallets
                WHERE user_id = ? AND asset_id = ?
                FOR UPDATE
            ");
            $st->bind_param("ii", $tx['user_id'], $tx['asset_id']);
            $st->execute();
            $wallet = $st->get_result()->fetch_assoc();

            if (!$wallet || $wallet['balance'] < $tx['amount']) {
                throw new Exception('Insufficient wallet balance');
            }

            /* Debit wallet */
            $st = $conn->prepare("
                UPDATE crypto_wallets
                SET balance = balance - ?
                WHERE id = ?
            ");
            $st->bind_param("di", $tx['amount'], $wallet['id']);
            $st->execute();

            /* Mark approved */
            $st = $conn->prepare("
                UPDATE crypto_txn
                SET
                    status = 'posted',
                    decision = 'approved',
                    reviewed_by = ?,
                    reviewed_at = NOW()
                WHERE id = ?
            ");
            $st->bind_param("ii", $admin['id'], $txId);
            $st->execute();

            /* Audit */
            $meta = json_encode([
                'tx_id' => $txId,
                'ref'   => $tx['ref'],
                'amount'=> $tx['amount']
            ]);

            $a = $conn->prepare("
                INSERT INTO audit_logs (actor_id, action, meta, ip)
                VALUES (?, 'CRYPTO_APPROVED', ?, ?)
            ");
            $ip = client_ip();
            $a->bind_param("iss", $admin['id'], $meta, $ip);
            $a->execute();

            $conn->commit();
            flash('msg', 'Transaction approved successfully');

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

    /* ---------- REJECT ---------- */
    if ($action === 'reject') {

        $st = $conn->prepare("
            UPDATE crypto_txn
            SET
                status = 'rejected',
                decision = 'rejected',
                reviewed_by = ?,
                reviewed_at = NOW()
            WHERE id = ?
        ");
        $st->bind_param("ii", $admin['id'], $txId);
        $st->execute();

        flash('msg', 'Transaction rejected');
    }

    redirect('crypto_approvals.php');
}

/* ===============================
   LOAD PENDING ADMIN TXNS
================================ */
$rows = [];
$res = $conn->query("
    SELECT ct.*, u.email, ca.symbol
    FROM crypto_txn ct
    JOIN users u ON u.id = ct.user_id
    JOIN crypto_assets ca ON ca.id = ct.asset_id
    WHERE ct.status = 'pending_admin'
    ORDER BY ct.created_at DESC
");
while ($r = $res->fetch_assoc()) {
    $rows[] = $r;
}

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

<div class="container-fluid py-4">

<h3 class="fw-bold mb-3">Crypto Transactions Awaiting Approval</h3>

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

<div class="card ab-card p-3">
<div class="table-responsive">
<table class="table align-middle mb-0">
<thead>
<tr>
  <th>User</th>
  <th>Asset</th>
  <th>Amount</th>
  <th>Destination</th>
  <th>Date</th>
  <th class="text-end">Action</th>
</tr>
</thead>
<tbody>

<?php foreach ($rows as $r): ?>
<tr>
  <td><?= e($r['email']) ?></td>
  <td><?= e($r['symbol']) ?></td>
  <td><?= number_format((float)$r['amount'], 8) ?></td>
  <td class="text-muted"><?= e($r['destination']) ?></td>
  <td><?= e($r['created_at']) ?></td>
  <td class="text-end">

    <form method="post" class="d-inline">
      <?= csrf_field() ?>
      <input type="hidden" name="tx_id" value="<?= (int)$r['id'] ?>">
      <input type="hidden" name="action" value="approve">
      <button class="btn btn-sm btn-success">Approve</button>
    </form>

    <form method="post" class="d-inline ms-1">
      <?= csrf_field() ?>
      <input type="hidden" name="tx_id" value="<?= (int)$r['id'] ?>">
      <input type="hidden" name="action" value="reject">
      <button class="btn btn-sm btn-danger">Reject</button>
    </form>

  </td>
</tr>
<?php endforeach; ?>

<?php if (!$rows): ?>
<tr>
  <td colspan="6" class="text-center text-muted py-4">
    No transactions awaiting admin approval
  </td>
</tr>
<?php endif; ?>

</tbody>
</table>
</div>
</div>

</div>

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