<?php
require_once 'db.php';

$msg = ''; $msg_type = 'ok';

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

    if ($action === 'approve' && $wd_id) {
        $wd = $conn->query("SELECT * FROM withdrawals WHERE id={$wd_id} LIMIT 1")->fetch_assoc();
        if ($wd && $wd['status'] === 'pending') {
            // Balance was already deducted on submission — just mark approved
            $conn->query("UPDATE withdrawals SET status='approved', updated_at=NOW() WHERE id={$wd_id}");
            $uid = (int)$wd['user_id'];
            $net = (float)$wd['net_amount'];
            $desc = $conn->real_escape_string("Withdrawal approved – {$wd['method']} → {$wd['account_ref']}");
            $conn->query("INSERT INTO account_logs (user_id,type,category,amount,description)
                          VALUES ({$uid},'expense','withdraw',{$net},'{$desc}')");
            $msg = "Withdrawal #{$wd_id} approved. {$net} {$wd['method']} to {$wd['account_ref']}.";
        } else {
            $msg = 'Withdrawal not found or already processed.'; $msg_type = 'err';
        }
    }

    elseif ($action === 'reject' && $wd_id) {
        $note = $conn->real_escape_string(trim($_POST['admin_note'] ?? ''));
        $wd   = $conn->query("SELECT * FROM withdrawals WHERE id={$wd_id} LIMIT 1")->fetch_assoc();
        if ($wd && $wd['status'] === 'pending') {
            $uid    = (int)$wd['user_id'];
            $amount = (float)$wd['amount'];
            $conn->begin_transaction();
            try {
                // Refund balance back to user
                $conn->query("UPDATE users SET balance = balance + {$amount} WHERE id={$uid}");
                $conn->query("UPDATE withdrawals SET status='rejected', admin_note='{$note}', updated_at=NOW() WHERE id={$wd_id}");
                $desc_e = $conn->real_escape_string("Withdrawal #{$wd_id} rejected – refunded");
                $conn->query("INSERT INTO account_logs (user_id,type,category,amount,description)
                              VALUES ({$uid},'income','withdraw',{$amount},'{$desc_e}')");
                $conn->commit();
                $msg = "Withdrawal #{$wd_id} rejected. {$amount} refunded to user #{$uid}.";
            } catch (Exception $e) {
                $conn->rollback();
                $msg = 'Error: ' . $e->getMessage(); $msg_type = 'err';
            }
        } else {
            $msg = 'Withdrawal not found or already processed.'; $msg_type = 'err';
        }
    }

    elseif ($action === 'delete' && $wd_id) {
        $wd = $conn->query("SELECT * FROM withdrawals WHERE id={$wd_id} LIMIT 1")->fetch_assoc();
        if ($wd) {
            // If pending, refund before deleting
            if ($wd['status'] === 'pending') {
                $uid    = (int)$wd['user_id'];
                $amount = (float)$wd['amount'];
                $conn->query("UPDATE users SET balance = balance + {$amount} WHERE id={$uid}");
            }
            $conn->query("DELETE FROM withdrawals WHERE id={$wd_id}");
            $msg = "Withdrawal #{$wd_id} deleted" . ($wd['status']==='pending' ? " and balance refunded." : ".");
        } else {
            $msg = 'Withdrawal not found.'; $msg_type = 'err';
        }
    }
}

// ── Filters ───────────────────────────────────────────────────
$status_filter = $_GET['status'] ?? 'all';
$search        = trim($_GET['q'] ?? '');
$page          = max(1, (int)($_GET['page'] ?? 1));
$per_page      = 20;
$offset        = ($page - 1) * $per_page;

$where = [];
if ($status_filter !== 'all') $where[] = "w.status='" . $conn->real_escape_string($status_filter) . "'";
if ($search) {
    $s = $conn->real_escape_string($search);
    $where[] = "(u.phone LIKE '%{$s}%' OR w.method LIKE '%{$s}%' OR w.account_ref LIKE '%{$s}%' OR w.id='" . (int)$search . "')";
}
$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$total = (int)$conn->query("SELECT COUNT(*) as c FROM withdrawals w LEFT JOIN users u ON u.id=w.user_id {$where_sql}")->fetch_assoc()['c'];
$pages = max(1, ceil($total / $per_page));

$withdrawals = [];
$res = $conn->query("SELECT w.*, u.phone, u.full_name, u.balance as cur_balance
                     FROM withdrawals w
                     LEFT JOIN users u ON u.id=w.user_id
                     {$where_sql}
                     ORDER BY w.created_at DESC
                     LIMIT {$per_page} OFFSET {$offset}");
while ($row = $res->fetch_assoc()) $withdrawals[] = $row;

// Summary
$counts = $conn->query("SELECT status, COUNT(*) as c, COALESCE(SUM(amount),0) as s, COALESCE(SUM(net_amount),0) as ns FROM withdrawals GROUP BY status")->fetch_all(MYSQLI_ASSOC);
$cnt = ['pending'=>['c'=>0,'s'=>0,'ns'=>0], 'approved'=>['c'=>0,'s'=>0,'ns'=>0], 'rejected'=>['c'=>0,'s'=>0,'ns'=>0]];
foreach ($counts as $r) $cnt[$r['status']] = ['c'=>$r['c'],'s'=>$r['s'],'ns'=>$r['ns']];

$currency = $conn->query("SELECT key_value FROM settings WHERE key_name='currency_symbol' LIMIT 1")->fetch_assoc()['key_value'] ?? 'TZS';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin – Manage Withdrawals</title>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
:root{
  --bg:#f0f4f0;--sidebar:#1a2e1a;
  --green:#2d7a3a;--green-lt:#3eaabb;
  --gold:#f5c518;--red:#e53935;--red-lt:#fdecea;
  --text:#1a2a1a;--muted:#6a7a6a;--border:#dde8dd;
  --card:#fff;--r:12px;--r-sm:8px;
  --shadow:0 2px 12px rgba(0,40,0,.08);
}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Outfit',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;display:flex}
.sidebar{width:220px;background:var(--sidebar);min-height:100vh;flex-shrink:0;
  display:flex;flex-direction:column;position:sticky;top:0;height:100vh;overflow-y:auto}
.sb-logo{padding:22px 18px 16px;border-bottom:1px solid rgba(255,255,255,.08)}
.sb-logo h2{font-size:16px;font-weight:800;color:#fff}
.sb-logo p{font-size:11px;color:rgba(255,255,255,.4);margin-top:2px}
.sb-nav{padding:12px 0;flex:1}
.sb-section{font-size:10px;font-weight:700;color:rgba(255,255,255,.3);text-transform:uppercase;letter-spacing:.8px;padding:10px 18px 4px}
.sb-link{display:flex;align-items:center;gap:10px;padding:10px 18px;text-decoration:none;
  color:rgba(255,255,255,.65);font-size:13px;font-weight:500;transition:all .18s;border-left:3px solid transparent}
.sb-link svg{width:18px;height:18px;fill:currentColor;flex-shrink:0}
.sb-link:hover{color:#fff;background:rgba(255,255,255,.06)}
.sb-link.active{color:#fff;background:rgba(255,255,255,.1);border-left-color:var(--gold)}
.main{flex:1;display:flex;flex-direction:column;min-width:0}
.topbar{background:#fff;padding:14px 24px;border-bottom:1px solid var(--border);
  display:flex;align-items:center;justify-content:space-between;
  position:sticky;top:0;z-index:100;box-shadow:0 1px 4px rgba(0,0,0,.04)}
.topbar h1{font-size:18px;font-weight:800}
.content{padding:20px 24px;flex:1}
.btn{display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:var(--r-sm);
  font-family:'Outfit',sans-serif;font-size:13px;font-weight:700;border:none;cursor:pointer;text-decoration:none;transition:opacity .18s}
.btn:hover{opacity:.85}
.btn-green{background:var(--green);color:#fff}
.btn-red{background:var(--red);color:#fff}
.btn-ghost{background:transparent;color:var(--muted);border:1.5px solid var(--border)}
.btn svg{width:16px;height:16px;fill:currentColor}
.alert{padding:13px 16px;border-radius:var(--r-sm);font-size:13px;font-weight:500;margin-bottom:16px;display:flex;align-items:center;gap:8px}
.alert svg{width:18px;height:18px;fill:currentColor;flex-shrink:0}
.alert-ok{background:#eafaf0;border:1px solid #a0ddb8;color:#145c30}
.alert-err{background:var(--red-lt);border:1px solid #f5b0b0;color:#7f1d1d}
.stats-row{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:20px}
.stat-card{background:var(--card);border-radius:var(--r);padding:18px 20px;box-shadow:var(--shadow);border-left:4px solid transparent;text-decoration:none;display:block}
.stat-card.pending{border-left-color:var(--gold)}
.stat-card.approved{border-left-color:var(--green)}
.stat-card.rejected{border-left-color:var(--red)}
.stat-label{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px}
.stat-val{font-size:22px;font-weight:800;color:var(--text)}
.stat-sub{font-size:12px;color:var(--muted);margin-top:4px}
.status-tabs{display:flex;gap:6px;margin-bottom:16px}
.stab{padding:7px 16px;border-radius:20px;font-size:12px;font-weight:700;text-decoration:none;
  color:var(--muted);background:#fff;border:1.5px solid var(--border);transition:all .18s}
.stab:hover{border-color:var(--green)}
.stab.active{background:var(--green);color:#fff;border-color:var(--green)}
.filter-bar{background:var(--card);border-radius:var(--r);padding:14px 16px;margin-bottom:16px;box-shadow:var(--shadow)}
.filter-bar form{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.filter-bar input,.filter-bar select{padding:8px 12px;border:1.5px solid var(--border);border-radius:var(--r-sm);
  font-family:'Outfit',sans-serif;font-size:13px;color:var(--text);background:#fff;outline:none}
.filter-bar input{flex:1;min-width:160px}
.filter-bar input:focus{border-color:var(--green-lt)}
.table-wrap{background:var(--card);border-radius:var(--r);box-shadow:var(--shadow);overflow:hidden}
.table-head{padding:14px 16px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
.table-head h3{font-size:14px;font-weight:700}
.table-head .count{font-size:12px;color:var(--muted)}
table{width:100%;border-collapse:collapse}
th{background:#f8fbf8;font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.4px;padding:11px 14px;text-align:left;border-bottom:1px solid var(--border)}
td{padding:12px 14px;font-size:13px;border-bottom:1px solid #f4f8f4;vertical-align:middle}
tr:last-child td{border-bottom:none}
tr:hover td{background:#fafcfa}
.badge{padding:3px 10px;border-radius:20px;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.4px;white-space:nowrap}
.badge-pending{background:#fff8e0;color:#a07000}
.badge-approved{background:#e6f9ef;color:#145c30}
.badge-rejected{background:var(--red-lt);color:#7f1d1d}
.user-cell .name{font-weight:700;font-size:13px}
.user-cell .phone{font-size:11px;color:var(--muted);margin-top:2px}
.amount-main{font-size:15px;font-weight:800;color:var(--red)}
.amount-net{font-size:11px;color:var(--green);margin-top:2px}
.amount-fee{font-size:11px;color:var(--muted)}
.action-btns{display:flex;gap:6px;align-items:center;flex-wrap:wrap}
.act-btn{display:inline-flex;align-items:center;gap:4px;padding:5px 12px;border-radius:var(--r-sm);
  font-size:11px;font-weight:700;border:none;cursor:pointer;font-family:'Outfit',sans-serif;white-space:nowrap;transition:opacity .18s}
.act-btn:hover{opacity:.8}
.act-approve{background:var(--green);color:#fff}
.act-reject{background:#fff3e0;color:#e65100;border:1px solid #ffd0a0}
.act-delete{background:var(--red-lt);color:var(--red)}
.pagination{display:flex;align-items:center;justify-content:center;gap:6px;padding:20px 0}
.pag-btn{padding:7px 14px;border-radius:var(--r-sm);font-size:13px;font-weight:600;text-decoration:none;color:var(--muted);border:1.5px solid var(--border);background:#fff;transition:all .18s}
.pag-btn:hover,.pag-btn.active{background:var(--green);color:#fff;border-color:var(--green)}
.modal-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:1000;align-items:center;justify-content:center;padding:20px}
.modal-overlay.open{display:flex}
.modal{background:#fff;border-radius:var(--r);max-width:480px;width:100%;box-shadow:0 20px 60px rgba(0,0,0,.25);max-height:90vh;overflow-y:auto}
.modal-head{padding:18px 20px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between}
.modal-head h3{font-size:16px;font-weight:700}
.modal-close{width:32px;height:32px;border-radius:50%;background:var(--bg);border:none;cursor:pointer;font-size:18px;display:flex;align-items:center;justify-content:center}
.modal-body{padding:20px}
.modal-body .field{margin-bottom:14px}
.modal-body label{display:block;font-size:11px;font-weight:700;color:var(--muted);margin-bottom:5px;text-transform:uppercase;letter-spacing:.4px}
.modal-body textarea{width:100%;padding:10px 12px;border:1.5px solid var(--border);border-radius:var(--r-sm);font-family:'Outfit',sans-serif;font-size:13px;outline:none;resize:vertical}
.modal-body textarea:focus{border-color:var(--green-lt)}
.modal-foot{display:flex;gap:8px;justify-content:flex-end;padding:14px 20px;border-top:1px solid var(--border)}
.empty-state{text-align:center;padding:48px 24px;color:var(--muted)}
.empty-state svg{width:48px;height:48px;fill:#c8d8c8;margin-bottom:12px}
.wd-detail-row{font-size:12px;color:var(--muted);display:flex;gap:6px;flex-wrap:wrap;margin-top:4px}
.wd-detail-row span{background:#f0f8f0;padding:2px 8px;border-radius:20px;font-weight:500}
</style>
</head>
<body>

<!-- Sidebar -->
<aside class="sidebar">
  <div class="sb-logo"><h2>WFM Admin</h2><p>Finance Panel</p></div>
  <nav class="sb-nav">
    <div class="sb-section">Finance</div>
    <a href="admin_deposits.php" class="sb-link">
      <svg viewBox="0 0 24 24"><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 active">
      <svg viewBox="0 0 24 24"><path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z"/></svg>Withdrawals</a>
    <a href="admin_payment_methods.php" class="sb-link">
      <svg viewBox="0 0 24 24"><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"><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"><path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/></svg>Dashboard</a>
    <a href="../admin_logout.php" class="sb-link">
      <svg viewBox="0 0 24 24"><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>
  </nav>
</aside>

<div class="main">
  <div class="topbar">
    <h1>💸 Manage Withdrawals</h1>
    <span style="font-size:12px;color:var(--muted)"><?= date('d M Y H:i') ?></span>
  </div>

  <div class="content">

    <?php if ($msg): ?>
    <div class="alert alert-<?= $msg_type ?>">
      <svg viewBox="0 0 24 24"><path d="<?= $msg_type==='ok'?'M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z':'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z' ?>"/></svg>
      <?= htmlspecialchars($msg) ?>
    </div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="stats-row">
      <a href="?status=pending" class="stat-card pending">
        <div class="stat-label">⏳ Pending</div>
        <div class="stat-val"><?= $cnt['pending']['c'] ?></div>
        <div class="stat-sub">Gross: <?= number_format($cnt['pending']['s'],2) ?> <?= $currency ?></div>
      </a>
      <a href="?status=approved" class="stat-card approved">
        <div class="stat-label">✅ Approved</div>
        <div class="stat-val"><?= $cnt['approved']['c'] ?></div>
        <div class="stat-sub">Paid out: <?= number_format($cnt['approved']['ns'],2) ?> <?= $currency ?></div>
      </a>
      <a href="?status=rejected" class="stat-card rejected">
        <div class="stat-label">↩ Rejected (Refunded)</div>
        <div class="stat-val"><?= $cnt['rejected']['c'] ?></div>
        <div class="stat-sub"><?= number_format($cnt['rejected']['s'],2) ?> <?= $currency ?></div>
      </a>
    </div>

    <!-- Status Tabs -->
    <div class="status-tabs">
      <?php foreach (['all'=>'All','pending'=>'Pending','approved'=>'Approved','rejected'=>'Rejected'] as $k=>$v): ?>
      <a href="?status=<?= $k ?><?= $search?'&q='.urlencode($search):'' ?>"
         class="stab <?= $status_filter===$k?'active':'' ?>"><?= $v ?></a>
      <?php endforeach; ?>
    </div>

    <!-- Filter -->
    <div class="filter-bar">
      <form method="GET">
        <input type="hidden" name="status" value="<?= htmlspecialchars($status_filter) ?>">
        <input type="text" name="q" placeholder="Search phone, method, account…" value="<?= htmlspecialchars($search) ?>">
        <button type="submit" class="btn btn-green">
          <svg viewBox="0 0 24 24"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/></svg>Search
        </button>
        <?php if ($search): ?><a href="?status=<?= htmlspecialchars($status_filter) ?>" class="btn btn-ghost">Clear</a><?php endif; ?>
      </form>
    </div>

    <!-- Table -->
    <div class="table-wrap">
      <div class="table-head">
        <h3>Withdrawal Requests</h3>
        <span class="count"><?= $total ?> total · page <?= $page ?>/<?= $pages ?></span>
      </div>
      <?php if (empty($withdrawals)): ?>
      <div class="empty-state">
        <svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z"/></svg>
        <p>No withdrawals found.</p>
      </div>
      <?php else: ?>
      <table>
        <thead>
          <tr>
            <th>#ID</th>
            <th>User</th>
            <th>Amount / Fee</th>
            <th>Send To</th>
            <th>Method</th>
            <th>Date</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($withdrawals as $w): ?>
          <tr>
            <td style="font-weight:700;color:var(--muted)">#<?= $w['id'] ?></td>
            <td>
              <div class="user-cell">
                <div class="name"><?= htmlspecialchars($w['full_name'] ?: 'User #'.$w['user_id']) ?></div>
                <div class="phone"><?= htmlspecialchars($w['phone']) ?></div>
                <div style="font-size:11px;color:var(--muted)">Balance: <?= number_format($w['cur_balance'],2) ?></div>
              </div>
            </td>
            <td>
              <div class="amount-main">-<?= number_format($w['amount'],2) ?> <?= $currency ?></div>
              <div class="amount-fee">Fee: <?= number_format($w['fee'],2) ?></div>
              <div class="amount-net">→ <?= number_format($w['net_amount'],2) ?> net</div>
            </td>
            <td>
              <div style="font-weight:700;font-size:13px"><?= htmlspecialchars($w['account_ref']) ?></div>
              <?php if ($w['account_name']): ?>
              <div style="font-size:11px;color:var(--muted)"><?= htmlspecialchars($w['account_name']) ?></div>
              <?php endif; ?>
            </td>
            <td style="font-size:12px;color:var(--muted)"><?= htmlspecialchars($w['method']) ?></td>
            <td style="font-size:12px;color:var(--muted);white-space:nowrap">
              <?= date('d M Y', strtotime($w['created_at'])) ?><br>
              <span style="color:#bbb"><?= date('H:i', strtotime($w['created_at'])) ?></span>
            </td>
            <td>
              <span class="badge badge-<?= $w['status'] ?>"><?= ucfirst($w['status']) ?></span>
              <?php if ($w['admin_note']): ?>
              <div style="font-size:10px;color:var(--muted);margin-top:3px;max-width:100px"><?= htmlspecialchars($w['admin_note']) ?></div>
              <?php endif; ?>
            </td>
            <td>
              <div class="action-btns">
                <?php if ($w['status'] === 'pending'): ?>
                <form method="POST" onsubmit="return confirm('Mark withdrawal #<?= $w['id'] ?> as approved?\n\nUser: <?= addslashes($w['phone']) ?>\nAmount to send: <?= number_format($w['net_amount'],2) ?> <?= $currency ?>\nTo: <?= addslashes($w['account_ref']) ?>')">
                  <input type="hidden" name="action" value="approve">
                  <input type="hidden" name="wd_id" value="<?= $w['id'] ?>">
                  <button type="submit" class="act-btn act-approve">✓ Approve</button>
                </form>
                <button class="act-btn act-reject"
                        onclick="openReject(<?= $w['id'] ?>,'<?= addslashes($w['phone']) ?>',<?= $w['amount'] ?>)">
                  ↩ Reject
                </button>
                <?php endif; ?>
                <button class="act-btn act-delete"
                        onclick="openDelete(<?= $w['id'] ?>,'<?= addslashes($w['phone']) ?>','<?= $w['status'] ?>')">🗑</button>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <?php endif; ?>
    </div>

    <?php if ($pages > 1): ?>
    <div class="pagination">
      <?php if ($page > 1): ?><a href="?status=<?= urlencode($status_filter) ?>&q=<?= urlencode($search) ?>&page=<?= $page-1 ?>" class="pag-btn">‹ Prev</a><?php endif; ?>
      <?php for ($i=max(1,$page-2);$i<=min($pages,$page+2);$i++): ?>
      <a href="?status=<?= urlencode($status_filter) ?>&q=<?= urlencode($search) ?>&page=<?= $i ?>" class="pag-btn <?= $i===$page?'active':'' ?>"><?= $i ?></a>
      <?php endfor; ?>
      <?php if ($page < $pages): ?><a href="?status=<?= urlencode($status_filter) ?>&q=<?= urlencode($search) ?>&page=<?= $page+1 ?>" class="pag-btn">Next ›</a><?php endif; ?>
    </div>
    <?php endif; ?>

  </div>
</div>

<!-- Reject Modal -->
<div class="modal-overlay" id="rejectModal">
  <div class="modal">
    <div class="modal-head">
      <h3>↩ Reject Withdrawal</h3>
      <button class="modal-close" onclick="closeModal('rejectModal')">×</button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="reject">
      <input type="hidden" name="wd_id" id="rejectWdId">
      <div class="modal-body">
        <div style="background:#fff8e0;border:1px solid #f5d080;border-radius:8px;padding:12px;margin-bottom:14px;font-size:13px;color:#7a5000">
          ↩ Rejecting will <strong>refund</strong> the full amount back to user <strong id="rejectUser"></strong>.<br>
          Amount: <strong id="rejectAmt"></strong> <?= $currency ?>
        </div>
        <div class="field">
          <label>Reason (admin log only)</label>
          <textarea name="admin_note" rows="3" placeholder="e.g. Invalid account details, under review…"></textarea>
        </div>
      </div>
      <div class="modal-foot">
        <button type="button" class="btn btn-ghost" onclick="closeModal('rejectModal')">Cancel</button>
        <button type="submit" class="btn btn-red">Confirm Reject &amp; Refund</button>
      </div>
    </form>
  </div>
</div>

<!-- Delete Modal -->
<div class="modal-overlay" id="deleteModal">
  <div class="modal">
    <div class="modal-head">
      <h3>🗑 Delete Withdrawal Record</h3>
      <button class="modal-close" onclick="closeModal('deleteModal')">×</button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="delete">
      <input type="hidden" name="wd_id" id="deleteWdId">
      <div class="modal-body">
        <p id="deleteMsg" style="font-size:14px;padding:12px;border-radius:8px;background:var(--red-lt);color:#7f1d1d"></p>
      </div>
      <div class="modal-foot">
        <button type="button" class="btn btn-ghost" onclick="closeModal('deleteModal')">Cancel</button>
        <button type="submit" class="btn btn-red">Delete Record</button>
      </div>
    </form>
  </div>
</div>

<script>
function openReject(id,phone,amt){
  document.getElementById('rejectWdId').value=id;
  document.getElementById('rejectUser').textContent=phone;
  document.getElementById('rejectAmt').textContent=parseFloat(amt).toLocaleString(undefined,{minimumFractionDigits:2});
  document.getElementById('rejectModal').classList.add('open');
}
function openDelete(id,phone,status){
  document.getElementById('deleteWdId').value=id;
  const msg = status==='pending'
    ? `⚠ Delete withdrawal #${id} for ${phone}? Since it's PENDING, the amount will be automatically refunded to the user.`
    : `⚠ Permanently delete withdrawal #${id} for ${phone}? Status is ${status.toUpperCase()} — no balance change will occur.`;
  document.getElementById('deleteMsg').textContent=msg;
  document.getElementById('deleteModal').classList.add('open');
}
function closeModal(id){document.getElementById(id).classList.remove('open');}
document.querySelectorAll('.modal-overlay').forEach(m=>m.addEventListener('click',e=>{if(e.target===m)m.classList.remove('open');}));
</script>
</body>
</html>