<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

$recentOrders = getRecentOrders(30);

// Also fetch pending payment links to show them in the simulation table
$links = getDB()->query("SELECT slug as order_id, user_id, amount, status, created_at FROM payment_links WHERE status='pending' ORDER BY created_at DESC LIMIT 30")->fetchAll(PDO::FETCH_ASSOC);

$recentItems = array_merge($recentOrders, $links);
usort($recentItems, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

$userIds = array_unique(array_filter(array_column($recentItems, 'user_id')));
$usersById = [];
if (!empty($userIds)) {
    $placeholders = implode(',', array_fill(0, count($userIds), '?'));
    $stmt = getDB()->prepare("SELECT id, name FROM users WHERE id IN ($placeholders)");
    $stmt->execute(array_values($userIds));
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $u) {
        $usersById[$u['id']] = $u;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $pageTitle = "Simulate Payment — Admin Control Panel"; include __DIR__ . '/admin-style.php'; ?>
</head>
<body>
<?php include __DIR__ . '/admin-nav.php'; ?>
    <div class="wrap">
      <div style="margin-bottom:24px;">
        <h1 style="font-size:22px;font-weight:700;color:var(--color-ink);letter-spacing:-0.5px;display:flex;align-items:center;gap:8px;">
          <i data-lucide="test-tube" style="color:#3b82f6;width:24px;height:24px;"></i> Simulate Payment
        </h1>
        <p style="font-size:13px;color:var(--color-ink-mute);margin-top:4px;">Manually trigger a successful payment callback for any pending order.</p>
      </div>

      <div class="card" style="max-width:600px; margin-bottom: 24px;">
        <div class="card-title" style="margin-bottom:16px;">Simulate by Order ID</div>
        <div style="display:flex; gap:12px;">
            <input type="text" id="simOrderId" class="form-input" placeholder="e.g. fg_A1B2..." style="flex:1;">
            <button class="btn btn-primary" onclick="simulatePay()" style="padding: 0 24px;">Simulate <i data-lucide="zap" style="width:16px;height:16px;margin-left:4px;"></i></button>
        </div>
      </div>

      <div class="card" style="padding:0;overflow:hidden;margin-bottom:0;">
          <div style="padding:22px 28px 18px;">
            <div class="card-title">Recent Pending Orders</div>
            <div class="card-sub">Click simulate to instantly mark an order as paid</div>
          </div>
          <div class="table-container" style="margin:0;border-radius:0 0 var(--r-xl) var(--r-xl);">
            <table class="table">
              <thead>
                <tr>
                  <th>Order ID</th>
                  <th>Amount</th>
                  <th>User</th>
                  <th>Date</th>
                  <th style="text-align:right;">Action</th>
                </tr>
              </thead>
              <tbody>
                <?php 
                $hasPending = false;
                if (!empty($recentItems)): 
                  foreach ($recentItems as $ro):
                    if ($ro['status'] !== 'pending') continue;
                    $hasPending = true;
                    $uName = 'Guest (Demo)';
                    if (!empty($ro['user_id']) && isset($usersById[$ro['user_id']])) $uName = $usersById[$ro['user_id']]['name'];
                ?>
                <tr>
                  <td class="tnum" style="font-weight:600;color:var(--blue-700);font-size:13px;"><?= htmlspecialchars($ro['order_id']) ?></td>
                  <td class="tnum" style="font-weight:700;">₹<?= number_format($ro['amount'], 2) ?></td>
                  <td style="font-weight:500;"><?= htmlspecialchars($uName) ?></td>
                  <td style="color:var(--color-ink-mute);font-size:12px;"><?= htmlspecialchars(date('M d, h:i A', strtotime($ro['created_at']))) ?></td>
                  <td style="text-align:right;">
                    <button class="btn btn-secondary" onclick="simulatePayWithId('<?= htmlspecialchars($ro['order_id']) ?>')" style="padding:4px 12px;font-size:12px;height:auto;">Simulate</button>
                  </td>
                </tr>
                <?php endforeach; endif; ?>
                
                <?php if (!$hasPending): ?>
                <tr><td colspan="5">
                  <div class="empty-state">
                    <div class="empty-state-icon"><i data-lucide="check-circle"></i></div>
                    <div class="empty-state-title">No pending orders</div>
                    <div class="empty-state-sub">All recent orders have been processed.</div>
                  </div>
                </td></tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>

    </div>
  </main>
</div>
<script>
    if (window.lucide) { lucide.createIcons(); }
    
    function simulatePay() {
        const oid = document.getElementById('simOrderId').value.trim();
        if(!oid) { alert('Enter Order ID'); return; }
        executeSimulate(oid);
    }
    function simulatePayWithId(oid) {
        if(confirm('Simulate successful payment for ' + oid + '?')) {
            executeSimulate(oid);
        }
    }
    function executeSimulate(oid) {
        const formData = new FormData();
        formData.append('order_id', oid);
        formData.append('csrf_token', '<?= csrfToken() ?>');
        
        fetch('../api/simulate-payment.php', {
            method: 'POST',
            body: formData
        })
        .then(r=>r.text())
        .then(t => {
            alert(t);
            window.location.reload();
        }).catch(e => {
            alert('Error simulating payment.');
        });
    }
</script>
</body>
</html>
