<?php
/**
 * PayIndia - Standalone Integration Demo & Redirect Example
 *
 * This file is completely independent of the platform's database.
 * You can copy this code and host it on any external merchant website
 * to integrate the PayIndia Payment Gateway.
 */

// =====================================================================
// 1. CONFIGURATION: Configure your merchant API keys here
// =====================================================================
$apiKey = 'pi_test_xxxxxxxxxxxxxxxxxxxxxxxx';    // Replace with your API Key/Sandbox Key
$apiSecret = 'sk_test_xxxxxxxxxxxxxxxxxxxxxxxx'; // Replace with your API Secret Key

// Dynamically detect base domain and API endpoint URL
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
$apiBaseUrl = $protocol . $_SERVER['HTTP_HOST'] . '/api';

// =====================================================================
// 2. ROUTER: Detect callback redirects vs. payment initiation
// =====================================================================
$action = $_GET['action'] ?? '';

if ($action === 'callback') {
    // -----------------------------------------------------------------
    // CALLBACK STAGE: Customer returned to website after checkout
    // -----------------------------------------------------------------
    $orderId = strip_tags($_GET['order_id'] ?? '');
    $status = strip_tags($_GET['status'] ?? '');
    
    $txnVerified = null;
    $errorMessage = '';

    if (!empty($orderId)) {
        // Securely verify transaction status on the backend using cURL
        $payload = ['order_id' => $orderId];

        $ch = curl_init($apiBaseUrl . '/check-status');
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'X-API-Key: ' . $apiKey,
                'X-API-Secret: ' . $apiSecret
            ]
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $data = json_decode($response, true);
        if ($httpCode === 200 && isset($data['status']) && $data['status'] === 'success') {
            $txnVerified = $data['data'];
        } else {
            $errorMessage = $data['error'] ?? 'Backend verification failed.';
        }
    } else {
        $errorMessage = 'Invalid callback parameters.';
    }
    
    // Render the beautiful success / failure receipt
    renderReceiptHTML($txnVerified, $errorMessage, $orderId);

} else {
    // -----------------------------------------------------------------
    // INITIATION STAGE: Trigger payment and redirect customer
    // -----------------------------------------------------------------
    $orderId = 'ORD_' . time() . '_' . rand(1000, 9999);
    $amount = '10.00'; // Target amount in INR
    $customerName = 'Demo Customer';
    
    // Redirect callback URL back to this script
    $callbackUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?action=callback';

    $payload = [
        'amount' => $amount,
        'order_id' => $orderId,
        'customer_name' => $customerName,
        'description' => 'Demo Payment Simulation',
        'callback_url' => $callbackUrl
    ];

    // Request new checkout link from PayIndia REST API
    $ch = curl_init($apiBaseUrl . '/create-order');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'X-API-Key: ' . $apiKey,
            'X-API-Secret: ' . $apiSecret
        ]
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr = curl_error($ch);
    curl_close($ch);

    if ($curlErr) {
        renderErrorHTML('Connection Failure', 'Failed to connect to gateway endpoint: ' . $curlErr, $payload, $apiBaseUrl);
    } else {
        $data = json_decode($response, true);
        if ($httpCode === 201 && isset($data['status']) && $data['status'] === 'success') {
            $paymentUrl = $data['data']['payment_url'];
            
            // Redirect customer immediately to payment checkout link
            header('Location: ' . $paymentUrl);
            exit;
        } else {
            // Render credentials error screen
            $detail = $data['error'] ?? 'Please confirm your X-API-Key and X-API-Secret credentials are set correctly inside the source code of this file.';
            renderErrorHTML('API Authentication Failed', $detail, $payload, $apiBaseUrl, $data);
        }
    }
}

// =====================================================================
// Helper Functions to Render Responsive HTML Screens
// =====================================================================

function renderReceiptHTML($txn, $error, $orderId) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Transaction Receipt - PayIndia Demo</title>
        <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
        <style>
            body { font-family: 'Inter', sans-serif; background-color: #F8FAF7; padding: 40px 15px; color: #1a2e1a; }
            .receipt-card { max-width: 520px; background: #fff; margin: 0 auto; border-radius: 16px; border: 1px solid #E8EDE5; box-shadow: 0 4px 24px rgba(11, 61, 46, 0.04); padding: 30px; }
            .checkmark-wrapper { width: 64px; height: 64px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; }
            .checkmark-wrapper.success { background-color: #ECFDF5; color: #10B981; border: 2px solid #A7F3D0; }
            .checkmark-wrapper.danger { background-color: #FEF2F2; color: #EF4444; border: 2px solid #FCA5A5; }
            .receipt-table { width: 100%; margin-top: 25px; border-collapse: collapse; font-size: 14px; }
            .receipt-table td { padding: 12px 0; border-bottom: 1px dashed #E8EDE5; }
            .receipt-table tr:last-child td { border-bottom: none; }
            .receipt-label { color: #5f7a5f; text-align: left; }
            .receipt-value { font-weight: 600; text-align: right; color: #0B3D2E; }
            .btn-action { background-color: #0B3D2E; color: #C6E547; border: none; padding: 12px 24px; font-weight: 700; border-radius: 12px; transition: all 0.2s; width: 100%; text-decoration: none; display: block; text-align: center; margin-top: 30px; }
            .btn-action:hover { background-color: #0d4a37; color: #C6E547; transform: translateY(-1px); }
        </style>
    </head>
    <body>
        <div class="receipt-card">
            <?php if ($txn && $txn['payment_status'] === 'success'): ?>
                <div class="checkmark-wrapper success">
                    <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
                </div>
                <h3 class="text-center fw-bold text-success mb-1">Payment Successful!</h3>
                <p class="text-muted text-center small">Transaction verified via gateway API</p>
                
                <table class="receipt-table">
                    <tr>
                        <td class="receipt-label">Order ID</td>
                        <td class="receipt-value font-monospace"><?= htmlspecialchars($txn['order_id']) ?></td>
                    </tr>
                    <tr>
                        <td class="receipt-label">Customer Name</td>
                        <td class="receipt-value"><?= htmlspecialchars($txn['customer_name']) ?></td>
                    </tr>
                    <tr>
                        <td class="receipt-label">Verified Amount</td>
                        <td class="receipt-value text-success fw-bold">₹<?= number_format($txn['amount'], 2) ?></td>
                    </tr>
                    <tr>
                        <td class="receipt-label">UTR Reference</td>
                        <td class="receipt-value font-monospace"><?= htmlspecialchars($txn['utr'] ?: 'Pending') ?></td>
                    </tr>
                    <tr>
                        <td class="receipt-label">Payment Method</td>
                        <td class="receipt-value text-uppercase"><?= htmlspecialchars($txn['payment_method'] ?: 'UPI') ?></td>
                    </tr>
                    <tr>
                        <td class="receipt-label">Paid Timestamp</td>
                        <td class="receipt-value"><?= htmlspecialchars($txn['paid_at'] ?: $txn['created_at']) ?></td>
                    </tr>
                </table>
            <?php else: ?>
                <div class="checkmark-wrapper danger">
                    <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
                </div>
                <h3 class="text-center fw-bold text-danger mb-1">Verification Failed</h3>
                <p class="text-muted text-center small"><?= htmlspecialchars($error ?: 'Unconfirmed payment status.') ?></p>
                
                <table class="receipt-table">
                    <tr>
                        <td class="receipt-label">Order ID</td>
                        <td class="receipt-value font-monospace"><?= htmlspecialchars($orderId) ?></td>
                    </tr>
                    <tr>
                        <td class="receipt-label">Payment Status</td>
                        <td class="receipt-value text-danger">Unverified / Failed</td>
                    </tr>
                </table>
            <?php endif; ?>
            
            <a href="demo" class="btn-action">Return to Demo Page</a>
        </div>
    </body>
    </html>
    <?php
}

function renderErrorHTML($title, $details, $payload, $endpoint, $rawResponse = null) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Checkout Setup Error - 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">
        <style>
            body { font-family: 'Inter', sans-serif; background-color: #F8FAF7; padding: 50px 15px; color: #1a2e1a; }
            .error-card { max-width: 680px; background: #fff; margin: 0 auto; border-radius: 16px; border: 1px solid #E8EDE5; box-shadow: 0 4px 24px rgba(11, 61, 46, 0.04); padding: 30px; }
            .error-header { display: flex; align-items: center; gap: 15px; margin-bottom: 20px; border-bottom: 2px solid #FEE2E2; padding-bottom: 15px; }
            .error-icon { width: 44px; height: 44px; border-radius: 10px; background-color: #FEF2F2; color: #EF4444; display: flex; align-items: center; justify-content: center; }
            .code-panel { background: #051e16; color: #E2E8F0; padding: 20px; border-radius: 12px; font-family: 'Fira Code', monospace; font-size: 12.5px; margin-top: 20px; overflow-x: auto; }
            .code-label { font-size: 11px; font-weight: 700; color: #8fa08f; text-transform: uppercase; margin-bottom: 6px; }
        </style>
    </head>
    <body>
        <div class="error-card">
            <div class="error-header">
                <div class="error-icon">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>
                </div>
                <div>
                    <h3 class="mb-0 fw-bold text-danger"><?= htmlspecialchars($title) ?></h3>
                    <p class="text-muted small mb-0">PayIndia checkout gateway integration guide</p>
                </div>
            </div>
            
            <p class="mb-3">Our payment simulator page encountered an error when trying to request a checkout session:</p>
            <div class="alert alert-danger p-3 rounded-3 mb-4">
                <strong>Error Details:</strong> <?= htmlspecialchars($details) ?>
            </div>
            
            <h5 class="fw-bold mb-2">How to Fix This:</h5>
            <ol class="small text-muted mb-4">
                <li>Open <strong><code>demo.php</code></strong> in a text editor.</li>
                <li>Locate variables <strong><code>$apiKey</code></strong> and <strong><code>$apiSecret</code></strong> at the top of the file (lines 14 & 15).</li>
                <li>Replace the mock credentials with the active API keys generated inside your merchant dashboard.</li>
                <li>Refresh this page to run the checkout redirect automatically.</li>
            </ol>

            <div class="code-label">Target Endpoint URL</div>
            <pre class="code-panel p-2 mb-3"><code><?= htmlspecialchars($endpoint) ?></code></pre>

            <div class="code-label">Request Payload Sent</div>
            <pre class="code-panel p-3 mb-3"><code><?= json_encode($payload, JSON_PRETTY_PRINT) ?></code></pre>
            
            <?php if ($rawResponse): ?>
                <div class="code-label">Raw Response Received</div>
                <pre class="code-panel p-3 text-warning"><code><?= json_encode($rawResponse, JSON_PRETTY_PRINT) ?></code></pre>
            <?php endif; ?>
        </div>
    </body>
    </html>
    <?php
}
?>
