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

$users = readJson(USERS_FILE);
$userList = [];
foreach ($users as $u) {
    if (!empty($u['webhook_url'])) {
        $userList[] = ['id' => $u['id'], 'name' => $u['name'] ?? '', 'email' => $u['email'] ?? '', 'webhook_url' => $u['webhook_url']];
    }
}

$result = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send_test') {
    $targetUrl = trim($_POST['webhook_url'] ?? '');
    if (empty($targetUrl) || !filter_var($targetUrl, FILTER_VALIDATE_URL)) {
        $result = ['success' => false, 'error' => 'Invalid webhook URL'];
    } else {
        $payload = json_encode([
            'event' => 'payment.received',
            'timestamp' => nowIST()->format('Y-m-d H:i:s'),
            'data' => [
                'order_id' => 'TEST_' . strtoupper(bin2hex(random_bytes(4))),
                'amount' => '99.00',
                'sender_name' => 'Test User',
                'utr' => 'TESTUTR' . rand(100000, 999999),
                'transaction_id' => 'TXN_TEST_' . rand(100000, 999999),
                'payment_time' => nowIST()->format('Y-m-d H:i:s'),
                'upi_id' => 'test@fam'
            ]
        ], JSON_PRETTY_PRINT);

        $ch = curl_init($targetUrl);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'X-FamAPI-Event: payment.received',
                'X-FamAPI-Signature: ' . hash_hmac('sha256', $payload, ENCRYPTION_KEY)
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => true
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        $time = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
        curl_close($ch);

        $result = [
            'success' => $error === '' && $httpCode >= 200 && $httpCode < 400,
            'http_code' => $httpCode,
            'response' => $response,
            'error' => $error ?: 'None',
            'time' => round($time * 1000) . 'ms',
            'payload' => $payload,
            'url' => $targetUrl
        ];
    }
}

$pageTitle = 'Webhook Tester';
$pageSub = 'Test and debug webhook delivery for any connected user.';
include __DIR__ . '/../includes/admin_header.php';
?>

<div class="admin-wrap">
  <div class="card" style="max-width:800px">
    <h2 class="card-title"><i class="fa-solid fa-satellite-dish"></i> Send Test Webhook</h2>
    <p style="color:var(--muted);font-size:0.88rem;margin-top:-4px;margin-bottom:1.2rem">Ek test payload bhejo kisi bhi webhook URL pe. Isse tum check kar sakte ho ki webhook sahi kaam kar raha hai ya nahi.</p>

    <form method="POST" style="display:flex;flex-direction:column;gap:16px">
      <input type="hidden" name="action" value="send_test">
      <div>
        <label style="display:block;font-size:0.85rem;color:var(--muted);margin-bottom:6px">Select User (auto-fills webhook URL)</label>
        <select id="userSelect" onchange="document.getElementById('webhookUrl').value=this.value" style="width:100%;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);border-radius:8px;padding:10px 14px;color:#f1f5f9;font-size:0.88rem">
          <option value="">-- Manual URL Entry --</option>
          <?php foreach ($userList as $u): ?>
          <option value="<?= htmlspecialchars($u['webhook_url']) ?>"><?= htmlspecialchars($u['name'] . ' (' . $u['email'] . ')') ?></option>
          <?php endforeach; ?>
          <?php if (empty($userList)): ?>
          <option disabled>No users have set a webhook URL yet</option>
          <?php endif; ?>
        </select>
      </div>
      <div>
        <label style="display:block;font-size:0.85rem;color:var(--muted);margin-bottom:6px">Webhook URL</label>
        <input type="url" name="webhook_url" id="webhookUrl" placeholder="https://your-server.com/webhook" required style="width:100%;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);border-radius:8px;padding:10px 14px;color:#f1f5f9;font-size:0.88rem;outline:none;box-sizing:border-box" />
      </div>
      <button type="submit" style="background:#3b82f6;color:#fff;border:none;border-radius:8px;padding:12px 24px;font-size:0.92rem;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:8px;width:fit-content">
        <i class="fa-solid fa-paper-plane"></i> Send Test Webhook
      </button>
    </form>
  </div>

  <?php if ($result): ?>
  <div class="card" style="max-width:800px;margin-top:20px;border-left:3px solid <?= $result['success'] ? '#34d399' : '#f87171' ?>">
    <h2 class="card-title" style="color:<?= $result['success'] ? '#34d399' : '#f87171' ?>">
      <i class="fa-solid fa-<?= $result['success'] ? 'circle-check' : 'circle-xmark' ?>"></i>
      <?= $result['success'] ? 'Webhook Delivered!' : 'Delivery Failed' ?>
    </h2>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;margin:16px 0">
      <div style="background:rgba(255,255,255,0.04);border-radius:8px;padding:12px;text-align:center">
        <div style="font-size:0.75rem;color:var(--muted)">HTTP Status</div>
        <div style="font-size:1.3rem;font-weight:700;color:<?= $result['http_code'] >= 200 && $result['http_code'] < 400 ? '#34d399' : '#f87171' ?>"><?= $result['http_code'] ?></div>
      </div>
      <div style="background:rgba(255,255,255,0.04);border-radius:8px;padding:12px;text-align:center">
        <div style="font-size:0.75rem;color:var(--muted)">Response Time</div>
        <div style="font-size:1.3rem;font-weight:700;color:#3b82f6"><?= $result['time'] ?></div>
      </div>
      <div style="background:rgba(255,255,255,0.04);border-radius:8px;padding:12px;text-align:center">
        <div style="font-size:0.75rem;color:var(--muted)">Error</div>
        <div style="font-size:0.85rem;font-weight:600;color:<?= $result['error'] === 'None' ? '#34d399' : '#f87171' ?>"><?= htmlspecialchars($result['error']) ?></div>
      </div>
    </div>
    <div style="margin-top:16px">
      <div style="font-size:0.82rem;color:var(--muted);margin-bottom:6px">Target URL</div>
      <div style="background:#0f172a;border-radius:8px;padding:10px 14px;font-family:monospace;font-size:0.82rem;color:#38bdf8;word-break:break-all"><?= htmlspecialchars($result['url']) ?></div>
    </div>
    <div style="margin-top:14px">
      <div style="font-size:0.82rem;color:var(--muted);margin-bottom:6px">Payload Sent</div>
      <pre style="background:#0f172a;border-radius:8px;padding:14px;font-family:monospace;font-size:0.8rem;color:#a5f3fc;overflow-x:auto;margin:0;line-height:1.6"><?= htmlspecialchars($result['payload']) ?></pre>
    </div>
    <div style="margin-top:14px">
      <div style="font-size:0.82rem;color:var(--muted);margin-bottom:6px">Response Body</div>
      <pre style="background:#0f172a;border-radius:8px;padding:14px;font-family:monospace;font-size:0.8rem;color:#86efac;overflow-x:auto;margin:0;line-height:1.6"><?= htmlspecialchars($result['response'] ?: '(empty response)') ?></pre>
    </div>
  </div>
  <?php endif; ?>

  <div class="card" style="max-width:800px;margin-top:20px">
    <h2 class="card-title"><i class="fa-solid fa-book"></i> Webhook Format Reference</h2>
    <p style="color:var(--muted);font-size:0.85rem;margin-top:-4px">Jab payment hoti hai to tumhare server pe yeh payload aata hai:</p>
    <pre style="background:#0f172a;border-radius:8px;padding:14px;font-family:monospace;font-size:0.8rem;color:#e2e8f0;overflow-x:auto;margin-top:12px;line-height:1.6">{
  "event": "payment.received",
  "timestamp": "2026-08-22 15:30:00",
  "data": {
    "order_id": "ORD_XXXXXXXX",
    "amount": "99.00",
    "sender_name": "Aditya Kumar",
    "utr": "2026082212345678901234",
    "transaction_id": "TXNXXXXXXXXXXXX",
    "payment_time": "2026-08-22 15:29:45",
    "upi_id": "aditya@fam"
  }
}</pre>
    <div style="margin-top:16px">
      <div style="font-size:0.85rem;color:var(--muted);margin-bottom:8px"><strong>Headers:</strong></div>
      <div style="display:flex;flex-direction:column;gap:6px">
        <code style="background:rgba(255,255,255,0.06);padding:6px 12px;border-radius:6px;font-size:0.82rem;color:#fbbf24">X-FamAPI-Event: payment.received</code>
        <code style="background:rgba(255,255,255,0.06);padding:6px 12px;border-radius:6px;font-size:0.82rem;color:#38bdf8">X-FamAPI-Signature: hmac-sha256-signature</code>
        <code style="background:rgba(255,255,255,0.06);padding:6px 12px;border-radius:6px;font-size:0.82rem;color:#e2e8f0">Content-Type: application/json</code>
      </div>
    </div>
  </div>

  <div class="card" style="max-width:800px;margin-top:20px">
    <h2 class="card-title"><i class="fa-solid fa-vial"></i> Quick Test: Use Our Receiver</h2>
    <p style="color:var(--muted);font-size:0.85rem;margin-top:-4px;margin-bottom:12px">Agar tumhara khud ka server nahi hai, to hamare built-in test receiver ka use karo:</p>
    <div style="background:#0f172a;border-radius:8px;padding:12px 16px;font-family:monospace;font-size:0.85rem;color:#86efac;word-break:break-all">https://fampay.adityahost.in/webhook_test.php</div>
    <p style="color:var(--muted);font-size:0.82rem;margin-top:10px">Yeh endpoint har webhook payload save karta hai. Last 50 payloads dikhai dete hain.</p>
    <a href="../webhook_test.php" target="_blank" style="display:inline-block;margin-top:12px;color:#3b82f6;font-size:0.85rem;text-decoration:none;font-weight:600">View Received Webhooks <i class="fa-solid fa-arrow-right" style="font-size:0.7rem"></i></a>
  </div>
</div>

<?php include __DIR__ . '/../includes/admin_footer.php'; ?>
