<?php
require_once __DIR__ . '/includes/functions.php';
$baseUrl = getBaseUrl();
session_start();
$user = null;
if (isset($_SESSION['user_id'])) {
    $user = getUserById($_SESSION['user_id']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php 
$pageTitle = "Developer Docs — FamGateway";
include 'includes/header.php'; 
?>
<meta name="description" content="Official FamGateway API Documentation. Integrate our Govt Recognized MSME (UDYAM-BR-28-0050000) automated UPI payment gateway easily.">
<meta name="keywords" content="FamPay API Docs, UPI Payment API, FamGateway Integration, Govt Recognized MSME, Webhooks">

<!-- Open Graph / Social SEO -->
<meta property="og:title" content="Developer Docs — FamGateway">
<meta property="og:description" content="Official FamGateway API Documentation. Integrate our Govt Recognized MSME (UDYAM-BR-28-0050000) automated UPI payment gateway easily.">
<meta property="og:type" content="website">
<meta property="og:image" content="https://famgateway.in/assets/img/og-image.png">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://famgateway.in/assets/img/og-image.png">

<!-- Structured Data for API Docs -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "SoftwareApplication",
      "name": "FamGateway API",
      "applicationCategory": "DeveloperApplication",
      "operatingSystem": "Any",
      "description": "Developer documentation for the FamGateway UPI payment verification API.",
      "url": "https://famgateway.in/docs.php"
    },
    {
      "@type": "BreadcrumbList",
      "itemListElement": [{
        "@type": "ListItem",
        "position": 1,
        "name": "Home",
        "item": "https://famgateway.in/"
      },{
        "@type": "ListItem",
        "position": 2,
        "name": "Documentation",
        "item": "https://famgateway.in/docs.php"
      }]
    }
  ]
}
</script>
<style>
/* Scoped Premium Docs Styles */
.docs-header {
  margin-bottom: 40px;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 20px;
  padding: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.03);
}
.docs-title {
  font-size: 32px;
  font-weight: 800;
  color: #0f172a;
  letter-spacing: -1px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 12px;
}
.docs-badge {
  font-size: 12px;
  font-weight: 600;
  background: #eff6ff;
  color: #2563eb;
  border: 1px solid #bfdbfe;
  padding: 4px 12px;
  border-radius: 999px;
  letter-spacing: 0;
}
.docs-subtitle {
  font-size: 15px;
  color: #64748b;
  line-height: 1.6;
  max-width: 680px;
}
.docs-alert {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-left: 4px solid #2563eb;
  padding: 16px 20px;
  border-radius: 12px;
  margin-top: 20px;
  font-size: 14px;
  color: #334155;
  display: flex;
  align-items: center;
  gap: 12px;
}

/* Copy All Banner */
.copy-all-banner {
  background: linear-gradient(135deg, #1e3a8a, #2563eb);
  color: #ffffff;
  border-radius: 16px;
  padding: 20px 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 36px;
  box-shadow: 0 4px 16px rgba(37, 99, 235, 0.25);
}
.copy-all-text h3 { font-size: 16px; font-weight: 700; margin-bottom: 4px; }
.copy-all-text p { font-size: 13px; color: #bfdbfe; margin: 0; }
.btn-copy-all {
  background: #ffffff;
  color: #1d4ed8;
  border: none;
  padding: 10px 20px;
  border-radius: 10px;
  font-weight: 600;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}
.btn-copy-all:hover { background: #f1f5f9; transform: translateY(-1px); }

/* Section Cards */
.doc-card {
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 20px;
  padding: 32px;
  margin-bottom: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.02);
}
.doc-card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}
.doc-sec-num {
  width: 32px;
  height: 32px;
  background: #eff6ff;
  color: #2563eb;
  border: 1px solid #dbeafe;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 15px;
  font-weight: 700;
}
.doc-sec-title {
  font-size: 20px;
  font-weight: 700;
  color: #0f172a;
  letter-spacing: -0.5px;
}
.doc-sec-desc {
  font-size: 14px;
  color: #64748b;
  line-height: 1.6;
  margin-bottom: 24px;
}

/* Styled Tables */
.doc-table-wrap {
  overflow-x: auto;
  border: 1px solid #e2e8f0;
  border-radius: 14px;
  margin-bottom: 24px;
}
.doc-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13.5px;
  text-align: left;
}
.doc-table th {
  background: #f8fafc;
  padding: 12px 16px;
  font-weight: 600;
  color: #475569;
  border-bottom: 1px solid #e2e8f0;
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}
.doc-table td {
  padding: 14px 16px;
  border-bottom: 1px solid #f1f5f9;
  color: #334155;
  vertical-align: middle;
}
.doc-table tr:last-child td { border-bottom: none; }
.param-name {
  font-family: 'Consolas', 'Fira Code', monospace;
  font-weight: 600;
  color: #0f172a;
  background: #f1f5f9;
  padding: 3px 8px;
  border-radius: 6px;
  font-size: 13px;
}
.badge-type {
  font-family: monospace;
  font-size: 12px;
  color: #64748b;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  padding: 2px 8px;
  border-radius: 6px;
}
.badge-req {
  font-size: 11px;
  font-weight: 700;
  color: #dc2626;
  background: #fee2e2;
  padding: 3px 8px;
  border-radius: 6px;
  text-transform: uppercase;
}
.badge-opt {
  font-size: 11px;
  font-weight: 600;
  color: #64748b;
  background: #f1f5f9;
  padding: 3px 8px;
  border-radius: 6px;
  text-transform: uppercase;
}

/* Premium Code Blocks */
.doc-code-box {
  background: #0f172a;
  border: 1px solid #1e293b;
  border-radius: 14px;
  overflow: hidden;
  margin-bottom: 20px;
  box-shadow: 0 10px 25px rgba(15, 23, 42, 0.15);
}
.doc-code-header {
  background: #1e293b;
  padding: 10px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #334155;
}
.doc-code-label {
  font-size: 12px;
  font-weight: 600;
  color: #94a3b8;
  font-family: 'Consolas', monospace;
  display: flex;
  align-items: center;
  gap: 8px;
}
.doc-copy-btn {
  background: #334155;
  color: #e2e8f0;
  border: 1px solid #475569;
  padding: 5px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 6px;
}
.doc-copy-btn:hover { background: #475569; color: #ffffff; }
.doc-copy-btn.copied { background: #10b981; border-color: #059669; color: #ffffff; }
.doc-code-content {
  padding: 18px 20px;
  margin: 0;
  overflow-x: auto;
  font-family: 'Consolas', 'Fira Code', monospace;
  font-size: 13.5px;
  line-height: 1.7;
  color: #e2e8f0;
  background: #0f172a;
}
.doc-code-content code {
  color: #e2e8f0;
  background: none;
  padding: 0;
  font-family: inherit;
}
.doc-note {
  font-size: 13.5px;
  color: #475569;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  padding: 12px 16px;
  border-radius: 10px;
  margin-top: 12px;
  line-height: 1.6;
}
.doc-note code {
  background: #e2e8f0;
  color: #0f172a;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12.5px;
}
@media (max-width: 768px) {
  .copy-all-banner { flex-direction: column; text-align: center; }
  .btn-copy-all { width: 100%; justify-content: center; }
  .doc-card { padding: 20px; }
}
</style>
</head>
<body>

<?php include 'includes/nav.php'; ?>
    
<main class="main-content">
  <div class="wrap" style="max-width: 960px;">

    <!-- Page Header -->
    <div class="docs-header dash-anim-right">
      <div class="docs-title">
        Developer Documentation
        <span class="docs-badge">FamGateway API v2.0</span>
      </div>
      <div class="docs-subtitle">
        Integrate FamGateway automated payment verification into your apps, Telegram bots, and websites with simple HTTP requests.
      </div>
      <div class="docs-alert">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#2563eb" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
        <span><b>Before you start:</b> Make sure you have connected your FamPay Gmail account in the Dashboard to generate your live <code>api_key</code>.</span>
      </div>
      <div style="margin-top:20px; display:flex; gap:12px;">
         <a href="/famgateway-sdk.zip" class="btn btn-primary" download><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right:6px;vertical-align:middle;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg> Download PHP SDK (.zip)</a>
      </div>
    </div>

    <!-- Copy Full Docs Banner -->
    <div class="copy-all-banner dash-anim-up" style="animation-delay:0.1s;">
      <div class="copy-all-text">
        <h3>Building with ChatGPT, Claude, or Cursor?</h3>
        <p>Copy the entire API documentation formatted in clean Markdown to feed into your AI assistant.</p>
      </div>
      <button class="btn-copy-all" id="copyAllBtn" onclick="copyAllDocs()">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
        Copy AI Prompt / Full Docs
      </button>
    </div>

    <div id="docsContent">

      <!-- Section 0: Base URL & Auth -->
      <div class="doc-card dash-anim-up">
        <div class="doc-card-header">
          <div class="doc-sec-num">0</div>
          <h2 class="doc-sec-title">Base URL & Authentication</h2>
        </div>
        <p class="doc-sec-desc">All API requests are made over HTTPS. Authentication uses a simple <code>api_key</code> query parameter. You can find your API key in the <a href="/api-keys.php">API Keys</a> section of your dashboard.</p>
        
        <div class="doc-code-box">
          <div class="doc-code-header"><span class="doc-code-label">BASE URL</span><button class="doc-copy-btn" onclick="copyBlock(this)">Copy</button></div>
          <pre class="doc-code-content"><?= htmlspecialchars($baseUrl) ?></pre>
        </div>
        <div class="doc-note">
          🔑 <b>Authentication:</b> Include <code>?api_key=YOUR_API_KEY</code> in every request. Never expose your API key in client-side JavaScript or public repositories.<br><br>
          ⏱️ <b>Rate Limit:</b> 20 API requests per IP per 60 seconds. Exceeding this returns HTTP 429. Poll the verify endpoint every 3–5 seconds, not faster.
        </div>
      </div>

      <!-- Section 1: Prerequisites -->
      <div class="doc-card dash-anim-up">
        <div class="doc-card-header">
          <div class="doc-sec-num">1</div>
          <h2 class="doc-sec-title">Prerequisites — Connect Your FamPay Account</h2>
        </div>
        <p class="doc-sec-desc">Before making any API calls, you must connect your FamPay Gmail account in the Dashboard. This allows FamGateway to automatically monitor your inbox for payment confirmation emails and verify transactions in real-time.</p>
        <div class="doc-table-wrap">
          <table class="doc-table">
            <thead><tr><th>Step</th><th>What to Do</th></tr></thead>
            <tbody>
              <tr><td style="font-weight:700;color:#2563eb;">1</td><td>Go to <a href="/dashboard.php">Dashboard → Gmail Settings</a></td></tr>
              <tr><td style="font-weight:700;color:#2563eb;">2</td><td>Enter your FamPay-linked Gmail address</td></tr>
              <tr><td style="font-weight:700;color:#2563eb;">3</td><td>Create a <a href="https://myaccount.google.com/apppasswords" target="_blank">Google App Password</a> (16 characters, no spaces) and enter it</td></tr>
              <tr><td style="font-weight:700;color:#2563eb;">4</td><td>Enter your FamPay UPI ID (e.g., <code>yourname@fam</code>)</td></tr>
              <tr><td style="font-weight:700;color:#2563eb;">5</td><td>Click Save — your <code>api_key</code> will now be active</td></tr>
            </tbody>
          </table>
        </div>
        <div class="doc-note">⚠️ <b>Why Gmail App Password?</b> FamGateway reads the FamPay payment notification emails from your Gmail inbox via IMAP to verify transactions. Your main Gmail password is never stored — only the App Password, which is encrypted in our database and can be revoked anytime.</div>
      </div>

      <!-- Section 2: Create Order -->
      <div class="doc-card dash-anim-up">
        <div class="doc-card-header">
          <div class="doc-sec-num">2</div>
          <h2 class="doc-sec-title">Create Order & Generate UPI QR</h2>
        </div>
        <p class="doc-sec-desc">Creates a unique payment session. The API automatically adds a small fractional offset (e.g., ₹100 → ₹100.04) to the amount to ensure each transaction is uniquely identifiable — preventing double-spend fraud even when multiple customers pay the same base amount simultaneously.</p>
        
        <div class="doc-table-wrap">
          <table class="doc-table">
            <thead><tr><th>Parameter</th><th>Type</th><th>Status</th><th>Description</th></tr></thead>
            <tbody>
              <tr><td><span class="param-name">api_key</span></td><td><span class="badge-type">string</span></td><td><span class="badge-req">Required</span></td><td>Your active API Key.</td></tr>
              <tr><td><span class="param-name">amount</span></td><td><span class="badge-type">float</span></td><td><span class="badge-req">Required</span></td><td>Payment amount (e.g., <code>499.00</code>). Must be a positive number.</td></tr>
              <tr><td><span class="param-name">redirect_url</span></td><td><span class="badge-type">string</span></td><td><span style="color:var(--color-ink-mute);font-size:11px;font-weight:600;padding:2px 6px;border-radius:4px;background:var(--color-hairline);">Optional</span></td><td>Where to redirect the user after a successful payment. <b>Must start with <code>http://</code> or <code>https://</code></b>.</td></tr>
              <tr><td><span class="param-name">webhook_url</span></td><td><span class="badge-type">string</span></td><td><span style="color:var(--color-ink-mute);font-size:11px;font-weight:600;padding:2px 6px;border-radius:4px;background:var(--color-hairline);">Optional</span></td><td>Override the global dashboard Webhook URL for <b>this order only</b>. Useful for routing payments from different projects (websites, bots) to separate endpoints using a single API key. Falls back to your dashboard webhook if omitted. <b>Must start with <code>http://</code> or <code>https://</code></b>.</td></tr>
            </tbody>
          </table>
        </div>

        <div class="doc-code-box">
          <div class="doc-code-header"><span class="doc-code-label">GET /api/qr.php</span><button class="doc-copy-btn" onclick="copyBlock(this)">Copy</button></div>
          <pre class="doc-code-content">GET <?= htmlspecialchars($baseUrl) ?>/api/qr.php?api_key=YOUR_KEY&amount=499</pre>
        </div>

        <div class="doc-code-box">
          <div class="doc-code-header"><span class="doc-code-label">RESPONSE — 200 OK</span><button class="doc-copy-btn" onclick="copyBlock(this)">Copy</button></div>
          <pre class="doc-code-content">{
  "status": "success",
  "data": {
    "order_id":       "fg_A1B2C3D4",
    "qr_url":         "<?= htmlspecialchars($baseUrl) ?>/api/qr-image.php?order_id=fg_A1B2C3D4",
    "amount":         "499",
    "payable_amount": "499.04",
    "upi_intent":     "upi://pay?pa=you@fam&pn=FamPay&tr=fg_A1B2C3D4&am=499.04&cu=INR",
    "created_at_ist": "29-07-2026 14:30:00",
    "expires_at_ist": "29-07-2026 14:35:00"
  }
}</pre>
        </div>
        <div class="doc-note">
          ⚠️ <b>Critical — Use payable_amount:</b> Always display <code>payable_amount</code> (e.g., ₹499.04) to your user on screen, NOT the base <code>amount</code>. The customer must send this exact amount. The gateway matches this unique decimal to verify the payment.<br><br>
          🖼️ <b>Web Developers:</b> Do NOT generate your own QR code. Simply render <code>qr_url</code> as an <code>&lt;img src="..."&gt;</code> tag. The image is auto-generated with your avatar and the correct UPI deep link embedded.<br><br>
          <b>Bot / Native Developers:</b> You can ignore <code>qr_url</code> and grab the raw <code>upi_intent</code> string to render native, clean, avatar-less QR codes directly in Telegram, Discord, or mobile apps.<br><br>
          ⏰ <b>Expiry:</b> Orders expire in 5 minutes. After expiry, <code>verify-order.php</code> returns <code>status: expired</code>.
        </div>
      </div>

      <!-- Section 3: Verify Payment -->
      <div class="doc-card dash-anim-up">
        <div class="doc-card-header">
          <div class="doc-sec-num">3</div>
          <h2 class="doc-sec-title">Verify Payment Status (Poll)</h2>
        </div>
        <p class="doc-sec-desc">After displaying the QR code, poll this endpoint every 3–5 seconds from your server. When the customer pays, FamGateway detects the FamPay Gmail notification in real-time, verifies the exact fractional amount, and returns a <code>success</code> response with the full transaction details.</p>

        <div class="doc-table-wrap">
          <table class="doc-table">
            <thead><tr><th>Parameter</th><th>Type</th><th>Status</th><th>Description</th></tr></thead>
            <tbody>
              <tr><td><span class="param-name">api_key</span></td><td><span class="badge-type">string</span></td><td><span class="badge-req">Required</span></td><td>Your API key.</td></tr>
              <tr><td><span class="param-name">order_id</span></td><td><span class="badge-type">string</span></td><td><span class="badge-req">Required</span></td><td>The <code>order_id</code> returned from Step 2's Create Order call.</td></tr>
            </tbody>
          </table>
        </div>

        <div class="doc-code-box">
          <div class="doc-code-header"><span class="doc-code-label">GET /api/verify-order.php</span><button class="doc-copy-btn" onclick="copyBlock(this)">Copy</button></div>
          <pre class="doc-code-content">GET <?= htmlspecialchars($baseUrl) ?>/api/verify-order.php?api_key=YOUR_KEY&order_id=fg_A1B2C3D4</pre>
        </div>

        <div class="doc-code-box">
          <div class="doc-code-header"><span class="doc-code-label">RESPONSE — SUCCESS (200 OK)</span><button class="doc-copy-btn" onclick="copyBlock(this)">Copy</button></div>
          <pre class="doc-code-content">{
  "status": "success",
  "data": {
    "order_id":         "fg_A1B2C3D4",
    "transaction_id":   "FMP987654321",
    "amount":           499,
    "payable_amount":   499.04,
    "utr":              "420987654321",
    "sender_name":      "Rahul Sharma",
    "payment_time_ist": "29-07-2026 14:31:12"
  }
}</pre>
        </div>

        <div class="doc-note">
          🔄 <b>Webhooks:</b> You will receive a JSON webhook notification at your configured URL as soon as the payment is confirmed.
          <br><br>
          <b>Bots (No Webhooks Needed):</b> If you are building a bot on a local server without a public URL, you don't need webhooks! Simply poll this verify endpoint every 3 seconds to check the order status in real-time.
          <br><br>
          🔒 <b>Anti-Replay Protection:</b> The gateway has built-in double-spend detection. The same FamPay transaction email cannot confirm two different orders. Each <code>utr</code> can only be used once.
        </div>
      </div>

      <!-- Section 4: Code Examples -->
      <div class="doc-card dash-anim-up">
        <div class="doc-card-header">
          <div class="doc-sec-num">4</div>
          <h2 class="doc-sec-title">Full Integration Examples</h2>
        </div>
        <p class="doc-sec-desc">Complete, copy-paste ready integration examples in PHP, Python, and Node.js showing the full payment flow.</p>

        <div class="doc-code-box">
          <div class="doc-code-header"><span class="doc-code-label">PHP — Secure Checkout Flow</span><button class="doc-copy-btn" onclick="copyBlock(this)">Copy</button></div>
          <pre class="doc-code-content">&lt;?php
$API_KEY = 'YOUR_API_KEY';
$REDIRECT = urlencode('https://yourwebsite.com/success.php');
$BASE_URL = '<?= htmlspecialchars($baseUrl) ?>';

// Step 1: Create order
$res = file_get_contents("$BASE_URL/api/qr.php?api_key=$API_KEY&amount=499&redirect_url=$REDIRECT");
$data = json_decode($res, true)['data'];

// Step 2: Redirect user to Secure Hosted Checkout
header("Location: " . $data['checkout_url']);
exit;

/* 
 * WHAT HAPPENS NEXT?
 * 1. User sees the QR code on our secure page.
 * 2. They pay and our system verifies it automatically.
 * 3. They are redirected back to your redirect_url.
 * 4. We will send a Webhook to your server confirming the payment!
 */
</pre>
        </div>

        <div class="doc-code-box">
          <div class="doc-code-header"><span class="doc-code-label">Python — Secure Checkout Flow</span><button class="doc-copy-btn" onclick="copyBlock(this)">Copy</button></div>
          <pre class="doc-code-content">import requests
from flask import redirect

API_KEY  = 'YOUR_API_KEY'
BASE_URL = '<?= htmlspecialchars($baseUrl) ?>'
REDIRECT = 'https://yourwebsite.com/success'

# Step 1: Create order
res = requests.get(f'{BASE_URL}/api/qr.php', params={
    'api_key': API_KEY, 'amount': 499, 'redirect_url': REDIRECT
}).json()

checkout_url = res['data']['checkout_url']

# Step 2: Redirect user to Hosted Checkout
# (Example using Flask redirect)
return redirect(checkout_url)

# Wait for our Webhook to hit your server to mark the order as paid!
</pre>
        </div>

        <div class="doc-code-box">
          <div class="doc-code-header"><span class="doc-code-label">Node.js — Secure Checkout Flow</span><button class="doc-copy-btn" onclick="copyBlock(this)">Copy</button></div>
          <pre class="doc-code-content">const API_KEY  = 'YOUR_API_KEY';
const BASE_URL = '<?= htmlspecialchars($baseUrl) ?>';
const REDIRECT = 'https://yourwebsite.com/success';
const amount   = 499;

async function createCheckout() {
  // Step 1: Create order
  const res = await fetch(
    `${BASE_URL}/api/qr.php?api_key=${API_KEY}&amount=${amount}&redirect_url=${encodeURIComponent(REDIRECT)}`
  );
  const { data } = await res.json();
  
  // Step 2: Redirect user
  // (In Express.js, this would be: res.redirect(data.checkout_url))
  window.location.href = data.checkout_url;
}

// We will handle the QR code and payment verification.
// You just need to listen for the Webhook to fulfill the order!
</pre>
        </div>
      </div>



      <!-- Section 5: Payment Links API -->
      <div class="doc-card dash-anim-up">
        <div class="doc-card-header">
          <div class="doc-sec-num">5</div>
          <h2 class="doc-sec-title">Payment Links (Shareable URLs)</h2>
        </div>
        <p class="doc-sec-desc">Payment Links are reusable, shareable URLs that let anyone pay you without needing any API integration. Create them from your dashboard or via API. You can verify if a payment link has been paid using the same <code>verify-order.php</code> endpoint.</p>

        <div class="doc-table-wrap">
          <table class="doc-table">
            <thead><tr><th>Parameter</th><th>Type</th><th>Status</th><th>Description</th></tr></thead>
            <tbody>
              <tr><td><span class="param-name">order_id</span></td><td><span class="badge-type">string</span></td><td><span class="badge-req">Required</span></td><td>For payment links, prefix the slug with <code>LINK_</code> — e.g., <code>LINK_yourname-abc123</code></td></tr>
            </tbody>
          </table>
        </div>
        
        <div class="doc-code-box">
          <div class="doc-code-header"><span class="doc-code-label">CHECK IF PAYMENT LINK IS PAID</span><button class="doc-copy-btn" onclick="copyBlock(this)">Copy</button></div>
          <pre class="doc-code-content">GET <?= htmlspecialchars($baseUrl) ?>/api/verify-order.php?api_key=YOUR_KEY&order_id=LINK_yourname-abc123</pre>
        </div>

        <div class="doc-code-box">
          <div class="doc-code-header"><span class="doc-code-label">PAYMENT LINK URL FORMAT</span><button class="doc-copy-btn" onclick="copyBlock(this)">Copy</button></div>
          <pre class="doc-code-content"><?= htmlspecialchars($baseUrl) ?>/pay/your-custom-slug</pre>
        </div>
        <div class="doc-note">📋 <b>Create links from Dashboard:</b> Go to <a href="/payment-links.php">Payment Links</a> in your merchant dashboard to create and manage reusable payment links with custom slugs, amounts, and expiry times.</div>
      </div>

      <!-- Section 7: Webhooks -->
      <div class="doc-card dash-anim-up">
        <div class="doc-card-header">
          <div class="doc-sec-num">7</div>
          <h2 class="doc-sec-title">Webhook Signature Verification</h2>
        </div>
        <p class="doc-sec-desc">When a payment succeeds, FamGateway sends a signed HTTP POST to your webhook endpoint. You must verify the signature to ensure the request genuinely came from us.</p>
        
        <div class="doc-table-wrap">
          <table class="doc-table">
            <thead><tr><th>Header</th><th>Description</th></tr></thead>
            <tbody>
              <tr><td><span class="param-name">HTTP_X_FAMGATEWAY_SIGNATURE</span></td><td>HMAC SHA256 signature of the raw JSON body, signed using your <code>api_key</code>.</td></tr>
            </tbody>
          </table>
        </div>

        <div class="doc-code-box">
          <div class="doc-code-header"><span class="doc-code-label">PHP WEBHOOK VERIFICATION EXAMPLE</span><button class="doc-copy-btn" onclick="copyBlock(this)">Copy</button></div>
          <pre class="doc-code-content">&lt;?php
$API_KEY = 'YOUR_API_KEY'; // Use your API key as the secret
$rawBody  = file_get_contents('php://input');
$sigHeader = $_SERVER['HTTP_X_FAMGATEWAY_SIGNATURE'] ?? '';

// Verify using HMAC SHA256
$expected = hash_hmac('sha256', $rawBody, $API_KEY);

if (!hash_equals($expected, $sigHeader)) {
    http_response_code(401);
    die('Invalid signature — request ignored.');
}

// Signature verified! Process the event.
$event = json_decode($rawBody, true);
if ($event['event'] === 'payment.success') {
    // Fulfill the order in your DB
    // $event['order_id'], $event['utr'], $event['amount']
    echo 'OK';
}</pre>
        </div>
      </div>

      <!-- Section 8: Error Codes -->
      <div class="doc-card dash-anim-up">
        <div class="doc-card-header">
          <div class="doc-sec-num">8</div>
          <h2 class="doc-sec-title">HTTP Status & Error Codes</h2>
        </div>
        <p class="doc-sec-desc">All error responses follow a consistent JSON format: <code>{"status": "error_type", "message": "Human-readable description"}</code></p>

        <div class="doc-table-wrap" style="margin-bottom:0;">
          <table class="doc-table">
            <thead><tr><th>HTTP Code</th><th>Status Field</th><th>When it happens</th><th>Fix</th></tr></thead>
            <tbody>
              <tr>
                <td><span class="param-name" style="color:#dc2626;background:#fee2e2;">401</span></td>
                <td><code>unauthorized</code></td>
                <td>Missing or invalid <code>api_key</code></td>
                <td>Check your API key in <a href="/api-keys.php">API Keys</a></td>
              </tr>
              <tr>
                <td><span class="param-name" style="color:#dc2626;background:#fee2e2;">403</span></td>
                <td><code>suspended</code></td>
                <td>Account banned by admin</td>
                <td>Contact support</td>
              </tr>
              <tr>
                <td><span class="param-name" style="color:#64748b;background:#f1f5f9;">404</span></td>
                <td><code>not_found</code></td>
                <td><code>order_id</code> does not exist or belongs to another user</td>
                <td>Verify the order_id is correct</td>
              </tr>
              <tr>
                <td><span class="param-name" style="color:#ea580c;background:#ffedd5;">408</span></td>
                <td><code>expired</code></td>
                <td>5-minute payment window exceeded</td>
                <td>Create a new order and show fresh QR</td>
              </tr>
              <tr>
                <td><span class="param-name" style="color:#ca8a04;background:#fef9c3;">429</span></td>
                <td><code>error</code></td>
                <td>Rate limit exceeded (20 req/min per IP)</td>
                <td>Slow down polling to every 5 seconds minimum</td>
              </tr>
              <tr>
                <td><span class="param-name" style="color:#dc2626;background:#fee2e2;">500</span></td>
                <td><code>error</code></td>
                <td>Gmail IMAP not connected or server error</td>
                <td>Check Gmail connection in <a href="/dashboard.php">Dashboard</a></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

    </div><!-- /#docsContent -->

  </div>
</main>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    if (window.lucide) { lucide.createIcons(); }
});

function copyBlock(btn) {
    const pre = btn.closest('.doc-code-box').querySelector('pre');
    navigator.clipboard.writeText(pre.innerText).then(() => {
        const oldText = btn.innerText;
        btn.innerText = 'Copied!';
        btn.classList.add('copied');
        setTimeout(() => {
            btn.innerText = oldText;
            btn.classList.remove('copied');
        }, 1500);
    });
}

function copyAllDocs() {
    let content = "I want to integrate FamGateway into my website. Please write the backend code (in your language of choice) for the following flow:\n\n";
    content += "1. User clicks 'Pay Now' on your site.\n";
    content += "2. Your server calls: <?= htmlspecialchars($baseUrl) ?>/api/qr.php?api_key=MY_API_KEY&amount=100&redirect_url=https://mywebsite.com/success\n";
    content += "   (The API responds with JSON containing data.order_id)\n";
    content += "3. You redirect user to: <?= htmlspecialchars($baseUrl) ?>/checkout.php?order_id=xyz\n";
    content += "4. User completes payment.\n";
    content += "5. User is redirected to https://mywebsite.com/success?order_id=xyz&status=success\n";
    content += "6. Also, create a Webhook handler route that listens for a POST request.\n";
    content += "   - It needs to read the X-FamGateway-Signature header.\n";
    content += "   - It needs to verify the HMAC SHA-256 signature of the raw POST body using my API key as the secret.\n";
    content += "   - If the signature matches, parse the JSON body and check if event == 'payment.success'.\n";
    content += "   - If payment is successful, mark the order (using order_id from the JSON) as paid in my database.\n\n";
    content += "Please provide complete, secure code to handle this integration. Here is the full API documentation for your reference:\n\n";
    content += "========================================\n\n";
    content += document.getElementById('docsContent').innerText;
    navigator.clipboard.writeText(content).then(() => {
        const btn = document.getElementById('copyAllBtn');
        const oldHTML = btn.innerHTML;
        btn.innerHTML = '✓ Copied Full Markdown Docs!';
        btn.style.background = '#10b981';
        btn.style.color = '#ffffff';
        setTimeout(() => {
            btn.innerHTML = oldHTML;
            btn.style.background = '';
            btn.style.color = '';
        }, 2500);
    });
}
</script>

</body>
</html>
