<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/helpers/banking.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();

/* ===============================
   APPROVE / REJECT REQUEST
================================ */
if (is_post() && isset($_POST['request_id'], $_POST['action'])) {
    csrf_verify();

    $requestId = (int)$_POST['request_id'];
    $action    = trim($_POST['action']);

    /* Load pending request */
    $st = $conn->prepare("
        SELECT *
        FROM card_requests
        WHERE id = ? AND status = 'pending'
        LIMIT 1
    ");
    $st->bind_param("i", $requestId);          // ✅ 1 type, 1 var
    $st->execute();
    $req = $st->get_result()->fetch_assoc();

    if (!$req) {
        flash('err', 'Request not found or already processed.');
        redirect('card_requests.php');
    }

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

        /* Load user name SAFELY */
        $uid = (int)$req['user_id'];
        $u = $conn->prepare("SELECT full_name FROM users WHERE id = ?");
        $u->bind_param("i", $uid);              // ✅ 1 type, 1 var
        $u->execute();
        $ur = $u->get_result()->fetch_assoc();

        $cardholder = !empty($ur['full_name'])
            ? strtoupper($ur['full_name'])
            : 'ASTRABANK CUSTOMER';

        /* Generate virtual card */
        generate_virtual_card(
            $conn,
            (int)$req['user_id'],
            (int)$req['id'],
            (string)$req['network'],
            $cardholder
        );

        /* Update request */
        $status = 'approved';
        $adminId = (int)$admin['id'];

        $up = $conn->prepare("
            UPDATE card_requests
            SET status = ?, reviewed_by = ?, reviewed_at = NOW()
            WHERE id = ?
        ");
        $up->bind_param("sii", $status, $adminId, $requestId);  // ✅ 3 types, 3 vars
        $up->execute();

        flash('msg', 'Card request approved.');
    }

    /* ---------- REJECT ---------- */
    if ($action === 'reject') {
        $status = 'rejected';
        $adminId = (int)$admin['id'];

        $up = $conn->prepare("
            UPDATE card_requests
            SET status = ?, reviewed_by = ?, reviewed_at = NOW()
            WHERE id = ?
        ");
        $up->bind_param("sii", $status, $adminId, $requestId);  // ✅ 3 types, 3 vars
        $up->execute();

        flash('msg', 'Card request rejected.');
    }

    redirect('card_requests.php');
}

/* ===============================
   LOAD PENDING REQUESTS
================================ */
$rows = [];
$res = $conn->query("
    SELECT cr.*, u.email
    FROM card_requests cr
    JOIN users u ON u.id = cr.user_id
    WHERE cr.status = 'pending'
    ORDER BY cr.created_at DESC
");
while ($r = $res->fetch_assoc()) $rows[] = $r;

$title = 'Card Requests';
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">Virtual Card Requests</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>Network</th>
  <th>Tier</th>
  <th>Note</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><?= strtoupper(e($r['network'])) ?></td>
  <td><?= strtoupper(e($r['tier'])) ?></td>
  <td><?= e($r['note'] ?? '-') ?></td>
  <td><?= e($r['created_at']) ?></td>
  <td class="text-end">
    <form method="post" class="d-inline">
      <?= csrf_field() ?>
      <input type="hidden" name="request_id" value="<?= (int)$r['id'] ?>">
      <button name="action" value="approve" class="btn btn-sm btn-success">
        Approve
      </button>
    </form>

    <form method="post" class="d-inline ms-1">
      <?= csrf_field() ?>
      <input type="hidden" name="request_id" value="<?= (int)$r['id'] ?>">
      <button name="action" value="reject" 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 pending card requests
  </td>
</tr>
<?php endif; ?>

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

</div>

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