<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_page_access();

// ── Filters from GET ──────────────────────────────────────────
$filter_status   = $_GET['status']   ?? 'all';
$filter_currency = $_GET['currency'] ?? 'all';
$filter_country  = $_GET['country']  ?? 'all';
$filter_gateway  = $_GET['gateway']  ?? 'all';
$search          = trim($_GET['search'] ?? '');
$page            = max(1, (int)($_GET['page'] ?? 1));
$per_page        = 25;
$offset          = ($page - 1) * $per_page;

// ── Build WHERE clause ────────────────────────────────────────
$where  = ['1=1'];
$params = [];

if ($filter_status !== 'all') {
    $where[]  = 'p.status = ?';
    $params[] = strtoupper($filter_status);
}
if ($filter_currency !== 'all') {
    $where[]  = 'p.currency = ?';
    $params[] = $filter_currency;
}
if ($filter_country !== 'all') {
    $where[]  = 'u.country = ?';
    $params[] = $filter_country;
}
if ($filter_gateway !== 'all') {
    $where[]  = 'p.gateway = ?';
    $params[] = $filter_gateway;
}
if ($search !== '') {
    $where[]  = '(p.tracking_code LIKE ? OR mi.article_title LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR CONCAT(u.first_name," ",u.last_name) LIKE ?)';
    $like     = '%' . $search . '%';
    $params   = array_merge($params, [$like, $like, $like, $like, $like, $like]);
}

$whereSQL = implode(' AND ', $where);

// ── Total count ───────────────────────────────────────────────
$countSQL = "
    SELECT COUNT(*) FROM payments p
    LEFT JOIN submissions s  ON s.submission_id  = p.submission_id
    LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
    LEFT JOIN journals j     ON j.journal_id     = s.journal_id
    LEFT JOIN users u        ON u.user_id        = s.user_id
    WHERE $whereSQL
";
$countStmt = $pdo->prepare($countSQL);
$countStmt->execute($params);
$total_records = (int)$countStmt->fetchColumn();
$total_pages   = max(1, ceil($total_records / $per_page));

// ── Main data query ───────────────────────────────────────────
$dataSQL = "
    SELECT
        p.payment_id,
        p.tracking_code,
        p.gateway,
        p.gateway_order_id,
        p.gateway_capture_id,
        p.gateway_session_id,
        p.status,
        p.payer_email,
        p.payer_name,
        p.amount,
        p.currency,
        p.paid_at,
        p.created_at,
        s.submission_id,
        s.submission_status,
        mi.article_title,
        j.name AS journal_name,
        u.user_id,
        u.first_name,
        u.last_name,
        u.email AS author_email,
        u.country AS author_country
    FROM payments p
    LEFT JOIN submissions s      ON s.submission_id  = p.submission_id
    LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
    LEFT JOIN journals j         ON j.journal_id     = s.journal_id
    LEFT JOIN users u            ON u.user_id        = s.user_id
    WHERE $whereSQL
    ORDER BY p.created_at DESC
    LIMIT $per_page OFFSET $offset
";
$dataStmt = $pdo->prepare($dataSQL);
$dataStmt->execute($params);
$payments = $dataStmt->fetchAll(PDO::FETCH_ASSOC);

// ── Summary stats ─────────────────────────────────────────────
$summarySQL = "
    SELECT
        COUNT(*)                                              AS total,
        SUM(p.status = 'COMPLETED')                          AS completed,
        SUM(p.status = 'CREATED')                            AS pending,
        SUM(p.status = 'FAILED')                             AS failed,
        SUM(CASE WHEN p.status='COMPLETED' AND p.currency='USD' THEN p.amount ELSE 0 END) AS total_usd,
        SUM(CASE WHEN p.status='COMPLETED' AND p.currency='INR' THEN p.amount ELSE 0 END) AS total_inr,
        SUM(CASE WHEN p.status='COMPLETED' AND p.currency='NGN' THEN p.amount ELSE 0 END) AS total_ngn
    FROM payments p
    LEFT JOIN submissions s ON s.submission_id = p.submission_id
    LEFT JOIN users u       ON u.user_id       = s.user_id
";
$sum = $pdo->query($summarySQL)->fetch(PDO::FETCH_ASSOC);

// ── Distinct filter options ───────────────────────────────────
$currencies = $pdo->query("SELECT DISTINCT currency FROM payments WHERE currency IS NOT NULL ORDER BY currency")
                  ->fetchAll(PDO::FETCH_COLUMN);
$gateways   = $pdo->query("SELECT DISTINCT gateway FROM payments WHERE gateway IS NOT NULL ORDER BY gateway")
                  ->fetchAll(PDO::FETCH_COLUMN);
$countries  = $pdo->query("
    SELECT DISTINCT u.country FROM payments p
    LEFT JOIN submissions s ON s.submission_id = p.submission_id
    LEFT JOIN users u ON u.user_id = s.user_id
    WHERE u.country IS NOT NULL AND u.country != ''
    ORDER BY u.country
")->fetchAll(PDO::FETCH_COLUMN);

$active_section = 'payments';
function p($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
function getCurrSymbol($c){
    $m = ['INR'=>'₹','USD'=>'$','NGN'=>'₦','BDT'=>'৳','PKR'=>'Rs ','PHP'=>'₱',
          'MYR'=>'RM ','IDR'=>'Rp ','KES'=>'KSh ','GHS'=>'₵ ','NPR'=>'Rs ',
          'TRY'=>'₺','ZAR'=>'R ','VND'=>'₫ ','CNY'=>'¥ ','ETB'=>'Br ','TZS'=>'TSh '];
    return $m[$c] ?? '$';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Payment Management — Admin</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
body{font-family:'Roboto',sans-serif;margin:0;height:100vh;overflow:hidden}
body.dark{background:#0F172A;color:#E2E8F0}
.sidebar{width:250px;background:#1E293B;color:white;transition:all .3s;height:100%;position:fixed;top:0;left:0;z-index:10;overflow-y:auto}
.sidebar.collapsed{width:70px}
.sidebar.collapsed .sidebar-title{display:none}
.content{margin-left:250px;transition:margin-left .3s;height:100vh;overflow-y:auto}
.content.collapsed-sidebar{margin-left:70px}
.nav-item{padding:10px 12px;cursor:pointer;transition:background .2s;display:flex;align-items:center}
.nav-item:hover{background:#334155}
.nav-item.active{background:#334155;border-left:3px solid #3B82F6}
body.dark .bg-white{background:#1E293B}
body.dark .bg-gray-50{background:#0F172A}
body.dark .bg-slate-100{background:#0F172A}
body.dark .border-gray-100,.dark .border-gray-200{border-color:#334155}
body.dark .text-gray-800{color:#F1F5F9}
body.dark .text-gray-700{color:#CBD5E1}
body.dark .text-gray-600{color:#94A3B8}
body.dark .text-gray-500{color:#64748B}
body.dark select,body.dark input{background:#334155;border-color:#475569;color:#E2E8F0}
@media(max-width:768px){.sidebar{transform:translateX(-250px)}.sidebar.mobile-open{transform:translateX(0)}.content{margin-left:0}}

/* Status badges */
.s-COMPLETED{background:#D1FAE5;color:#065F46}
.s-CREATED{background:#FEF3C7;color:#92400E}
.s-FAILED{background:#FEE2E2;color:#991B1B}
.s-REFUNDED{background:#F3F4F6;color:#374151}

/* Gateway badges */
.g-paypal{background:#EFF6FF;color:#1E40AF;border:1px solid #BFDBFE}
.g-stripe{background:#EEF2FF;color:#4338CA;border:1px solid #C7D2FE}
.g-razorpay{background:#E3F2FD;color:#1565C0;border:1px solid #90CAF9}
.g-bank{background:#F9FAFB;color:#374151;border:1px solid #D1D5DB}

.inp{width:100%;border:1px solid #D1D5DB;border-radius:8px;padding:8px 12px;font-size:13px;color:#374151;outline:none;background:white;transition:border-color .15s}
.inp:focus{border-color:#3B82F6;box-shadow:0 0 0 2px rgba(59,130,246,.1)}
body.dark .inp{background:#334155;border-color:#475569;color:#E2E8F0}

.stat-card{background:white;border-radius:12px;border:1px solid #E2E8F0;padding:18px 20px}
body.dark .stat-card{background:#1E293B;border-color:#334155}

.data-table{width:100%;border-collapse:collapse;font-size:13px}
.data-table th{background:#F9FAFB;padding:10px 12px;text-align:left;font-size:11px;font-weight:700;color:#6B7280;text-transform:uppercase;letter-spacing:.4px;border-bottom:1px solid #E5E7EB;white-space:nowrap}
.data-table td{padding:10px 12px;border-bottom:1px solid #F3F4F6;vertical-align:middle}
.data-table tr:hover td{background:#F9FAFB}
body.dark .data-table th{background:#0F172A;border-color:#334155;color:#64748B}
body.dark .data-table td{border-color:#1E293B}
body.dark .data-table tr:hover td{background:#1E293B}

.mono{font-family:monospace;font-size:11.5px;background:#F3F4F6;padding:2px 6px;border-radius:4px}
body.dark .mono{background:#374151;color:#E2E8F0}

.amount-val{font-weight:700;font-size:13.5px}
</style>
</head>
<body class="bg-slate-100">

<button onclick="toggleMobile()" class="fixed top-3 left-3 z-20 bg-slate-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>

<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="content" id="content">

  <!-- Topbar -->
  <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between sticky top-0 z-10 shadow-sm">
    <div class="flex items-center gap-3">
      <button onclick="toggleSidebar()" class="text-gray-400 hover:text-gray-600 hidden md:block">
        <i class="fas fa-bars text-lg"></i>
      </button>
      <div class="flex items-center gap-2">
        <i class="fas fa-credit-card text-blue-500"></i>
        <span class="font-bold text-gray-800">Payment Management</span>
      </div>
    </div>
    <div class="flex items-center gap-3">
      <span class="text-xs text-gray-400"><?= number_format($total_records) ?> records</span>
      <button id="darkToggle" class="text-gray-400 hover:text-gray-600 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
        <i class="fas fa-moon text-sm"></i>
      </button>
    </div>
  </div>

  <main class="p-5 space-y-5">

    <!-- ── Summary Stats ── -->
    <div class="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-7 gap-3">
      <div class="stat-card col-span-1">
        <div class="text-xs font-bold text-gray-400 uppercase tracking-wide mb-1">Total</div>
        <div class="text-2xl font-bold text-gray-800"><?= number_format((int)$sum['total']) ?></div>
      </div>
      <div class="stat-card">
        <div class="text-xs font-bold text-gray-400 uppercase tracking-wide mb-1">Completed</div>
        <div class="text-2xl font-bold text-emerald-600"><?= number_format((int)$sum['completed']) ?></div>
      </div>
      <div class="stat-card">
        <div class="text-xs font-bold text-gray-400 uppercase tracking-wide mb-1">Pending</div>
        <div class="text-2xl font-bold text-amber-500"><?= number_format((int)$sum['pending']) ?></div>
      </div>
      <div class="stat-card">
        <div class="text-xs font-bold text-gray-400 uppercase tracking-wide mb-1">Failed</div>
        <div class="text-2xl font-bold text-red-500"><?= number_format((int)$sum['failed']) ?></div>
      </div>
      <div class="stat-card">
        <div class="text-xs font-bold text-gray-400 uppercase tracking-wide mb-1">USD Collected</div>
        <div class="text-xl font-bold text-emerald-700">$<?= number_format((float)$sum['total_usd'], 2) ?></div>
      </div>
      <div class="stat-card">
        <div class="text-xs font-bold text-gray-400 uppercase tracking-wide mb-1">INR Collected</div>
        <div class="text-xl font-bold text-blue-700">₹<?= number_format((float)$sum['total_inr'], 2) ?></div>
      </div>
      <div class="stat-card">
        <div class="text-xs font-bold text-gray-400 uppercase tracking-wide mb-1">NGN Collected</div>
        <div class="text-xl font-bold text-orange-600">₦<?= number_format((float)$sum['total_ngn'], 2) ?></div>
      </div>
    </div>

    <!-- ── Filters ── -->
    <div class="bg-white border border-gray-200 rounded-xl p-4">
      <form method="GET" id="filterForm">
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3">

          <!-- Search -->
          <div class="lg:col-span-2 relative">
            <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs"></i>
            <input type="text" name="search" class="inp pl-8"
                   placeholder="Search author, tracking code, article title…"
                   value="<?= p($search) ?>">
          </div>

          <!-- Status -->
          <select name="status" class="inp" onchange="this.form.submit()">
            <option value="all"      <?= $filter_status==='all'       ? 'selected':'' ?>>All Status</option>
            <option value="COMPLETED"<?= $filter_status==='COMPLETED' ? 'selected':'' ?>>✅ Completed</option>
            <option value="CREATED"  <?= $filter_status==='CREATED'   ? 'selected':'' ?>>⏳ Pending</option>
            <option value="FAILED"   <?= $filter_status==='FAILED'    ? 'selected':'' ?>>❌ Failed</option>
            <option value="REFUNDED" <?= $filter_status==='REFUNDED'  ? 'selected':'' ?>>↩ Refunded</option>
          </select>

          <!-- Gateway -->
          <select name="gateway" class="inp" onchange="this.form.submit()">
            <option value="all" <?= $filter_gateway==='all' ? 'selected':'' ?>>All Gateways</option>
            <?php foreach ($gateways as $gw): ?>
            <option value="<?= p($gw) ?>" <?= $filter_gateway===$gw ? 'selected':'' ?>>
              <?= p(ucfirst($gw)) ?>
            </option>
            <?php endforeach; ?>
          </select>

          <!-- Currency -->
          <select name="currency" class="inp" onchange="this.form.submit()">
            <option value="all" <?= $filter_currency==='all' ? 'selected':'' ?>>All Currencies</option>
            <?php foreach ($currencies as $cur): ?>
            <option value="<?= p($cur) ?>" <?= $filter_currency===$cur ? 'selected':'' ?>>
              <?= p($cur) ?>
            </option>
            <?php endforeach; ?>
          </select>

        </div>

        <!-- Row 2: Country + buttons -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-3 mt-3">
          <select name="country" class="inp" onchange="this.form.submit()">
            <option value="all" <?= $filter_country==='all' ? 'selected':'' ?>>All Countries</option>
            <?php foreach ($countries as $c): ?>
            <option value="<?= p($c) ?>" <?= $filter_country===$c ? 'selected':'' ?>>
              <?= p($c) ?>
            </option>
            <?php endforeach; ?>
          </select>

          <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-bold transition flex items-center justify-center gap-2">
            <i class="fas fa-filter text-xs"></i> Apply Filters
          </button>

          <a href="admin_payments.php" class="border border-gray-300 text-gray-600 hover:bg-gray-50 px-4 py-2 rounded-lg text-sm font-bold transition flex items-center justify-center gap-2">
            <i class="fas fa-times text-xs"></i> Clear Filters
          </a>
        </div>

        <!-- Active filters display -->
        <?php
        $activeFilters = [];
        if ($filter_status !== 'all') $activeFilters[] = "Status: <strong>" . p($filter_status) . "</strong>";
        if ($filter_gateway !== 'all') $activeFilters[] = "Gateway: <strong>" . p(ucfirst($filter_gateway)) . "</strong>";
        if ($filter_currency !== 'all') $activeFilters[] = "Currency: <strong>" . p($filter_currency) . "</strong>";
        if ($filter_country !== 'all') $activeFilters[] = "Country: <strong>" . p($filter_country) . "</strong>";
        if ($search !== '') $activeFilters[] = "Search: <strong>" . p($search) . "</strong>";
        ?>
        <?php if (!empty($activeFilters)): ?>
        <div class="mt-3 flex flex-wrap gap-2 items-center">
          <span class="text-xs text-gray-400 font-semibold">Active:</span>
          <?php foreach ($activeFilters as $af): ?>
          <span class="text-xs bg-blue-50 text-blue-700 border border-blue-200 px-2 py-1 rounded-full"><?= $af ?></span>
          <?php endforeach; ?>
          <span class="text-xs text-gray-400">— <?= number_format($total_records) ?> results</span>
        </div>
        <?php endif; ?>

      </form>
    </div>

    <!-- ── Data Table ── -->
    <div class="bg-white border border-gray-200 rounded-xl overflow-hidden">
      <div class="px-5 py-3 border-b border-gray-100 flex items-center justify-between">
        <span class="text-sm font-bold text-gray-700">
          Payment Records
          <span class="text-gray-400 font-normal ml-1">(<?= number_format($total_records) ?> total)</span>
        </span>
        <span class="text-xs text-gray-400">
          Page <?= $page ?> of <?= $total_pages ?>
        </span>
      </div>

      <?php if (empty($payments)): ?>
      <div class="text-center py-16 text-gray-400">
        <i class="fas fa-receipt text-4xl mb-3 block text-gray-200"></i>
        <div class="font-bold text-gray-500">No payment records found</div>
        <div class="text-sm mt-1">Try adjusting your filters</div>
      </div>
      <?php else: ?>
      <div style="overflow-x:auto">
        <table class="data-table">
          <thead>
            <tr>
              <th>#</th>
              <th>Tracking Code</th>
              <th>Author</th>
              <th>Country</th>
              <th>Article</th>
              <th>Gateway</th>
              <th>Amount</th>
              <th>Status</th>
              <th>Transaction ID</th>
              <th>Date</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($payments as $p):
              $isCompleted = $p['status'] === 'COMPLETED';
              $authorName  = trim(($p['first_name'] ?? '') . ' ' . ($p['last_name'] ?? '')) ?: '—';
              $txn         = $p['gateway_capture_id'] ?: ($p['gateway_order_id'] ?: ($p['gateway_session_id'] ?: '—'));
              $txnShort    = $txn !== '—' ? mb_substr($txn, 0, 22) . '…' : '—';
              $title       = $p['article_title'] ? mb_substr($p['article_title'], 0, 45) . (mb_strlen($p['article_title']) > 45 ? '…' : '') : '—';
              $date        = $isCompleted && $p['paid_at']
                             ? date('d M Y, H:i', strtotime($p['paid_at']))
                             : date('d M Y, H:i', strtotime($p['created_at']));
              $sym         = getCurrSymbol($p['currency'] ?? 'USD');
              $amtColor    = match($p['currency'] ?? 'USD') {
                  'INR' => 'text-blue-700', 'NGN' => 'text-orange-600',
                  'USD' => 'text-emerald-700', default => 'text-gray-700'
              };
            ?>
            <tr>
              <td class="text-gray-400 text-xs"><?= (int)$p['payment_id'] ?></td>
              <td>
                <span class="mono"><?= p($p['tracking_code']) ?></span>
              </td>
              <td>
                <div class="font-semibold text-gray-800 text-sm"><?= p($authorName) ?></div>
                <div class="text-xs text-gray-400"><?= p($p['author_email'] ?? '') ?></div>
              </td>
              <td>
                <?php if (!empty($p['author_country'])): ?>
                <span class="text-xs text-gray-600 bg-gray-100 px-2 py-0.5 rounded-full">
                  <?= p($p['author_country']) ?>
                </span>
                <?php else: ?>
                <span class="text-gray-300 text-xs">—</span>
                <?php endif; ?>
              </td>
              <td>
                <div class="text-xs text-gray-700 max-w-[180px]"><?= p($title) ?></div>
                <?php if (!empty($p['journal_name'])): ?>
                <div class="text-xs text-gray-400 mt-0.5"><?= p(mb_substr($p['journal_name'], 0, 30)) ?></div>
                <?php endif; ?>
              </td>
              <td>
                <span class="text-xs font-bold px-2 py-1 rounded-md g-<?= p(strtolower($p['gateway'])) ?>">
                  <?= p(ucfirst($p['gateway'])) ?>
                </span>
              </td>
              <td>
                <span class="amount-val <?= $amtColor ?>">
                  <?= $sym . number_format((float)$p['amount'], 2) ?>
                </span>
                <div class="text-xs text-gray-400"><?= p($p['currency']) ?></div>
              </td>
              <td>
                <span class="text-xs font-bold px-2 py-1 rounded-full s-<?= p($p['status']) ?>">
                  <?= p(ucfirst(strtolower($p['status']))) ?>
                </span>
              </td>
              <td>
                <?php if ($txn !== '—'): ?>
                <span class="mono text-xs" title="<?= p($txn) ?>"><?= p($txnShort) ?></span>
                <?php else: ?>
                <span class="text-gray-300 text-xs">—</span>
                <?php endif; ?>
              </td>
              <td class="text-xs text-gray-500 whitespace-nowrap"><?= $date ?></td>
              <td>
                <div class="flex items-center gap-1">
                  <?php if (!empty($p['submission_id'])): ?>
                  <a href="submission_view.php?id=<?= (int)$p['submission_id'] ?>"
                     class="text-blue-500 hover:text-blue-700 text-xs p-1.5 rounded hover:bg-blue-50 transition"
                     title="View Submission">
                    <i class="fas fa-file-alt"></i>
                  </a>
                  <?php endif; ?>
                 
                  <button onclick="showDetails(<?= htmlspecialchars(json_encode($p)) ?>)"
                          class="text-gray-400 hover:text-gray-700 text-xs p-1.5 rounded hover:bg-gray-100 transition"
                          title="Details">
                    <i class="fas fa-eye"></i>
                  </button>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>

      <!-- Pagination -->
      <?php if ($total_pages > 1): ?>
      <div class="px-5 py-4 border-t border-gray-100 flex items-center justify-between flex-wrap gap-3">
        <div class="text-sm text-gray-500">
          Showing <?= number_format(($page-1)*$per_page + 1) ?>–<?= number_format(min($page*$per_page, $total_records)) ?>
          of <?= number_format($total_records) ?> records
        </div>
        <div class="flex gap-1">
          <?php
          $baseQ = http_build_query(array_merge($_GET, ['page' => '']));
          for ($i = max(1, $page-3); $i <= min($total_pages, $page+3); $i++):
          ?>
          <a href="?<?= $baseQ . $i ?>"
             class="px-3 py-1.5 rounded-lg text-sm font-semibold border transition
                    <?= $i === $page
                        ? 'bg-blue-600 text-white border-blue-600'
                        : 'bg-white text-gray-600 border-gray-200 hover:bg-gray-50' ?>">
            <?= $i ?>
          </a>
          <?php endfor; ?>
        </div>
      </div>
      <?php endif; ?>
    </div>

  </main>
</div>

<!-- ── Detail Modal ── -->
<div id="detailModal" class="fixed inset-0 z-50 hidden" style="background:rgba(0,0,0,.5)">
  <div class="flex items-center justify-center min-h-screen p-4">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto" id="modalBox">
      <div class="flex items-center justify-between px-6 py-4 border-b border-gray-100">
        <span class="font-bold text-gray-800 flex items-center gap-2">
          <i class="fas fa-receipt text-blue-500"></i> Payment Details
        </span>
        <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 w-8 h-8 rounded-lg flex items-center justify-center hover:bg-gray-100">
          <i class="fas fa-times"></i>
        </button>
      </div>
      <div class="p-6" id="modalContent">
        <!-- filled by JS -->
      </div>
    </div>
  </div>
</div>

<script>
let sc = false;
function toggleMobile(){ document.getElementById('sidebar')?.classList.toggle('mobile-open'); }
function toggleSidebar(){
    sc = !sc;
    document.getElementById('sidebar')?.classList.toggle('collapsed', sc);
    document.getElementById('content')?.classList.toggle('collapsed-sidebar', sc);
}
document.getElementById('darkToggle').addEventListener('click', function(){
    document.body.classList.toggle('dark');
    this.querySelector('i').classList.toggle('fa-moon');
    this.querySelector('i').classList.toggle('fa-sun');
    localStorage.setItem('dm', document.body.classList.contains('dark') ? '1' : '0');
});
if (localStorage.getItem('dm') === '1') {
    document.body.classList.add('dark');
    document.getElementById('darkToggle').querySelector('i').classList.replace('fa-moon', 'fa-sun');
}

// Search on Enter
document.querySelector('input[name=search]').addEventListener('keydown', function(e){
    if (e.key === 'Enter') this.closest('form').submit();
});

// Detail modal
const symMap = {'INR':'₹','USD':'$','NGN':'₦','BDT':'৳','PKR':'Rs ','PHP':'₱','MYR':'RM ','IDR':'Rp ','KES':'KSh ','GHS':'₵ '};
function getCurrSym(c){ return symMap[c] || '$'; }

function showDetails(p) {
    const sym = getCurrSym(p.currency);
    const txn = p.gateway_capture_id || p.gateway_order_id || p.gateway_session_id || '—';
    const date = p.paid_at || p.created_at || '—';

    document.getElementById('modalContent').innerHTML = `
      <div class="space-y-3 text-sm">
        <div class="grid grid-cols-2 gap-3">
          <div><div class="text-xs text-gray-400 mb-1">Payment ID</div><span class="font-mono text-xs bg-gray-100 px-2 py-1 rounded">#${p.payment_id}</span></div>
          <div><div class="text-xs text-gray-400 mb-1">Status</div><span class="font-bold text-xs px-2 py-1 rounded-full s-${p.status}">${p.status}</span></div>
          <div><div class="text-xs text-gray-400 mb-1">Tracking Code</div><span class="font-mono text-xs bg-gray-100 px-2 py-1 rounded">${p.tracking_code || '—'}</span></div>
          <div><div class="text-xs text-gray-400 mb-1">Gateway</div><span class="font-bold text-xs px-2 py-1 rounded g-${(p.gateway||'').toLowerCase()}">${p.gateway || '—'}</span></div>
          <div><div class="text-xs text-gray-400 mb-1">Amount</div><span class="font-bold text-lg">${sym}${parseFloat(p.amount||0).toFixed(2)} ${p.currency}</span></div>
          <div><div class="text-xs text-gray-400 mb-1">Date</div><span class="text-gray-700">${date}</span></div>
        </div>
        <hr>
        <div><div class="text-xs text-gray-400 mb-1">Payer Name</div><div class="font-semibold">${p.payer_name || '—'}</div></div>
        <div><div class="text-xs text-gray-400 mb-1">Payer Email</div><div>${p.payer_email || '—'}</div></div>
        <div><div class="text-xs text-gray-400 mb-1">Country</div><div>${p.author_country || '—'}</div></div>
        <hr>
        <div><div class="text-xs text-gray-400 mb-1">Transaction ID</div><div class="font-mono text-xs break-all bg-gray-50 p-2 rounded">${txn}</div></div>
        ${p.article_title ? `<div><div class="text-xs text-gray-400 mb-1">Article</div><div class="text-gray-700">${p.article_title}</div></div>` : ''}
      </div>
    `;
    document.getElementById('detailModal').classList.remove('hidden');
}
function closeModal(){
    document.getElementById('detailModal').classList.add('hidden');
}
document.getElementById('detailModal').addEventListener('click', function(e){
    if (e.target === this) closeModal();
});
document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closeModal(); });
</script>
</body>
</html>