<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();
$baseUrl = getBaseUrl();

$loggedIn = isLoggedIn();
$user = null;
if ($loggedIn) {
    $user = getUserById($_SESSION['user_id']);
    if (!$user) $loggedIn = false;
}

if ($loggedIn) {
    $pageTitle = 'Documentation';
    $activeNav = 'docs';
    include __DIR__ . '/includes/user_header.php';
} else {
    $pageTitle = 'Developer Docs';
    include __DIR__ . '/includes/public_header.php';
    include __DIR__ . '/includes/nav.php';
}
?>

<div class="wrap docs-wrap" style="max-width:900px;">
  <div class="page-head">
    <h1 class="page-title">Developer Documentation</h1>
    <p class="page-sub">FamPay UPI payments ko 2 API calls mein integrate karo. QR generate karo, payment verify karo — bas.</p>
  </div>

  <div class="docs-callout">
    <strong>Shuru karne se pehle:</strong> Account register karo, dashboard mein apna FamPay Gmail connect karo, aur API key copy karo.
  </div>

  <button class="btn btn-secondary btn-block" id="copyAllBtn" onclick="copyAllDocs()" style="margin-bottom:32px;">Copy full documentation</button>

  <div id="docsContent">

  <!-- SECTION 0: Base URL -->
  <div class="docs-section" id="base">
    <h2><span class="docs-num">0</span> Base URL</h2>
    <p class="desc">Sabhi API endpoints is base URL ke relative hain:</p>
    <div class="code-block">
      <div class="code-label">Base URL <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre><?= htmlspecialchars($baseUrl) ?></pre>
    </div>
    <p class="desc">Har request mein <code>api_key</code> query parameter mandatory hai. Yeh aapko dashboard mein milta hai.</p>
  </div>

  <!-- SECTION 1: Create Order + QR -->
  <div class="docs-section" id="create-order">
    <h2><span class="docs-num">1</span> Create Order &amp; Generate QR</h2>
    <p class="desc">Ek naya order create karo aur UPI QR code generate karo. Customer ko yeh QR dikhao ya share karo payment lene ke liye.</p>

    <div class="docs-badge" style="background:rgba(59,130,246,0.12);color:#3b82f6;margin:12px 0"><i class="fa-solid fa-circle-info"></i> Yeh public endpoint hai — koi bhi call kar sakta hai bina login ke.</div>

    <h3 style="margin-top:18px;margin-bottom:10px;font-size:0.9rem;color:#f1f5f9"><i class="fa-solid fa-globe" style="color:#3b82f6"></i> Endpoint</h3>
    <div class="code-block">
      <div class="code-label">GET <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>GET <?= htmlspecialchars($baseUrl) ?>/api/qr.php?api_key=YOUR_KEY&amp;upi=YOUR_UPI&amp;amount=100</pre>
    </div>

    <h3 style="margin-top:18px;margin-bottom:10px;font-size:0.9rem;color:#f1f5f9"><i class="fa-solid fa-list" style="color:#a370fc"></i> Parameters</h3>
    <div class="table-wrap" style="margin-bottom:18px;">
    <table class="data-table">
      <tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr>
      <tr><td><code>api_key</code></td><td>string</td><td><span class="badge badge-red">Required</span></td><td>Aapka API key (dashboard se milega)</td></tr>
      <tr><td><code>upi</code></td><td>string</td><td><span class="badge badge-red">Required</span></td><td>UPI ID jahan payment aayegi (e.g. <code>yourname@fam</code>)</td></tr>
      <tr><td><code>amount</code></td><td>number</td><td><span class="badge badge-red">Required</span></td><td>Payment amount in INR (e.g. <code>100</code>)</td></tr>
    </table>
    </div>

    <h3 style="margin-top:18px;margin-bottom:10px;font-size:0.9rem;color:#f1f5f9"><i class="fa-solid fa-circle-check" style="color:#34d399"></i> Success Response — 200</h3>
    <div class="code-block">
      <div class="code-label">JSON Response <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>{
  "status": "success",
  "data": {
    "order_id":       "FAMPAY20260822214237F3F0C1",
    "qr_url":         "<?= htmlspecialchars($baseUrl) ?>/api/qr_image.php?order_id=FAMPAY20260822214237F3F0C1",
    "upi_id":         "yourname@fam",
    "amount":         "100",
    "created_at_ist": "22-08-2026 21:42:37",
    "expires_at_ist": "22-08-26 21:47:37",
    "checkout_url":   "<?= htmlspecialchars($baseUrl) ?>/pay.php?api_key=YOUR_KEY&amount=100",
    "open_in_new_tab": true
  }
}</pre>
    </div>
    <p class="desc" style="margin-top:10px;"><b>Response fields:</b></p>
    <div class="table-wrap" style="margin-bottom:18px;">
    <table class="data-table">
      <tr><th>Field</th><th>Description</th></tr>
      <tr><td><code>order_id</code></td><td>Unique order ID — isko verify ke liye store karo</td></tr>
      <tr><td><code>qr_url</code></td><td>QR code image URL — directly image mein dikhao customer ko</td></tr>
      <tr><td><code>upi_id</code></td><td>UPI ID jo payment receive karegi</td></tr>
      <tr><td><code>amount</code></td><td>Amount string mein</td></tr>
      <tr><td><code>created_at_ist</code></td><td>Order creation time (IST timezone)</td></tr>
      <tr><td><code>expires_at_ist</code></td><td>Order expiry time (5 min baad expire)</td></tr>
      <tr><td><code>checkout_url</code></td><td>Hosted checkout page URL — browser mein redirect karo</td></tr>
      <tr><td><code>open_in_new_tab</code></td><td><code>true</code> — checkout_url ko naye tab mein open karo</td></tr>
    </table>
    </div>

    <h3 style="margin-top:18px;margin-bottom:10px;font-size:0.9rem;color:#f1f5f9"><i class="fa-solid fa-circle-xmark" style="color:#f87171"></i> Error Responses</h3>
    <div class="code-block">
      <div class="code-label">401 — Missing api_key <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>{ "status": "unauthorized", "message": "Missing api_key" }</pre>
    </div>
    <div class="code-block">
      <div class="code-label">401 — Invalid api_key <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>{ "status": "unauthorized", "message": "Invalid api_key" }</pre>
    </div>
    <div class="code-block">
      <div class="code-label">400 — Missing upi/amount <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>{ "status": "error", "message": "Missing or invalid upi/amount parameters" }</pre>
    </div>
    <div class="code-block">
      <div class="code-label">402 — Plan expired <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>{ "status": "expired", "message": "Your plan has expired, please renew." }</pre>
    </div>
    <div class="code-block">
      <div class="code-label">403 — Account suspended <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>{ "status": "suspended", "message": "Account suspended by admin" }</pre>
    </div>
    <div class="code-block">
      <div class="code-label">400 — Gmail not connected <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>{ "status": "error", "message": "FamPay Gmail not connected. Connect it in your dashboard first." }</pre>
    </div>
  </div>

  <!-- SECTION 2: Verify Payment -->
  <div class="docs-section" id="verify">
    <h2><span class="docs-num">2</span> Verify Payment</h2>
    <p class="desc">Customer ne QR scan karke payment kar di? Ab is endpoint ko poll karo. Hamari system automatically aapke connected Gmail inbox check karti hai — agar FamPay se payment email aayi hai to order success ho jayega.</p>

    <div class="docs-badge" style="background:rgba(251,191,36,0.12);color:#fbbf24;margin:12px 0"><i class="fa-solid fa-clock"></i> Har 2-3 seconds mein poll karo jab tak payment success ya expire na ho jaye.</div>

    <h3 style="margin-top:18px;margin-bottom:10px;font-size:0.9rem;color:#f1f5f9"><i class="fa-solid fa-globe" style="color:#3b82f6"></i> Endpoint</h3>
    <div class="code-block">
      <div class="code-label">GET <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>GET <?= htmlspecialchars($baseUrl) ?>/api/verify_order.php?api_key=YOUR_KEY&amp;order_id=FAMPAYXXXXXXXXXX</pre>
    </div>

    <h3 style="margin-top:18px;margin-bottom:10px;font-size:0.9rem;color:#f1f5f9"><i class="fa-solid fa-list" style="color:#a370fc"></i> Parameters</h3>
    <div class="table-wrap" style="margin-bottom:18px;">
    <table class="data-table">
      <tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr>
      <tr><td><code>api_key</code></td><td>string</td><td><span class="badge badge-red">Required</span></td><td>Aapka API key</td></tr>
      <tr><td><code>order_id</code></td><td>string</td><td><span class="badge badge-red">Required</span></td><td>Create Order response se mila <code>order_id</code></td></tr>
    </table>
    </div>

    <h3 style="margin-top:18px;margin-bottom:10px;font-size:0.9rem;color:#f1f5f9"><i class="fa-solid fa-circle-check" style="color:#34d399"></i> Success Response — 200 (Payment received)</h3>
    <div class="code-block">
      <div class="code-label">JSON Response <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>{
  "status": "success",
  "data": {
    "order_id":         "FAMPAY20260822214237F3F0C1",
    "transaction_id":   "FMPXXXXXXXXX",
    "amount":           100.0,
    "utr":              "2026082212345678901234",
    "sender_name":      "Aditya Kumar",
    "payment_time_ist": "22-08-2026 21:44:15"
  }
}</pre>
    </div>

    <h3 style="margin-top:18px;margin-bottom:10px;font-size:0.9rem;color:#f1f5f9"><i class="fa-solid fa-clock" style="color:#fbbf24"></i> Pending Response — 200</h3>
    <div class="code-block">
      <div class="code-label">JSON Response <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>{
  "status": "pending",
  "message": "Payment not received yet"
}</pre>
    </div>
    <p class="desc" style="margin-top:8px;">Jab tak <code>status: "pending"</code> aata hai, customer ne payment nahi ki. Polling continue karo.</p>

    <h3 style="margin-top:18px;margin-bottom:10px;font-size:0.9rem;color:#f1f5f9"><i class="fa-solid fa-circle-xmark" style="color:#f87171"></i> Other Responses</h3>
    <div class="code-block">
      <div class="code-label">408 — Order expired <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>{ "status": "expired", "message": "Order expired (5 min timeout)" }</pre>
    </div>
    <p class="desc" style="margin-top:8px;">Order 5 minute mein expire hota hai. Naya order create karo aur dobara QR dikhao.</p>
  </div>

  <!-- SECTION 3: Hosted Checkout -->
  <div class="docs-section" id="checkout">
    <h2><span class="docs-num">3</span> Hosted Checkout Page</h2>
    <p class="desc">Agar tumhe apna frontend nahi banana — sirf customer ko redirect karo hamare hosted checkout page pe. Yeh page QR generate karta hai, payment detect karta hai, aur success page dikhata hai — sab automated.</p>

    <div class="code-block">
      <div class="code-label">Redirect URL <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>GET <?= htmlspecialchars($baseUrl) ?>/pay.php?api_key=YOUR_KEY&amp;amount=100&amp;upi=YOUR_UPI</pre>
    </div>

    <div class="table-wrap" style="margin-bottom:18px;margin-top:14px;">
    <table class="data-table">
      <tr><th>Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr>
      <tr><td><code>api_key</code></td><td>string</td><td><span class="badge badge-red">Required</span></td><td>Aapka API key</td></tr>
      <tr><td><code>amount</code></td><td>number</td><td><span class="badge badge-red">Required</span></td><td>Payment amount</td></tr>
      <tr><td><code>upi</code></td><td>string</td><td><span class="badge badge-blue">Optional</span></td><td>UPI ID override (default: dashboard UPI)</td></tr>
      <tr><td><code>name</code></td><td>string</td><td><span class="badge badge-blue">Optional</span></td><td>Payment name / product name</td></tr>
      <tr><td><code>redirect_url</code></td><td>string</td><td><span class="badge badge-blue">Optional</span></td><td>Payment success ke baad redirect URL</td></tr>
    </table>
    </div>
    <p class="desc" style="margin-top:10px;">Customer ko simply is URL pe redirect karo. Checkout page khud QR dikhayega, payment detect karega, aur success page dikha dega.</p>
  </div>

  <!-- SECTION 4: Complete Flow -->
  <div class="docs-section" id="flow">
    <h2><span class="docs-num">4</span> Complete Integration Flow</h2>
    <p class="desc">Yeh hai complete 2-step flow jo tumhe follow karna hai:</p>

    <div style="display:flex;flex-direction:column;gap:14px;margin-top:16px">
      <div style="background:rgba(163,112,252,0.08);border:1px solid rgba(163,112,252,0.2);border-radius:10px;padding:16px">
        <div style="font-size:0.82rem;color:#a370fc;font-weight:700;margin-bottom:6px">STEP 1 — Create Order</div>
        <p class="desc">Customer ko payment karne bolo:</p>
        <pre style="background:#0f172a;border-radius:8px;padding:12px;font-size:0.82rem;color:#e2e8f0;margin-top:8px;font-family:'JetBrains Mono',monospace;line-height:1.5">GET /api/qr.php?api_key=KEY&amp;upi=merchant@upi&amp;amount=99</pre>
        <p class="desc" style="margin-top:8px;">Response se <code>qr_url</code> lo aur customer ko QR dikhao, ya <code>checkout_url</code> pe redirect karo.</p>
      </div>

      <div style="text-align:center;color:#64748b;font-size:1.5rem"><i class="fa-solid fa-arrow-down"></i></div>

      <div style="background:rgba(52,211,153,0.08);border:1px solid rgba(52,211,153,0.2);border-radius:10px;padding:16px">
        <div style="font-size:0.82rem;color:#34d399;font-weight:700;margin-bottom:6px">STEP 2 — Verify Payment</div>
        <p class="desc">Customer ne pay kar diya? Ab poll karo:</p>
        <pre style="background:#0f172a;border-radius:8px;padding:12px;font-size:0.82rem;color:#e2e8f0;margin-top:8px;font-family:'JetBrains Mono',monospace;line-height:1.5">GET /api/verify_order.php?api_key=KEY&amp;order_id=FAMPAYXXXXXX</pre>
        <p class="desc" style="margin-top:8px;">Har 2-3 sec poll karo. Jab <code>status: "success"</code> aaye — payment confirm!</p>
      </div>
    </div>
  </div>

  <!-- SECTION 5: Code Examples -->
  <div class="docs-section" id="examples">
    <h2><span class="docs-num">5</span> Code Examples</h2>

    <div style="display:flex;gap:8px;margin-bottom:14px;flex-wrap:wrap;margin-top:12px">
      <button class="btn btn-sm" style="background:rgba(163,112,252,0.15);color:#a370fc;border:1px solid rgba(163,112,252,0.3)" onclick="showExample('curl')">cURL</button>
      <button class="btn btn-sm" style="background:rgba(255,255,255,0.05);color:#94a3b8;border:1px solid rgba(255,255,255,0.08)" onclick="showExample('python')">Python</button>
      <button class="btn btn-sm" style="background:rgba(255,255,255,0.05);color:#94a3b8;border:1px solid rgba(255,255,255,0.08)" onclick="showExample('node')">Node.js</button>
      <button class="btn btn-sm" style="background:rgba(255,255,255,0.05);color:#94a3b8;border:1px solid rgba(255,255,255,0.08)" onclick="showExample('php')">PHP</button>
      <button class="btn btn-sm" style="background:rgba(255,255,255,0.05);color:#94a3b8;border:1px solid rgba(255,255,255,0.08)" onclick="showExample('js')">JavaScript</button>
    </div>
    <div id="exampleBlock" class="code-block" style="min-height:100px"></div>
  </div>

  <!-- SECTION 6: Error Codes -->
  <div class="docs-section" id="errors">
    <h2><span class="docs-num">6</span> HTTP Status Codes</h2>
    <div class="table-wrap">
    <table class="data-table">
      <tr><th>HTTP Code</th><th>Status</th><th>Meaning</th></tr>
      <tr><td><code>200</code></td><td><code>success / pending</code></td><td>Request processed. Check <code>status</code> field.</td></tr>
      <tr><td><code>400</code></td><td><code>error</code></td><td>Missing or invalid parameters (upi, amount, etc.)</td></tr>
      <tr><td><code>401</code></td><td><code>unauthorized</code></td><td>API key missing ya invalid hai</td></tr>
      <tr><td><code>402</code></td><td><code>expired</code></td><td>Plan expire ho gaya — dashboard se renew karo</td></tr>
      <tr><td><code>403</code></td><td><code>suspended</code></td><td>Account admin ne suspend kar diya</td></tr>
      <tr><td><code>404</code></td><td><code>not_found</code></td><td>Order ID nahi mila</td></tr>
      <tr><td><code>408</code></td><td><code>expired</code></td><td>Order expire ho gaya (5 min timeout)</td></tr>
      <tr><td><code>500</code></td><td><code>error</code></td><td>Server error</td></tr>
    </table>
    </div>
  </div>

  <!-- SECTION 7: Webhooks -->
  <div class="docs-section" id="webhooks">
    <h2><span class="docs-num">7</span> Webhooks</h2>
    <p class="desc">Agar tum chahte ho ki payment confirm hone pe tumhare server pe automatic notification aaye — webhook setup karo. Dashboard > API Keys mein apna webhook URL daal do.</p>
    <p class="desc" style="margin-top:10px;">Jab payment success hogi, tumhare server pe yeh POST request aayegi:</p>
    <div class="code-block">
      <div class="code-label">Webhook Payload <button class="copy-btn" onclick="copyBlock(this)">Copy</button></div>
      <pre>{
  "event": "payment.received",
  "timestamp": "2026-08-22 21:44:15",
  "data": {
    "order_id":       "FAMPAYXXXXXXXXXX",
    "amount":         "100",
    "sender_name":    "Aditya Kumar",
    "utr":            "2026082212345678901234",
    "transaction_id": "FMPXXXXXXXXX",
    "payment_time":   "2026-08-22 21:44:10",
    "upi_id":         "aditya@fam"
  }
}</pre>
    </div>
    <h3 style="margin-top:18px;margin-bottom:10px;font-size:0.9rem;color:#f1f5f9"><i class="fa-solid fa-shield-halved" style="color:#a370fc"></i> Signature Verification</h3>
    <p class="desc">Har webhook request ke saath 2 headers aate hain:</p>
    <div class="table-wrap" style="margin-bottom:12px;">
    <table class="data-table">
      <tr><th>Header</th><th>Description</th></tr>
      <tr><td><code>X-FamAPI-Event</code></td><td>Event type (<code>payment.received</code>)</td></tr>
      <tr><td><code>X-FamAPI-Signature</code></td><td>HMAC-SHA256 signature — isse verify karo ki request hamari hai</td></tr>
    </table>
    </div>
  </div>

  <!-- SECTION 8: Rate Limits -->
  <div class="docs-section" id="limits">
    <h2><span class="docs-num">8</span> Rate Limits &amp; Notes</h2>
    <div style="display:flex;flex-direction:column;gap:10px;margin-top:12px">
      <div style="background:rgba(255,255,255,0.03);border-radius:8px;padding:12px;font-size:0.88rem;color:#94a3b8"><i class="fa-solid fa-clock" style="color:#3b82f6;margin-right:8px"></i> Order expiry: 5 minute. Uske baad naya order create karo.</div>
      <div style="background:rgba(255,255,255,0.03);border-radius:8px;padding:12px;font-size:0.88rem;color:#94a3b8"><i class="fa-solid fa-rotate" style="color:#a370fc;margin-right:8px"></i> Verify endpoint ko poll karo — 1 baar mein nahi milta, 2-3 sec gap se poll karo.</div>
      <div style="background:rgba(255,255,255,0.03);border-radius:8px;padding:12px;font-size:0.88rem;color:#94a3b8"><i class="fa-solid fa-gauge-high" style="color:#fbbf24;margin-right:8px"></i> API rate limit: 30 requests/minute per API key.</div>
      <div style="background:rgba(255,255,255,0.03);border-radius:8px;padding:12px;font-size:0.88rem;color:#94a3b8"><i class="fa-solid fa-shield-halved" style="color:#34d399;margin-right:8px"></i> All data is AES-256 encrypted in transit. UPI credentials never exposed.</div>
    </div>
  </div>

  </div><!-- end docsContent -->
</div>

<script>
var EXAMPLES = {};
EXAMPLES.curl = "# Step 1: Create Order & QR\ncurl -s \"" + "<?= htmlspecialchars($baseUrl) ?>/api/qr.php?api_key=YOUR_KEY&upi=merchant@upi&amount=100\"\n\n# Response: { \"status\":\"success\", \"data\":{ \"order_id\":\"FAMPAY...\", \"qr_url\":\"...\" } }\n\n# Step 2: Verify Payment (poll every 2-3 sec)\ncurl -s \"" + "<?= htmlspecialchars($baseUrl) ?>/api/verify_order.php?api_key=YOUR_KEY&order_id=FAMPAYXXXXXXXXXX\"\n\n# Response when paid: { \"status\":\"success\", \"data\":{ \"utr\":\"...\", \"amount\":100 } }\n# Response when pending: { \"status\":\"pending\", \"message\":\"Payment not received yet\" }";

EXAMPLES.python = "import requests, time\n\nBASE = '" + "<?= htmlspecialchars($baseUrl) ?>'\n\n# Step 1: Create Order\nresp = requests.get(f'{BASE}/api/qr.php', params={\n    'api_key': 'YOUR_KEY',\n    'upi': 'merchant@upi',\n    'amount': 100\n})\ndata = resp.json()['data']\nprint(f'Order: {data[\"order_id\"]}')\nprint(f'QR: {data[\"qr_url\"]}')\n\n# Step 2: Poll for payment\nwhile True:\n    v = requests.get(f'{BASE}/api/verify_order.php', params={\n        'api_key': 'YOUR_KEY',\n        'order_id': data['order_id']\n    }).json()\n    if v['status'] == 'success':\n        print(f'Paid! UTR: {v[\"data\"][\"utr\"]}')\n        break\n    elif v['status'] == 'expired':\n        print('Order expired')\n        break\n    time.sleep(3)";

EXAMPLES.node = "const axios = require('axios');\nconst BASE = '" + "<?= htmlspecialchars($baseUrl) ?>';\n\n// Step 1: Create Order\nconst { data: { data } } = await axios.get(`${BASE}/api/qr.php`, {\n  params: { api_key: 'YOUR_KEY', upi: 'merchant@upi', amount: 100 }\n});\nconsole.log('Order:', data.order_id);\nconsole.log('QR URL:', data.qr_url);\n\n// Step 2: Poll for payment\nwhile (true) {\n  const { data: result } = await axios.get(`${BASE}/api/verify_order.php`, {\n    params: { api_key: 'YOUR_KEY', order_id: data.order_id }\n  });\n  if (result.status === 'success') {\n    console.log('Paid! UTR:', result.data.utr);\n    break;\n  }\n  if (result.status === 'expired') {\n    console.log('Order expired');\n    break;\n  }\n  await new Promise(r => setTimeout(r, 3000));\n}";

EXAMPLES.php = "<?php\n$BASE = '" + "<?= htmlspecialchars($baseUrl) ?>';\n\n// Step 1: Create Order\n$url = \"$BASE/api/qr.php?api_key=YOUR_KEY&upi=merchant@upi&amount=100\";\n$data = json_decode(file_get_contents($url), true)['data'];\necho \"Order: \" . $data['order_id'] . \"\\n\";\necho \"QR: \" . $data['qr_url'] . \"\\n\";\n\n// Step 2: Poll for payment\nwhile (true) {\n    $verify = json_decode(file_get_contents(\n        \"$BASE/api/verify_order.php?api_key=YOUR_KEY&order_id=\" . $data['order_id']\n    ), true);\n    if ($verify['status'] === 'success') {\n        echo \"Paid! UTR: \" . $verify['data']['utr'];\n        break;\n    }\n    if ($verify['status'] === 'expired') {\n        echo \"Order expired\";\n        break;\n    }\n    sleep(3);\n}";

EXAMPLES.js = "// Fetch API (Browser)\nconst BASE = '" + "<?= htmlspecialchars($baseUrl) ?>';\n\n// Step 1: Create Order\nconst resp = await fetch(\n  `${BASE}/api/qr.php?api_key=YOUR_KEY&upi=merchant@upi&amount=100`\n);\nconst { data } = await resp.json();\nconsole.log('Order:', data.order_id);\nconsole.log('QR URL:', data.qr_url);\n\n// Step 2: Poll for payment\nasync function pollPayment(orderId) {\n  while (true) {\n    const res = await fetch(\n      `${BASE}/api/verify_order.php?api_key=YOUR_KEY&order_id=${orderId}`\n    );\n    const result = await res.json();\n    if (result.status === 'success') {\n      console.log('Paid! UTR:', result.data.utr);\n      return result;\n    }\n    if (result.status === 'expired') {\n      console.log('Order expired');\n      return null;\n    }\n    await new Promise(r => setTimeout(r, 3000));\n  }\n}\npollPayment(data.order_id);";

showExample('curl');

function showExample(lang) {
    document.getElementById('exampleBlock').textContent = EXAMPLES[lang];
    document.querySelectorAll('.docs-section#examples .btn-sm').forEach(function(b) {
        b.style.background = 'rgba(255,255,255,0.05)';
        b.style.color = '#94a3b8';
        b.style.border = '1px solid rgba(255,255,255,0.08)';
    });
    event.target.style.background = 'rgba(163,112,252,0.15)';
    event.target.style.color = '#a370fc';
    event.target.style.border = '1px solid rgba(163,112,252,0.3)';
}

function copyBlock(btn) {
    var pre = btn.closest('.code-block').querySelector('pre');
    navigator.clipboard.writeText(pre.innerText).then(function() {
        var old = btn.innerText;
        btn.innerText = 'Copied!';
        btn.classList.add('copied');
        setTimeout(function() { btn.innerText = old; btn.classList.remove('copied'); }, 1500);
    });
}

function copyAllDocs() {
    var content = document.getElementById('docsContent').innerText;
    navigator.clipboard.writeText(content).then(function() {
        var btn = document.getElementById('copyAllBtn');
        var old = btn.innerText;
        btn.innerText = 'Copied!';
        btn.classList.add('copied');
        setTimeout(function() { btn.innerText = old; btn.classList.remove('copied'); }, 2000);
    });
}
</script>

<?php if ($loggedIn) {
    include __DIR__ . '/includes/user_footer.php';
} else {
    include __DIR__ . '/includes/public_footer.php';
} ?>
