<?php
// PayIndia - Developer API Documentation
require_once __DIR__ . '/includes/functions.php';
initSession();

$loggedIn = isLoggedIn();
$apiKey = 'pi_live_xxxxxxxxxxxxxxxxxxxxxxxx';
$apiSecret = 'sk_live_xxxxxxxxxxxxxxxxxxxxxxxx';
$sandboxKey = 'pi_test_xxxxxxxxxxxxxxxxxxxxxxxx';
$userName = 'Developer';

if ($loggedIn) {
    $currentUser = getCurrentUser();
    $userId = $currentUser['id'];
    $userName = $currentUser['full_name'];
    $keys = Database::fetchOne("SELECT * FROM api_keys WHERE user_id = ? AND status = 'active'", [$userId]);
    if ($keys) {
        $apiKey = $keys['api_key'];
        $apiSecret = $keys['api_secret'];
        $sandboxKey = $keys['sandbox_key'];
    }
}

$sampleOrderId = 'ORD_' . date('Ymd') . '_' . rand(1000, 9999);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Developer API Documentation - PayIndia</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=Fira+Code:wght@400;500&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="icon" type="image/png" href="<?php echo APP_DOMAIN; ?>/assets/img/favicon.png">
    
    <style>
        :root {
            --pi-primary: #C6E547;
            --pi-primary-hover: #b8d63e;
            --pi-primary-light: rgba(198, 229, 71, 0.12);
            --pi-dark: #0B3D2E;
            --pi-dark-hover: #0d4a37;
            --pi-dark-light: #134d3a;
            --pi-bg: #F8FAF7;
            --pi-white: #FFFFFF;
            --pi-border: #E8EDE5;
            --pi-text: #1a2e1a;
            --pi-text-secondary: #5f7a5f;
            --pi-text-muted: #8fa08f;
            --pi-code-bg: #051e16;
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--pi-bg);
            color: var(--pi-text);
            scroll-behavior: smooth;
        }

        /* Navbar Style */
        .navbar-custom {
            background-color: var(--pi-dark);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            padding: 15px 0;
            position: sticky;
            top: 0;
            z-index: 1000;
        }
        .navbar-custom .navbar-brand {
            font-weight: 800;
            font-size: 22px;
            color: var(--pi-white);
            display: flex;
            align-items: center;
            gap: 10px;
            text-decoration: none;
        }
        .navbar-custom .navbar-brand span {
            color: var(--pi-primary);
        }

        /* Layout Structure */
        .docs-container {
            display: flex;
            min-height: calc(100vh - 73px);
        }

        /* Sidebar Styling */
        .docs-sidebar {
            width: 280px;
            background-color: var(--pi-white);
            border-right: 1px solid var(--pi-border);
            padding: 30px 20px;
            position: sticky;
            top: 73px;
            height: calc(100vh - 73px);
            overflow-y: auto;
            flex-shrink: 0;
        }

        .sidebar-title {
            font-size: 11px;
            font-weight: 700;
            color: var(--pi-text-muted);
            text-transform: uppercase;
            letter-spacing: 1.5px;
            margin-bottom: 12px;
            margin-top: 24px;
        }
        .sidebar-title:first-of-type {
            margin-top: 0;
        }

        .sidebar-nav {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .sidebar-nav-item {
            margin-bottom: 4px;
        }
        .sidebar-nav-link {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 8px 12px;
            color: var(--pi-text-secondary);
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            border-radius: 8px;
            transition: all 0.2s ease;
        }
        .sidebar-nav-link:hover {
            background-color: var(--pi-bg);
            color: var(--pi-dark);
        }
        .sidebar-nav-link.active {
            background-color: var(--pi-primary-light);
            color: var(--pi-dark);
            font-weight: 600;
        }

        /* Content Area Styling */
        .docs-content {
            flex: 1;
            padding: 50px 60px;
            max-width: 900px;
            overflow-y: auto;
        }

        /* Typography & Custom classes */
        h1, h2, h3, h4 {
            font-weight: 800;
            color: var(--pi-dark);
            letter-spacing: -0.5px;
        }
        h1 { font-size: 36px; margin-bottom: 20px; }
        h2 { font-size: 24px; margin-top: 40px; margin-bottom: 15px; border-bottom: 2px solid var(--pi-border); padding-bottom: 8px; }
        h3 { font-size: 18px; margin-top: 30px; margin-bottom: 12px; }

        p {
            color: var(--pi-text-secondary);
            font-size: 15px;
            line-height: 1.6;
        }

        .api-badge {
            font-size: 11px;
            font-weight: 700;
            padding: 4px 10px;
            border-radius: 6px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .api-badge.post { background-color: #ECFDF5; color: #10B981; border: 1px solid #A7F3D0; }
        .api-badge.get { background-color: #EFF6FF; color: #3B82F6; border: 1px solid #BFDBFE; }

        /* API Param Table styling */
        .param-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            font-size: 14px;
        }
        .param-table th {
            background-color: var(--pi-bg);
            color: var(--pi-dark);
            font-weight: 700;
            padding: 10px 14px;
            text-align: left;
            border-bottom: 2px solid var(--pi-border);
        }
        .param-table td {
            padding: 12px 14px;
            border-bottom: 1px solid var(--pi-border);
            vertical-align: top;
        }
        .param-name {
            font-family: 'Fira Code', monospace;
            font-weight: 600;
            color: #0E7490;
        }
        .param-type {
            font-size: 12px;
            font-weight: 500;
            color: var(--pi-text-muted);
            background: #F1F5F9;
            padding: 2px 6px;
            border-radius: 4px;
        }
        .param-required {
            font-size: 10px;
            font-weight: 700;
            color: #EF4444;
            text-transform: uppercase;
        }
        .param-optional {
            font-size: 10px;
            font-weight: 700;
            color: var(--pi-text-muted);
            text-transform: uppercase;
        }

        /* Code Block Container styling */
        .code-container {
            margin: 20px 0;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid rgba(11, 61, 46, 0.15);
        }
        .code-header {
            background-color: #031610;
            padding: 12px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }
        .code-tabs {
            display: flex;
            gap: 10px;
        }
        .code-tab {
            background: none;
            border: none;
            color: rgba(255, 255, 255, 0.4);
            font-size: 12px;
            font-weight: 600;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
        }
        .code-tab.active {
            color: var(--pi-primary);
            background-color: rgba(198, 229, 71, 0.1);
        }
        .btn-copy {
            background: none;
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: rgba(255, 255, 255, 0.6);
            font-size: 11px;
            padding: 4px 10px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .btn-copy:hover {
            color: var(--pi-primary);
            border-color: var(--pi-primary);
        }
        .code-body {
            background-color: var(--pi-code-bg);
            padding: 20px;
            margin: 0;
            overflow-x: auto;
        }
        .code-body pre {
            margin: 0;
        }
        .code-body code {
            font-family: 'Fira Code', monospace;
            font-size: 13px;
            color: #E2E8F0;
            line-height: 1.5;
        }

        /* Info Alert Boxes */
        .info-box {
            background-color: var(--pi-primary-light);
            border-left: 4px solid var(--pi-primary);
            padding: 16px 20px;
            border-radius: 0 12px 12px 0;
            margin: 25px 0;
        }
        .info-box h5 {
            font-size: 14px;
            font-weight: 700;
            color: var(--pi-dark);
            margin-bottom: 6px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .info-box p {
            margin: 0;
            font-size: 13.5px;
            color: var(--pi-dark-light);
        }

        .warning-box {
            background-color: rgba(245, 158, 11, 0.08);
            border-left: 4px solid var(--pi-warning, #F59E0B);
            padding: 16px 20px;
            border-radius: 0 12px 12px 0;
            margin: 25px 0;
        }
        .warning-box h5 {
            font-size: 14px;
            font-weight: 700;
            color: #78350F;
            margin-bottom: 6px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .warning-box p {
            margin: 0;
            font-size: 13.5px;
            color: #92400E;
        }

        @media (max-width: 991.98px) {
            .docs-sidebar { display: none; }
            .docs-content { padding: 40px 20px; }
        }
    </style>
</head>
<body>

    <!-- Header Navigation -->
    <nav class="navbar navbar-custom navbar-dark">
        <div class="container-fluid px-4">
            <a class="navbar-brand" href="<?php echo APP_DOMAIN; ?>/">
                <svg width="28" height="28" viewBox="0 0 32 32" fill="none" style="display:inline; vertical-align: middle;">
                    <rect width="32" height="32" rx="8" fill="#C6E547"/>
                    <path d="M8 16L14 10L20 16L14 22L8 16Z" fill="#0B3D2E"/>
                    <path d="M14 16L20 10L26 16L20 22L14 16Z" fill="#0B3D2E" opacity="0.6"/>
                </svg>
                Pay<span>India</span> <span style="font-size: 13px; font-weight: 500; background:rgba(255,255,255,0.1); padding: 2px 8px; border-radius: 12px; margin-left: 10px;">Developer Docs</span>
            </a>
            <div class="d-flex align-items-center gap-3">
                <a href="<?php echo APP_DOMAIN; ?>/demo" class="btn btn-outline-light btn-sm px-3 rounded-pill fw-semibold"><i data-lucide="play-circle" class="me-1" style="width:14px; height:14px; display:inline; vertical-align:-2px;"></i> Try Demo Checkout</a>
                <?php if ($loggedIn): ?>
                    <a href="<?php echo APP_DOMAIN; ?>/merchant/dashboard.php" class="btn btn-success btn-sm px-3 rounded-pill fw-semibold" style="background-color: var(--pi-primary); border:none; color: var(--pi-dark);"><i data-lucide="layout-dashboard" class="me-1" style="width:14px; height:14px; display:inline; vertical-align:-2px;"></i> Dashboard</a>
                <?php else: ?>
                    <a href="<?php echo APP_DOMAIN; ?>/auth/login.php" class="btn btn-outline-light btn-sm px-3 rounded-pill fw-semibold">Login</a>
                <?php endif; ?>
            </div>
        </div>
    </nav>

    <div class="docs-container">
        <!-- Sidebar Navigation -->
        <aside class="docs-sidebar">
            <div class="sidebar-title">Getting Started</div>
            <ul class="sidebar-nav">
                <li class="sidebar-nav-item"><a href="#introduction" class="sidebar-nav-link active" onclick="activateLink(this)"><i data-lucide="book-open" style="width:16px;"></i> Introduction</a></li>
                <li class="sidebar-nav-item"><a href="#authentication" class="sidebar-nav-link" onclick="activateLink(this)"><i data-lucide="key" style="width:16px;"></i> Authentication</a></li>
                <li class="sidebar-nav-item"><a href="#environments" class="sidebar-nav-link" onclick="activateLink(this)"><i data-lucide="terminal" style="width:16px;"></i> Environments</a></li>
            </ul>

            <div class="sidebar-title">REST APIs</div>
            <ul class="sidebar-nav">
                <li class="sidebar-nav-item"><a href="#api-create-order" class="sidebar-nav-link" onclick="activateLink(this)"><i data-lucide="plus-circle" style="width:16px;"></i> Create Order</a></li>
                <li class="sidebar-nav-item"><a href="#api-check-status" class="sidebar-nav-link" onclick="activateLink(this)"><i data-lucide="search" style="width:16px;"></i> Check Status</a></li>
            </ul>

            <div class="sidebar-title">Integrations</div>
            <ul class="sidebar-nav">
                <li class="sidebar-nav-item"><a href="#webhooks" class="sidebar-nav-link" onclick="activateLink(this)"><i data-lucide="webhook" style="width:16px;"></i> Webhooks</a></li>
                <li class="sidebar-nav-item"><a href="#callback" class="sidebar-nav-link" onclick="activateLink(this)"><i data-lucide="arrow-right-left" style="width:16px;"></i> Callbacks & Redirect</a></li>
                <li class="sidebar-nav-item"><a href="#full-flow-example" class="sidebar-nav-link" onclick="activateLink(this)"><i data-lucide="blocks" style="width:16px;"></i> PHP Integration Flow</a></li>
            </ul>

            <div class="sidebar-title">Sandbox Testing</div>
            <ul class="sidebar-nav">
                <li class="sidebar-nav-item"><a href="<?php echo APP_DOMAIN; ?>/demo" class="sidebar-nav-link" target="_blank"><i data-lucide="play-circle" style="width:16px;"></i> Checkout Simulator <i data-lucide="external-link" style="width:12px; margin-left: 2px;"></i></a></li>
            </ul>
        </aside>

        <!-- Main Content -->
        <main class="docs-content">
            
            <!-- Introduction -->
            <section id="introduction">
                <h1>PayIndia API Reference</h1>
                <p class="lead">Welcome to the PayIndia REST API documentation. PayIndia provides a lightweight, robust UPI-focused payment gateway engine that detects actual QR payments via Paytm Business API endpoints.</p>
                <p>Using our APIs, you can easily create checkout orders, generate dynamic payment landing links, redirect customers, verify transactions instantly, and receive real-time webhook status updates once they finish paying.</p>
                
                <div class="info-box">
                    <h5><i data-lucide="info" style="width:16px; height:16px;"></i> Developer Mode Detected</h5>
                    <?php if ($loggedIn): ?>
                        <p>Hi <strong><?php echo htmlspecialchars($userName); ?></strong>! You are currently logged in. We have automatically customized the code snippets below with your real active API credentials for easy copy-pasting.</p>
                    <?php else: ?>
                        <p>We are currently showing fallback demo keys in code snippets. <a href="<?php echo APP_DOMAIN; ?>/auth/login.php" class="fw-semibold text-dark">Log in to your account</a> to automatically populate these docs with your actual merchant credentials.</p>
                    <?php endif; ?>
                </div>
            </section>

            <!-- Authentication -->
            <section id="authentication">
                <h2>Authentication</h2>
                <p>All REST API endpoints require secure authentication headers. Your credentials consist of a live public Key and a secret Key which you must generate inside your <a href="<?php echo APP_DOMAIN; ?>/merchant/api-keys.php" target="_blank" class="fw-semibold">API Settings</a> page.</p>
                <p>Include the keys as custom HTTP headers with every request:</p>
                
                <table class="param-table">
                    <thead>
                        <tr>
                            <th>Header Name</th>
                            <th>Description</th>
                            <th>Example</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td class="param-name">X-API-Key</td>
                            <td>Your merchant environment API Key.</td>
                            <td><code><?php echo $apiKey; ?></code></td>
                        </tr>
                        <tr>
                            <td class="param-name">X-API-Secret</td>
                            <td>Your merchant environment API Secret. Keep this safe!</td>
                            <td><code><?php echo $apiSecret; ?></code></td>
                        </tr>
                        <tr>
                            <td class="param-name">Content-Type</td>
                            <td>Payload type indicator (must be JSON).</td>
                            <td><code>application/json</code></td>
                        </tr>
                    </tbody>
                </table>

                <div class="warning-box">
                    <h5><i data-lucide="alert-triangle" style="width:16px; height:16px;"></i> Keep Secrets Confidential</h5>
                    <p>Never share your API Secret or commit it to client-side code repositories. Always trigger requests to our API endpoint servers from your backend server application.</p>
                </div>
            </section>

            <!-- Environments -->
            <section id="environments">
                <h2>Environments</h2>
                <p>PayIndia supports two environments. You can toggle your environment mode within your Merchant Developer Console.</p>
                
                <ol>
                    <li><strong>Sandbox Mode (Test)</strong>: Used during integration testing. Checkout links will load a simulated payment page where you can trigger a successful payment callback instantly without transferring money. Use headers containing your sandbox credentials.</li>
                    <li><strong>Production Mode (Live)</strong>: Process actual transaction amounts. Integrates directly with your connected Paytm Merchant accounts to generate live UPI codes and poll transaction records.</li>
                </ol>

                <p>The base endpoint URL remains the same for both test and live environments:</p>
                <div class="code-container">
                    <div class="code-header">
                        <span class="text-white-50 font-monospace fs-7">Base Endpoint URL</span>
                        <button class="btn-copy" onclick="copyText('<?php echo APP_DOMAIN; ?>/api')"><i data-lucide="copy" style="width:12px;"></i> Copy</button>
                    </div>
                    <pre class="code-body"><code><?php echo APP_DOMAIN; ?>/api</code></pre>
                </div>
            </section>

            <!-- Create Order API -->
            <section id="api-create-order">
                <h2>Create Order</h2>
                <div class="d-flex align-items-center gap-2 mb-3">
                    <span class="api-badge post">POST</span>
                    <code class="font-monospace text-dark fw-bold"><?php echo APP_DOMAIN; ?>/api/create-order</code>
                </div>
                <p>Creates a transaction order in our database and returns a unique, secure `payment_url`. Redirect your customer to this URL to trigger the checkout flow.</p>
                
                <h3>Request Body Parameters</h3>
                <table class="param-table">
                    <thead>
                        <tr>
                            <th>Parameter</th>
                            <th>Type</th>
                            <th>Required</th>
                            <th>Description</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td class="param-name">amount</td>
                            <td><span class="param-type">float</span></td>
                            <td><span class="param-required">Yes</span></td>
                            <td>The order amount in INR. Must be greater than 0.00.</td>
                        </tr>
                        <tr>
                            <td class="param-name">order_id</td>
                            <td><span class="param-type">string</span></td>
                            <td><span class="param-required">Yes</span></td>
                            <td>Your internal unique transaction identifier (e.g. <code>ORD98765</code>).</td>
                        </tr>
                        <tr>
                            <td class="param-name">customer_name</td>
                            <td><span class="param-type">string</span></td>
                            <td><span class="param-required">Yes</span></td>
                            <td>The billing customer's full name.</td>
                        </tr>
                        <tr>
                            <td class="param-name">callback_url</td>
                            <td><span class="param-type">string</span></td>
                            <td><span class="param-optional">No</span></td>
                            <td>Redirect destination URL once payment completes.</td>
                        </tr>
                        <tr>
                            <td class="param-name">description</td>
                            <td><span class="param-type">string</span></td>
                            <td><span class="param-optional">No</span></td>
                            <td>Payment remarks shown to the customer (e.g. <code>Pro plan renewal</code>).</td>
                        </tr>
                        <tr>
                            <td class="param-name">customer_mobile</td>
                            <td><span class="param-type">string</span></td>
                            <td><span class="param-optional">No</span></td>
                            <td>Customer's phone number.</td>
                        </tr>
                        <tr>
                            <td class="param-name">is_reusable</td>
                            <td><span class="param-type">boolean</span></td>
                            <td><span class="param-optional">No</span></td>
                            <td>Set to <code>true</code> if you want this link to accept multiple customer payments (default: <code>false</code>).</td>
                        </tr>
                    </tbody>
                </table>

                <!-- Code Switcher for Create Order -->
                <div class="code-container">
                    <div class="code-header">
                        <div class="code-tabs" id="createOrderTabs">
                            <button class="code-tab active" onclick="switchTab('createOrder', 'curl', this)">cURL</button>
                            <button class="code-tab" onclick="switchTab('createOrder', 'php', this)">PHP</button>
                            <button class="code-tab" onclick="switchTab('createOrder', 'node', this)">Node.js</button>
                            <button class="code-tab" onclick="switchTab('createOrder', 'python', this)">Python</button>
                        </div>
                        <button class="btn-copy" id="createOrderCopyBtn"><i data-lucide="copy" style="width:12px;"></i> Copy</button>
                    </div>
                    
                    <!-- cURL -->
                    <div class="code-body-wrapper" id="createOrder-curl">
                        <pre class="code-body"><code class="language-bash">curl -X POST <?php echo APP_DOMAIN; ?>/api/create-order \
  -H "X-API-Key: <?php echo $apiKey; ?>" \
  -H "X-API-Secret: <?php echo $apiSecret; ?>" \
  -H "Content-Type: application/json" \
  -d '{
    "amount": "100.00",
    "order_id": "<?php echo $sampleOrderId; ?>",
    "customer_name": "Raushan Kumar",
    "description": "Order simulation purchase",
    "callback_url": "https://yourwebsite.com/callback.php"
  }'</code></pre>
                    </div>

                    <!-- PHP -->
                    <div class="code-body-wrapper d-none" id="createOrder-php">
                        <pre class="code-body"><code class="language-php">&lt;?php
$payload = [
    'amount' => '100.00',
    'order_id' => '<?php echo $sampleOrderId; ?>',
    'customer_name' => 'Raushan Kumar',
    'description' => 'Order simulation purchase',
    'callback_url' => 'https://yourwebsite.com/callback.php'
];

$ch = curl_init('<?php echo APP_DOMAIN; ?>/api/create-order');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'X-API-Key: <?php echo $apiKey; ?>',
        'X-API-Secret: <?php echo $apiSecret; ?>'
    ]
]);

$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);

if (isset($data['status']) && $data['status'] === 'success') {
    $checkoutUrl = $data['data']['payment_url'];
    // Redirect customer to $checkoutUrl
    header("Location: " . $checkoutUrl);
    exit;
} else {
    echo "Error creating order: " . ($data['error'] ?? 'Unknown error');
}
?&gt;</code></pre>
                    </div>

                    <!-- Node.js -->
                    <div class="code-body-wrapper d-none" id="createOrder-node">
                        <pre class="code-body"><code class="language-javascript">const fetch = require('node-fetch');

const payload = {
  amount: '100.00',
  order_id: '<?php echo $sampleOrderId; ?>',
  customer_name: 'Raushan Kumar',
  description: 'Order simulation purchase',
  callback_url: 'https://yourwebsite.com/callback.php'
};

fetch('<?php echo APP_DOMAIN; ?>/api/create-order', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': '<?php echo $apiKey; ?>',
    'X-API-Secret': '<?php echo $apiSecret; ?>'
  },
  body: JSON.stringify(payload)
})
.then(res => res.json())
.then(json => {
  if (json.status === 'success') {
    console.log('Redirect URL:', json.data.payment_url);
  } else {
    console.error('API Error:', json.error);
  }
})
.catch(err => console.error(err));</code></pre>
                    </div>

                    <!-- Python -->
                    <div class="code-body-wrapper d-none" id="createOrder-python">
                        <pre class="code-body"><code class="language-python">import requests

payload = {
    "amount": "100.00",
    "order_id": "<?php echo $sampleOrderId; ?>",
    "customer_name": "Raushan Kumar",
    "description": "Order simulation purchase",
    "callback_url": "https://yourwebsite.com/callback.php"
}

headers = {
    "Content-Type": "application/json",
    "X-API-Key": "<?php echo $apiKey; ?>",
    "X-API-Secret": "<?php echo $apiSecret; ?>"
}

response = requests.post("<?php echo APP_DOMAIN; ?>/api/create-order", json=payload, headers=headers)
data = response.json()

if data.get("status") == "success":
    print("Redirect user to:", data["data"]["payment_url"])
else:
    print("Error:", data.get("error"))</code></pre>
                    </div>
                </div>

                <h3>Success Response Schema (201 Created)</h3>
                <div class="code-container">
                    <div class="code-header">
                        <span class="text-white-50 font-monospace fs-7">201 Created Response</span>
                        <button class="btn-copy" onclick="copyText(this.nextElementSibling.textContent)"><i data-lucide="copy" style="width:12px;"></i> Copy</button>
                    </div>
                    <pre class="code-body"><code>{
  "status": "success",
  "message": "Order created successfully",
  "data": {
    "payment_url": "<?php echo APP_DOMAIN; ?>/pay/LRd7jTFOV2sFyhMyOBzbJLL1SQzMxe5V",
    "order_id": "<?php echo $sampleOrderId; ?>",
    "token": "LRd7jTFOV2sFyhMyOBzbJLL1SQzMxe5V",
    "amount": 100.00,
    "currency": "INR",
    "customer_name": "Raushan Kumar",
    "expires_at": "2026-06-06 11:15:30",
    "created_at": "2026-06-05 11:15:30"
  }
}</code></pre>
                </div>
            </section>

            <!-- Check Status API -->
            <section id="api-check-status">
                <h2>Check Status</h2>
                <div class="d-flex align-items-center gap-2 mb-3">
                    <span class="api-badge post">POST</span>
                    <code class="font-monospace text-dark fw-bold"><?php echo APP_DOMAIN; ?>/api/check-status</code>
                </div>
                <p>Retrieves the details and verification status of a transaction using your unique `order_id` reference.</p>
                
                <h3>Request Body Parameters</h3>
                <table class="param-table">
                    <thead>
                        <tr>
                            <th>Parameter</th>
                            <th>Type</th>
                            <th>Required</th>
                            <th>Description</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td class="param-name">order_id</td>
                            <td><span class="param-type">string</span></td>
                            <td><span class="param-required">Yes</span></td>
                            <td>The unique order ID reference you sent during order creation.</td>
                        </tr>
                    </tbody>
                </table>

                <div class="code-container">
                    <div class="code-header">
                        <div class="code-tabs" id="checkStatusTabs">
                            <button class="code-tab active" onclick="switchTab('checkStatus', 'curl', this)">cURL</button>
                            <button class="code-tab" onclick="switchTab('checkStatus', 'php', this)">PHP</button>
                            <button class="code-tab" onclick="switchTab('checkStatus', 'node', this)">Node.js</button>
                        </div>
                        <button class="btn-copy" id="checkStatusCopyBtn"><i data-lucide="copy" style="width:12px;"></i> Copy</button>
                    </div>
                    
                    <!-- cURL -->
                    <div class="code-body-wrapper" id="checkStatus-curl">
                        <pre class="code-body"><code class="language-bash">curl -X POST <?php echo APP_DOMAIN; ?>/api/check-status \
  -H "X-API-Key: <?php echo $apiKey; ?>" \
  -H "X-API-Secret: <?php echo $apiSecret; ?>" \
  -H "Content-Type: application/json" \
  -d '{
    "order_id": "<?php echo $sampleOrderId; ?>"
  }'</code></pre>
                    </div>

                    <!-- PHP -->
                    <div class="code-body-wrapper d-none" id="checkStatus-php">
                        <pre class="code-body"><code class="language-php">&lt;?php
$payload = [
    'order_id' => '<?php echo $sampleOrderId; ?>'
];

$ch = curl_init('<?php echo APP_DOMAIN; ?>/api/check-status');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'X-API-Key: <?php echo $apiKey; ?>',
        'X-API-Secret: <?php echo $apiSecret; ?>'
    ]
]);

$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);

if (isset($data['status']) && $data['status'] === 'success') {
    $paymentStatus = $data['data']['payment_status']; // 'success', 'pending', or 'failed'
    echo "Transaction Status: " . strtoupper($paymentStatus);
} else {
    echo "Error checking status: " . ($data['error'] ?? 'Unknown error');
}
?&gt;</code></pre>
                    </div>

                    <!-- NodeJS -->
                    <div class="code-body-wrapper d-none" id="checkStatus-node">
                        <pre class="code-body"><code class="language-javascript">const fetch = require('node-fetch');

fetch('<?php echo APP_DOMAIN; ?>/api/check-status', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': '<?php echo $apiKey; ?>',
    'X-API-Secret': '<?php echo $apiSecret; ?>'
  },
  body: JSON.stringify({ order_id: '<?php echo $sampleOrderId; ?>' })
})
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.error(err));</code></pre>
                    </div>
                </div>

                <h3>Success Response Schema (200 OK)</h3>
                <div class="code-container">
                    <div class="code-header">
                        <span class="text-white-50 font-monospace fs-7">200 OK Response</span>
                        <button class="btn-copy" onclick="copyText(this.nextElementSibling.textContent)"><i data-lucide="copy" style="width:12px;"></i> Copy</button>
                    </div>
                    <pre class="code-body"><code>{
  "status": "success",
  "data": {
    "order_id": "<?php echo $sampleOrderId; ?>",
    "amount": 100.00,
    "currency": "INR",
    "payment_status": "success",
    "customer_name": "Raushan Kumar",
    "customer_mobile": "9999999999",
    "utr": "615372849102",
    "payment_method": "UPI QR",
    "provider": "paytm",
    "gateway_txn_id": "TXN_9201938561",
    "paid_at": "2026-06-05 11:16:45",
    "payment_url": "<?php echo APP_DOMAIN; ?>/pay/LRd7jTFOV2sFyhMyOBzbJLL1SQzMxe5V",
    "callback_url": "https://yourwebsite.com/callback.php",
    "expires_at": "2026-06-06 11:15:30",
    "created_at": "2026-06-05 11:15:30"
  }
}</code></pre>
                </div>
            </section>

            <!-- Webhooks -->
            <section id="webhooks">
                <h2>Webhooks</h2>
                <p>Webhooks are used to receive real-time updates directly on your server whenever a transaction is completed successfully. Instead of polling our check status API, we will send an asynchronous HTTP POST request to your configured webhook URL.</p>
                <p>You can manage and add webhooks in your <a href="<?php echo APP_DOMAIN; ?>/merchant/webhooks.php" target="_blank" class="fw-semibold">Webhooks Portal</a>.</p>

                <h3>Signature Validation</h3>
                <p>To ensure webhook payloads are authentically generated by PayIndia, every webhook request contains a custom header named <strong>`X-PayIndia-Signature`</strong>.</p>
                <p>This signature represents the HMAC-SHA256 hash of the raw POST body payload, signed using your unique **Webhook Secret Key**.</p>
                
                <h3>Sample PHP Webhook Receiver & Verification</h3>
                <div class="code-container">
                    <div class="code-header">
                        <span class="text-white-50 font-monospace fs-7">webhook-handler.php</span>
                        <button class="btn-copy" onclick="copyText(this.nextElementSibling.textContent)"><i data-lucide="copy" style="width:12px;"></i> Copy</button>
                    </div>
                    <pre class="code-body"><code>&lt;?php
// Retrieve the signature header
$signature = $_SERVER['HTTP_X_PAYINDIA_SIGNATURE'] ?? '';

// Get Webhook Secret from your settings
$webhookSecret = "your_webhook_secret_key";

// Read raw POST body payload
$payload = file_get_contents('php://input');

// Calculate expected signature
$expectedSignature = hash_hmac('sha256', $payload, $webhookSecret);

// Verify match
if (hash_equals($expectedSignature, $signature)) {
    // Valid request! Parse JSON
    $data = json_decode($payload, true);
    $orderId = $data['order_id'];
    $amount = $data['amount'];
    $utr = $data['utr'];
    $status = $data['status']; // 'success'
    
    if ($data['event'] === 'payment.success') {
        // 1. Mark order as Paid in your database
        // 2. Deliver goods to customer
    }
    
    // Respond with 200 OK to acknowledge receipt
    http_response_code(200);
    echo json_encode(['received' => true]);
} else {
    // Invalid signature, ignore/fail
    http_response_code(400);
    echo "Invalid signature";
}
?&gt;</code></pre>
                </div>
            </section>

            <!-- Callbacks & Redirect -->
            <section id="callback">
                <h2>Callbacks & Redirect</h2>
                <p>If you passed a `callback_url` when creating the order, PayIndia will automatically redirect your customer's browser to this URL immediately after a successful checkout verification.</p>
                <p>When redirecting, we append key transaction details as URL query parameters:</p>
                <div class="code-container">
                    <div class="code-header">
                        <span class="text-white-50 font-monospace fs-7">Example Redirect URL</span>
                        <button class="btn-copy" onclick="copyText(this.nextElementSibling.textContent)"><i data-lucide="copy" style="width:12px;"></i> Copy</button>
                    </div>
                    <pre class="code-body"><code>https://yourwebsite.com/callback.php?status=success&order_id=<?php echo $sampleOrderId; ?>&amount=100.00&utr=615372849102</code></pre>
                </div>

                <div class="warning-box">
                    <h5><i data-lucide="shield" style="width:16px; height:16px;"></i> Secure Verification Requirement</h5>
                    <p>Browser redirects can easily be modified by malicious users. <strong>Never</strong> finalize transactions or deliver digital goods based solely on URL parameter states. Always run a backend status check API call or wait for the webhook trigger to confirm the payment was captured.</p>
                </div>
            </section>

            <!-- Full Flow Example -->
            <section id="full-flow-example">
                <h2>PHP Integration Flow</h2>
                <p>Here is a complete, step-by-step implementation showcasing how to create a payment checkout, redirect the user, and process the callback securely.</p>
                
                <div class="code-container">
                    <div class="code-header">
                        <span class="text-white-50 font-monospace fs-7">Complete Integration Sample</span>
                        <button class="btn-copy" onclick="copyText(this.nextElementSibling.textContent)"><i data-lucide="copy" style="width:12px;"></i> Copy</button>
                    </div>
                    <pre class="code-body"><code>&lt;?php
/**
 * Step 1: Initialize Payment Order
 */
function initiatePayment($orderId, $amount, $customerName) {
    $apiKey = "<?php echo $apiKey; ?>";
    $apiSecret = "<?php echo $apiSecret; ?>";
    
    $payload = [
        'amount' => number_format($amount, 2, '.', ''),
        'order_id' => $orderId,
        'customer_name' => $customerName,
        'callback_url' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?action=callback'
    ];

    $ch = curl_init('<?php echo APP_DOMAIN; ?>/api/create-order');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'X-API-Key: ' . $apiKey,
            'X-API-Secret: ' . $apiSecret
        ]
    ]);

    $response = curl_exec($ch);
    $data = json_decode($response, true);
    curl_close($ch);

    if (isset($data['status']) && $data['status'] === 'success') {
        // Redirect customer to PayIndia payment card
        header("Location: " . $data['data']['payment_url']);
        exit;
    } else {
        die("Payment initiation failed: " . ($data['error'] ?? 'Unknown Error'));
    }
}

/**
 * Step 2: Handle Browser Redirect Callback
 */
function handleCallback() {
    $orderId = $_GET['order_id'] ?? '';
    $status = $_GET['status'] ?? '';
    
    if (empty($orderId) || $status !== 'success') {
        die("Payment was not successful or was cancelled.");
    }
    
    // Now verify status securely on the backend
    $apiKey = "<?php echo $apiKey; ?>";
    $apiSecret = "<?php echo $apiSecret; ?>";
    
    $ch = curl_init('<?php echo APP_DOMAIN; ?>/api/check-status');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['order_id' => $orderId]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'X-API-Key: ' . $apiKey,
            'X-API-Secret: ' . $apiSecret
        ]
    ]);

    $response = curl_exec($ch);
    $data = json_decode($response, true);
    curl_close($ch);

    if (isset($data['status']) && $data['status'] === 'success' && $data['data']['payment_status'] === 'success') {
        $amount = $data['data']['amount'];
        $utr = $data['data']['utr'];
        
        echo "&lt;h1 style='color:green;'&gt;Payment Successful!&lt;/h1&gt;";
        echo "&lt;p&gt;Thank you, your order &lt;strong&gt;$orderId&lt;/strong&gt; of ₹$amount has been paid successfully.&lt;/p&gt;";
        echo "&lt;p&gt;UTR Reference: $utr&lt;/p&gt;";
    } else {
        echo "&lt;h1 style='color:red;'&gt;Verification Failed&lt;/h1&gt;";
        echo "&lt;p&gt;The payment verification returned an unconfirmed status.&lt;/p&gt;";
    }
}

// Simple Router Trigger
$action = $_GET['action'] ?? '';
if ($action === 'pay') {
    $randomOrderId = 'ORD_' . uniqid();
    initiatePayment($randomOrderId, 100.00, 'Raushan Kumar');
} elseif ($action === 'callback') {
    handleCallback();
} else {
    // Show initiation button
    echo "&lt;a href='?action=pay' style='padding:12px 24px; background:#0B3D2E; color:#C6E547; text-decoration:none; border-radius:8px; font-family:sans-serif; font-weight:bold;'&gt;Pay ₹100 using PayIndia&lt;/a&gt;";
}
?></code></pre>
                </div>
            </section>
            
        </main>
    </div>

    <!-- Scripts CDN -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
    <script>
        lucide.createIcons();

        // Active sidebar link scrolling
        function activateLink(link) {
            document.querySelectorAll('.sidebar-nav-link').forEach(el => el.classList.remove('active'));
            link.classList.add('active');
        }

        // Handle Active menu highlighting on page scroll
        window.addEventListener('DOMContentLoaded', () => {
            const observer = new IntersectionObserver(entries => {
                entries.forEach(entry => {
                    const id = entry.target.getAttribute('id');
                    if (entry.intersectionRatio > 0) {
                        const link = document.querySelector(`.sidebar-nav-link[href="#${id}"]`);
                        if (link) {
                            document.querySelectorAll('.sidebar-nav-link').forEach(el => el.classList.remove('active'));
                            link.classList.add('active');
                        }
                    }
                });
            });

            document.querySelectorAll('section[id]').forEach((section) => {
                observer.observe(section);
            });
        });

        // Tab Switching for Code Snippets
        function switchTab(containerId, tabName, btn) {
            // Deactivate all tabs inside container
            const container = btn.closest('.code-container');
            container.querySelectorAll('.code-tab').forEach(t => t.classList.remove('active'));
            btn.classList.add('active');

            // Hide all body blocks
            container.querySelectorAll('.code-body-wrapper').forEach(body => body.classList.add('d-none'));
            
            // Show selected body block
            const targetBody = container.querySelector(`#${containerId}-${tabName}`);
            if (targetBody) {
                targetBody.classList.remove('d-none');
            }
        }

        // Copy Code Text Helper
        function copyText(text) {
            navigator.clipboard.writeText(text).then(() => {
                alert('Copied to clipboard!');
            });
        }

        // Copy button binder
        document.getElementById('createOrderCopyBtn').addEventListener('click', function() {
            const container = this.closest('.code-container');
            const visibleCodeBlock = container.querySelector('.code-body-wrapper:not(.d-none) code');
            copyText(visibleCodeBlock.textContent);
        });

        document.getElementById('checkStatusCopyBtn').addEventListener('click', function() {
            const container = this.closest('.code-container');
            const visibleCodeBlock = container.querySelector('.code-body-wrapper:not(.d-none) code');
            copyText(visibleCodeBlock.textContent);
        });
    </script>
</body>
</html>
