<?php
session_start();
require_once 'db.php';

if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit;
}

// ── Handle actions ────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $dep_id = (int)($_POST['dep_id'] ?? 0);
    $action = $_POST['action'] ?? '';

    if ($dep_id && $action === 'approve') {
        // Get deposit info
        $dep = $conn->query("SELECT * FROM deposits WHERE id=$dep_id")->fetch_assoc();
        if ($dep && $dep['status'] === 'pending') {
            $conn->query("UPDATE deposits SET status='approved', approved_at=NOW() WHERE id=$dep_id");
            // Credit security_deposit
            $conn->query("UPDATE users SET security_deposit = security_deposit + {$dep['amount']} WHERE id={$dep['user_id']}");
            // Log
            $desc = $conn->real_escape_string("Deposit approved – " . $dep['method']);
            $conn->query("INSERT INTO account_logs (user_id,type,category,amount,description)
                          VALUES ({$dep['user_id']},'income','deposit_approved',{$dep['amount']},'$desc')");
            $_SESSION['dep_msg'] = ['ok', 'Deposit #' . $dep_id . ' approved and credited.'];
        }
    } elseif ($dep_id && $action === 'reject') {
        $note = $conn->real_escape_string(trim($_POST['reject_note'] ?? ''));
        $conn->query("UPDATE deposits SET status='rejected', reject_note='$note', approved_at=NOW() WHERE id=$dep_id AND status='pending'");
        $_SESSION['dep_msg'] = ['err', 'Deposit #' . $dep_id . ' rejected.'];
    } elseif ($dep_id && $action === 'delete') {
        $conn->query("DELETE FROM deposits WHERE id=$dep_id");
        $_SESSION['dep_msg'] = ['ok', 'Deposit #' . $dep_id . ' deleted.'];
    }

    header('Location: admin_deposits.php');
    exit;
}

// ── Flash ─────────────────────────────────────────────────────
[$ftype, $fmsg] = $_SESSION['dep_msg'] ?? [null, null];
unset($_SESSION['dep_msg']);

// ── Filter ───────────────────────────────────────────────────
$filter = $_GET['filter'] ?? 'all';
$search = trim($_GET['q'] ?? '');
$page   = max(1, (int)($_GET['page'] ?? 1));
$limit  = 20;
$offset = ($page - 1) * $limit;

$where = '1=1';
if ($filter === 'pending')  $where .= " AND d.status='pending'";
if ($filter === 'approved') $where .= " AND d.status='approved'";
if ($filter === 'rejected') $where .= " AND d.status='rejected'";
if ($search !== '') {
    $s = $conn->real_escape_string($search);
    $where .= " AND (u.phone LIKE '%$s%' OR d.method LIKE '%$s%' OR d.account_ref LIKE '%$s%')";
}

// ── Stats ─────────────────────────────────────────────────────
function dep_stat($conn, $status) {
    $r = $conn->query("SELECT COUNT(*) as c, COALESCE(SUM(amount),0) as s FROM deposits WHERE status='$status'")->fetch_assoc();
    return $r;
}
$st_pending  = dep_stat($conn, 'pending');
$st_approved = dep_stat($conn, 'approved');
$st_rejected = dep_stat($conn, 'rejected');

// ── Deposits ─────────────────────────────────────────────────
$total_rows = $conn->query("SELECT COUNT(*) as c FROM deposits d LEFT JOIN users u ON u.id=d.user_id WHERE $where")->fetch_assoc()['c'];
$total_pages = max(1, ceil($total_rows / $limit));

$deps = $conn->query("
    SELECT d.*, u.phone
    FROM deposits d
    LEFT JOIN users u ON u.id = d.user_id
    WHERE $where
    ORDER BY d.created_at DESC
    LIMIT $limit OFFSET $offset
")->fetch_all(MYSQLI_ASSOC);

// Currency
function get_currency($conn) {
    $r = $conn->query("SELECT key_value FROM settings WHERE key_name='currency_symbol'")->fetch_assoc();
    return $r['key_value'] ?? 'TZS';
}
$currency = get_currency($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Manage Deposits – WFM Admin</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
:root{
  --bg:#0d1117;--surface:#161b22;--surface2:#21262d;
  --border:#30363d;--green:#3fb950;--gold:#e3b341;
  --red:#f85149;--blue:#58a6ff;--purple:#bc8cff;
  --text:#e6edf3;--muted:#8b949e;
  --r:10px;
}
body{font-family:'Segoe UI',system-ui,sans-serif;background:var(--bg);color:var(--text);min-height:100vh;display:flex}

/* ── SIDEBAR ── */
.sidebar{
  width:220px;background:var(--surface);border-right:1px solid var(--border);
  min-height:100vh;position:fixed;top:0;left:0;display:flex;flex-direction:column;z-index:100;
}
.sb-logo{padding:20px 18px 16px;border-bottom:1px solid var(--border)}
.sb-logo .brand{font-size:16px;font-weight:800;color:var(--text)}
.sb-logo .sub{font-size:11px;color:var(--muted);margin-top:2px}
.sb-section{padding:12px 0 4px;font-size:10px;font-weight:700;color:var(--muted);
  letter-spacing:1px;text-transform:uppercase;padding-left:18px}
.sb-link{
  display:flex;align-items:center;gap:10px;padding:9px 18px;
  color:var(--muted);font-size:13px;text-decoration:none;
  border-left:3px solid transparent;transition:all .15s;
}
.sb-link:hover{color:var(--text);background:rgba(255,255,255,.04)}
.sb-link.active{color:var(--green);border-left-color:var(--green);background:rgba(63,185,80,.06)}
.sb-link svg{width:16px;height:16px;flex-shrink:0}
.sb-footer{margin-top:auto;padding:14px 18px;border-top:1px solid var(--border)}
.sb-footer a{display:flex;align-items:center;gap:8px;color:var(--muted);font-size:13px;text-decoration:none}
.sb-footer a:hover{color:var(--red)}

/* ── MAIN ── */
.main{margin-left:220px;flex:1;padding:24px}

/* ── TOPBAR ── */
.topbar{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px}
.topbar h1{font-size:20px;font-weight:700;display:flex;align-items:center;gap:8px}
.topbar .date{font-size:13px;color:var(--muted)}

/* ── FLASH ── */
.flash{padding:12px 16px;border-radius:var(--r);margin-bottom:18px;font-size:13px;font-weight:500}
.flash.ok{background:rgba(63,185,80,.1);border:1px solid rgba(63,185,80,.3);color:var(--green)}
.flash.err{background:rgba(248,81,73,.1);border:1px solid rgba(248,81,73,.3);color:var(--red)}

/* ── STAT CARDS ── */
.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:22px}
.stat-card{
  background:var(--surface);border:1px solid var(--border);
  border-radius:var(--r);padding:16px 18px;
  border-top:3px solid var(--border);
}
.stat-card.pending{border-top-color:var(--gold)}
.stat-card.approved{border-top-color:var(--green)}
.stat-card.rejected{border-top-color:var(--red)}
.stat-badge{display:flex;align-items:center;gap:6px;font-size:11px;font-weight:700;
  text-transform:uppercase;letter-spacing:.5px;margin-bottom:10px}
.stat-badge.pending{color:var(--gold)}
.stat-badge.approved{color:var(--green)}
.stat-badge.rejected{color:var(--red)}
.stat-num{font-size:28px;font-weight:800;line-height:1;color:var(--text)}
.stat-amt{font-size:13px;color:var(--muted);margin-top:4px}

/* ── FILTER BAR ── */
.filter-bar{
  background:var(--surface);border:1px solid var(--border);
  border-radius:var(--r);padding:14px 16px;
  display:flex;align-items:center;gap:10px;flex-wrap:wrap;
  margin-bottom:18px;
}
.filter-tabs{display:flex;gap:6px}
.ftab{
  padding:6px 16px;border-radius:20px;font-size:12px;font-weight:700;
  text-decoration:none;color:var(--muted);
  border:1px solid var(--border);background:transparent;transition:all .15s;cursor:pointer;
  font-family:inherit;
}
.ftab.active,.ftab:hover{background:var(--green);color:#000;border-color:var(--green)}
.search-wrap{display:flex;gap:8px;margin-left:auto}
.search-input{
  padding:7px 12px;border-radius:8px;border:1px solid var(--border);
  background:var(--surface2);color:var(--text);font-size:13px;
  font-family:inherit;outline:none;width:220px;
}
.search-input:focus{border-color:var(--blue)}
.search-btn{
  padding:7px 16px;border-radius:8px;background:var(--blue);color:#000;
  border:none;font-size:13px;font-weight:700;cursor:pointer;
  display:flex;align-items:center;gap:6px;font-family:inherit;
}

/* ── TABLE ── */
.table-wrap{
  background:var(--surface);border:1px solid var(--border);
  border-radius:var(--r);overflow:hidden;
}
.table-head{
  padding:14px 18px;border-bottom:1px solid var(--border);
  display:flex;align-items:center;justify-content:space-between;
}
.table-head h2{font-size:15px;font-weight:700}
.table-meta{font-size:12px;color:var(--muted)}
table{width:100%;border-collapse:collapse;font-size:13px}
thead tr{background:var(--surface2)}
th{
  padding:10px 14px;text-align:left;font-size:11px;font-weight:700;
  color:var(--muted);text-transform:uppercase;letter-spacing:.5px;
  white-space:nowrap;border-bottom:1px solid var(--border);
}
td{padding:12px 14px;border-bottom:1px solid rgba(48,54,61,.5);vertical-align:middle}
tr:last-child td{border-bottom:none}
tr:hover td{background:rgba(255,255,255,.02)}

/* ── PROOF IMAGE ── */
.proof-thumb{
  width:48px;height:48px;border-radius:6px;
  object-fit:cover;border:2px solid var(--border);
  cursor:pointer;display:block;
  transition:border-color .15s,transform .15s;
  background:var(--surface2);
}
.proof-thumb:hover{border-color:var(--blue);transform:scale(1.05)}
.proof-broken{
  width:48px;height:48px;border-radius:6px;
  background:var(--surface2);border:2px dashed var(--border);
  display:flex;align-items:center;justify-content:center;
  color:var(--muted);font-size:9px;text-align:center;line-height:1.3;
  font-weight:600;
}
.proof-pdf{
  width:48px;height:48px;border-radius:6px;
  background:rgba(248,81,73,.1);border:2px solid rgba(248,81,73,.3);
  display:flex;flex-direction:column;align-items:center;justify-content:center;
  color:var(--red);font-size:9px;font-weight:700;cursor:pointer;
  transition:all .15s;gap:2px;
}
.proof-pdf:hover{background:rgba(248,81,73,.2)}
.proof-pdf svg{width:18px;height:18px;fill:var(--red)}

/* ── STATUS BADGE ── */
.badge{display:inline-block;padding:3px 10px;border-radius:20px;
  font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.4px;white-space:nowrap}
.badge.pending{background:rgba(227,179,65,.15);color:var(--gold);border:1px solid rgba(227,179,65,.3)}
.badge.approved{background:rgba(63,185,80,.12);color:var(--green);border:1px solid rgba(63,185,80,.25)}
.badge.rejected{background:rgba(248,81,73,.12);color:var(--red);border:1px solid rgba(248,81,73,.25)}

/* ── ACTION BUTTONS ── */
.btn-approve{
  padding:5px 12px;border-radius:6px;background:var(--green);color:#000;
  font-size:12px;font-weight:700;border:none;cursor:pointer;font-family:inherit;
  display:inline-flex;align-items:center;gap:5px;
}
.btn-reject{
  padding:5px 12px;border-radius:6px;background:transparent;color:var(--red);
  font-size:12px;font-weight:700;border:1px solid var(--red);cursor:pointer;font-family:inherit;
  display:inline-flex;align-items:center;gap:5px;
}
.btn-del{
  padding:5px 8px;border-radius:6px;background:transparent;color:var(--muted);
  font-size:12px;border:1px solid var(--border);cursor:pointer;font-family:inherit;
}
.btn-approve:hover{opacity:.85}
.btn-reject:hover{background:rgba(248,81,73,.1)}
.btn-del:hover{color:var(--red);border-color:var(--red)}
.actions-cell{display:flex;align-items:center;gap:6px;flex-wrap:nowrap}

.user-phone{font-weight:700;color:var(--text);font-size:13px}
.user-id{font-size:11px;color:var(--muted)}
.amount-val{font-weight:800;font-size:14px;color:var(--green)}
.amount-cur{font-size:11px;color:var(--muted)}

/* ── PAGINATION ── */
.pagination{display:flex;align-items:center;gap:6px;padding:14px 18px;border-top:1px solid var(--border)}
.pag-btn{
  padding:5px 12px;border-radius:6px;font-size:12px;font-weight:600;
  text-decoration:none;color:var(--muted);border:1px solid var(--border);
  background:transparent;transition:all .15s;
}
.pag-btn.active,.pag-btn:hover{background:var(--blue);color:#000;border-color:var(--blue)}
.pag-info{font-size:12px;color:var(--muted);margin-left:auto}

/* ── LIGHTBOX ── */
.lightbox{
  display:none;position:fixed;inset:0;background:rgba(0,0,0,.92);
  z-index:9999;align-items:center;justify-content:center;flex-direction:column;gap:14px;
}
.lightbox.open{display:flex}
.lightbox img{
  max-width:90vw;max-height:82vh;
  border-radius:10px;border:2px solid var(--border);
  object-fit:contain;background:#111;
}
.lb-close{
  position:absolute;top:18px;right:22px;
  background:rgba(255,255,255,.1);border:none;color:#fff;
  font-size:24px;width:40px;height:40px;border-radius:50%;
  cursor:pointer;display:flex;align-items:center;justify-content:center;
  transition:background .15s;
}
.lb-close:hover{background:rgba(248,81,73,.4)}
.lb-filename{color:rgba(255,255,255,.55);font-size:12px}
.lb-open-link{
  padding:6px 16px;border-radius:20px;background:var(--blue);
  color:#000;font-size:12px;font-weight:700;text-decoration:none;
}

/* ── REJECT MODAL ── */
.modal-overlay{
  display:none;position:fixed;inset:0;background:rgba(0,0,0,.7);
  z-index:8000;align-items:center;justify-content:center;
}
.modal-overlay.open{display:flex}
.modal{
  background:var(--surface);border:1px solid var(--border);
  border-radius:14px;padding:24px;width:360px;
}
.modal h3{font-size:16px;font-weight:700;margin-bottom:14px}
.modal textarea{
  width:100%;padding:10px 12px;background:var(--surface2);
  border:1px solid var(--border);border-radius:8px;color:var(--text);
  font-size:13px;font-family:inherit;resize:none;height:90px;outline:none;margin-bottom:14px;
}
.modal-btns{display:flex;gap:10px;justify-content:flex-end}
.modal-cancel{
  padding:8px 18px;border-radius:8px;background:transparent;
  color:var(--muted);border:1px solid var(--border);cursor:pointer;font-family:inherit;font-size:13px;
}
.modal-confirm{
  padding:8px 18px;border-radius:8px;background:var(--red);
  color:#fff;border:none;cursor:pointer;font-family:inherit;font-size:13px;font-weight:700;
}
</style>
</head>
<body>

<!-- ── SIDEBAR ── -->
<aside class="sidebar">
  <div class="sb-logo">
    <div class="brand">WFM Admin</div>
    <div class="sub">Finance Panel</div>
  </div>

  <div class="sb-section">Finance</div>
  <a href="admin_deposits.php" class="sb-link active">
    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z" transform="rotate(90,12,12)"/></svg>
    Deposits
  </a>
  <a href="admin_withdrawals.php" class="sb-link">
    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z" transform="rotate(-90,12,12)"/></svg>
    Withdrawals
  </a>
  <a href="admin_payment_methods.php" class="sb-link">
    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M20 4H4c-1.11 0-2 .89-2 2v12c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4v-6h16v6zm0-10H4V6h16v2z"/></svg>
    Payment Methods
  </a>
  <a href="admin_finance_settings.php" class="sb-link">
    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M19.14 12.94c.04-.3.06-.61.06-.94s-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/></svg>
    Finance Settings
  </a>

  <div class="sb-section">System</div>
  <a href="admin_dashboard.php" class="sb-link">
    <svg viewBox="0 0 24 24" fill="currentColor"><path d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z"/></svg>
    Dashboard
  </a>

  <div class="sb-footer">
    <a href="admin_logout.php">
      <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M17 7l-1.41 1.41L18.17 11H8v2h10.17l-2.58 2.58L17 17l5-5-5-5zM4 5h8V3H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8v-2H4V5z"/></svg>
      Logout
    </a>
  </div>
</aside>

<!-- ── MAIN ── -->
<main class="main">
  <div class="topbar">
    <h1>💰 Manage Deposits</h1>
    <span class="date"><?= date('d M Y, H:i') ?></span>
  </div>

  <?php if ($fmsg): ?>
  <div class="flash <?= $ftype ?>"><?= htmlspecialchars($fmsg) ?></div>
  <?php endif; ?>

  <!-- Stats -->
  <div class="stats">
    <div class="stat-card pending">
      <div class="stat-badge pending">⬆ Pending</div>
      <div class="stat-num"><?= $st_pending['c'] ?></div>
      <div class="stat-amt"><?= number_format($st_pending['s'],2) ?> <?= $currency ?></div>
    </div>
    <div class="stat-card approved">
      <div class="stat-badge approved">✅ Approved</div>
      <div class="stat-num"><?= $st_approved['c'] ?></div>
      <div class="stat-amt"><?= number_format($st_approved['s'],2) ?> <?= $currency ?></div>
    </div>
    <div class="stat-card rejected">
      <div class="stat-badge rejected">✕ Rejected</div>
      <div class="stat-num"><?= $st_rejected['c'] ?></div>
      <div class="stat-amt"><?= number_format($st_rejected['s'],2) ?> <?= $currency ?></div>
    </div>
  </div>

  <!-- Filter bar -->
  <form method="GET" action="admin_deposits.php">
    <div class="filter-bar">
      <div class="filter-tabs">
        <?php foreach (['all'=>'All','pending'=>'Pending','approved'=>'Approved','rejected'=>'Rejected'] as $k=>$v): ?>
        <a href="?filter=<?= $k ?>&q=<?= urlencode($search) ?>"
           class="ftab <?= $filter===$k?'active':'' ?>"><?= $v ?></a>
        <?php endforeach; ?>
      </div>
      <div class="search-wrap">
        <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
        <input type="text" name="q" class="search-input"
               placeholder="Search phone, method, account..."
               value="<?= htmlspecialchars($search) ?>">
        <button type="submit" class="search-btn">
          <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M21 21l-4.35-4.35M17 11A6 6 0 1 1 5 11a6 6 0 0 1 12 0z" stroke="currentColor" stroke-width="2" fill="none"/></svg>
          Search
        </button>
      </div>
    </div>
  </form>

  <!-- Table -->
  <div class="table-wrap">
    <div class="table-head">
      <h2>Deposit Requests</h2>
      <span class="table-meta"><?= $total_rows ?> total · page <?= $page ?>/<?= $total_pages ?></span>
    </div>
    <div style="overflow-x:auto">
    <table>
      <thead>
        <tr>
          <th>#ID</th>
          <th>User</th>
          <th>Amount</th>
          <th>Method</th>
          <th>From Account</th>
          <th>Proof</th>
          <th>Date</th>
          <th>Status</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($deps)): ?>
        <tr><td colspan="9" style="text-align:center;color:var(--muted);padding:30px">No deposits found.</td></tr>
        <?php endif; ?>
        <?php foreach ($deps as $d):
          $proof_raw = $d['proof_path'] ?? '';

          // ── Resolve the correct web-accessible URL ──────────────
          // DB stores:  uploads/proofs/dep_1_xxx.jpg
          //             OR  ./uploads/proofs/dep_1_xxx.jpg
          // Server:     public_html/hacker/uploads/proofs/dep_1_xxx.jpg
          // Web URL:    /hacker/uploads/proofs/dep_1_xxx.jpg
          $proof_rel = ltrim($proof_raw, './');          // strip ./ prefix
          // If path already contains the subfolder name, just prepend /hacker/
          // If it somehow already starts with hacker/, keep as-is
          if (str_starts_with($proof_rel, 'hacker/')) {
              $proof_url = '/' . $proof_rel;
          } else {
              $proof_url = '/hacker/' . $proof_rel;
          }

          $ext       = strtolower(pathinfo($proof_raw, PATHINFO_EXTENSION));
          $is_pdf    = ($ext === 'pdf');
          $has_proof = !empty($proof_raw);
        ?>
        <tr>
          <td style="color:var(--muted);font-weight:700">#<?= $d['id'] ?></td>
          <td>
            <div class="user-phone">User #<?= $d['user_id'] ?></div>
            <div class="user-id"><?= htmlspecialchars($d['phone'] ?? '—') ?></div>
          </td>
          <td>
            <div class="amount-val">+<?= number_format($d['amount'],2) ?></div>
            <div class="amount-cur"><?= $currency ?></div>
          </td>
          <td><?= htmlspecialchars($d['method']) ?></td>
          <td style="color:var(--muted)"><?= htmlspecialchars($d['account_ref'] ?: '—') ?></td>
          <td>
            <?php if (!$has_proof): ?>
              <div class="proof-broken">No<br>Proof</div>
            <?php elseif ($is_pdf): ?>
              <a href="<?= htmlspecialchars($proof_url) ?>" target="_blank" class="proof-pdf" title="Open PDF">
                <svg viewBox="0 0 24 24"><path d="M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6zm4 18H6V4h7v5h5v11z"/></svg>
                PDF
              </a>
            <?php else: ?>
              <!-- Clickable image thumbnail → opens lightbox -->
              <img class="proof-thumb"
                   src="<?= htmlspecialchars($proof_url) ?>"
                   alt="Proof"
                   data-src="<?= htmlspecialchars($proof_url) ?>"
                   data-name="<?= htmlspecialchars(basename($proof_raw)) ?>"
                   onclick="openLightbox(this)"
                   onerror="this.outerHTML='<div class=\'proof-broken\'>Not<br>Found</div>'">
            <?php endif; ?>
          </td>
          <td style="white-space:nowrap">
            <div><?= date('d M Y', strtotime($d['created_at'])) ?></div>
            <div style="font-size:11px;color:var(--muted)"><?= date('H:i', strtotime($d['created_at'])) ?></div>
          </td>
          <td><span class="badge <?= $d['status'] ?>"><?= ucfirst($d['status']) ?></span></td>
          <td>
            <div class="actions-cell">
              <?php if ($d['status'] === 'pending'): ?>
              <form method="POST" style="margin:0" onsubmit="return confirm('Approve this deposit?')">
                <input type="hidden" name="dep_id" value="<?= $d['id'] ?>">
                <input type="hidden" name="action" value="approve">
                <button type="submit" class="btn-approve">✓ Approve</button>
              </form>
              <button type="button" class="btn-reject"
                      onclick="openReject(<?= $d['id'] ?>)">✕ Reject</button>
              <?php endif; ?>
              <form method="POST" style="margin:0" onsubmit="return confirm('Delete this record?')">
                <input type="hidden" name="dep_id" value="<?= $d['id'] ?>">
                <input type="hidden" name="action" value="delete">
                <button type="submit" class="btn-del" title="Delete">🗑</button>
              </form>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
    <div class="pagination">
      <?php for ($i = 1; $i <= $total_pages; $i++): ?>
      <a href="?filter=<?= $filter ?>&q=<?= urlencode($search) ?>&page=<?= $i ?>"
         class="pag-btn <?= $i===$page?'active':'' ?>"><?= $i ?></a>
      <?php endfor; ?>
      <span class="pag-info">Page <?= $page ?> of <?= $total_pages ?></span>
    </div>
    <?php endif; ?>
  </div>
</main>

<!-- ── LIGHTBOX ── -->
<div class="lightbox" id="lightbox" onclick="closeLightbox(event)">
  <button class="lb-close" onclick="closeLightbox()">✕</button>
  <img id="lbImg" src="" alt="Proof screenshot">
  <div style="display:flex;align-items:center;gap:14px">
    <span class="lb-filename" id="lbName"></span>
    <a id="lbLink" href="#" target="_blank" class="lb-open-link">Open full size ↗</a>
  </div>
</div>

<!-- ── REJECT MODAL ── -->
<div class="modal-overlay" id="rejectModal">
  <div class="modal" onclick="event.stopPropagation()">
    <h3>Reject Deposit</h3>
    <form method="POST" id="rejectForm">
      <input type="hidden" name="dep_id" id="rejectDepId">
      <input type="hidden" name="action" value="reject">
      <textarea name="reject_note" placeholder="Reason for rejection (optional)..."></textarea>
      <div class="modal-btns">
        <button type="button" class="modal-cancel" onclick="closeReject()">Cancel</button>
        <button type="submit" class="modal-confirm">Reject</button>
      </div>
    </form>
  </div>
</div>

<script>
// ── Lightbox ──
function openLightbox(img) {
  const src  = img.dataset.src || img.src;
  const name = img.dataset.name || 'proof';
  document.getElementById('lbImg').src  = src;
  document.getElementById('lbName').textContent = name;
  document.getElementById('lbLink').href = src;
  document.getElementById('lightbox').classList.add('open');
  document.body.style.overflow = 'hidden';
}
function closeLightbox(e) {
  if (e && e.target !== e.currentTarget && !e.target.classList.contains('lb-close')) return;
  document.getElementById('lightbox').classList.remove('open');
  document.body.style.overflow = '';
}
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeLightbox(); });

// ── Reject modal ──
function openReject(id) {
  document.getElementById('rejectDepId').value = id;
  document.getElementById('rejectModal').classList.add('open');
}
function closeReject() {
  document.getElementById('rejectModal').classList.remove('open');
}
document.getElementById('rejectModal').addEventListener('click', function(e) {
  if (e.target === this) closeReject();
});
</script>

</body>
</html>