<?php
// PhonePe Payment Gateway API - Browser Testable Version
// Based on PhonePe Developer Documentation: https://developer.phonepe.com/

// Version header for deploy verification
define('BUILD_VERSION', 'v2025-09-27_19:00_BROWSER_TESTABLE');
header('X-App-Build: '.BUILD_VERSION);
error_log('[PG] BUILD='.BUILD_VERSION);


// ---- Production credentials ----
$CLIENT_ID      = "SU2509232050194428161935";
$CLIENT_VERSION = "1";
$CLIENT_SECRET  = "ac7d0d8f-8bb1-45c4-baab-5f6f5e6ac3a2";
$MERCHANT_ID    = "M23N011JX7ZSO";

// ---- PRODUCTION endpoints ----
$AUTH_URL        = 'https://api.phonepe.com/apis/identity-manager/v1/oauth/token';
$PAY_URL         = 'https://api.phonepe.com/apis/pg/checkout/v2/pay';
$STATUS_URL_BASE = 'https://api.phonepe.com/apis/pg/checkout/v2/order/';

// ---------- helpers ----------
function http_post_json($url, $payload, $headers = [], $timeout = 25) {
    $ch = curl_init($url);
    $finalHeaders = array_merge(['Content-Type: application/json'], $headers);
    
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => $finalHeaders,
        CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
        CURLOPT_TIMEOUT        => $timeout,
    ]);
    
    $res  = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = $res === false ? curl_error($ch) : null;
    curl_close($ch);
    
    return [json_decode($res, true), $code, $err];
}

function http_post_form($url, $fields, $timeout = 25) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_POSTFIELDS     => http_build_query($fields),
        CURLOPT_TIMEOUT        => $timeout,
    ]);
    
    $res  = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = $res === false ? curl_error($ch) : null;
    curl_close($ch);
    
    return [json_decode($res, true), $code, $err];
}

function http_get_json($url, $headers = [], $timeout = 25) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_TIMEOUT        => $timeout,
    ]);
    
    $res  = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = $res === false ? curl_error($ch) : null;
    curl_close($ch);
    
    return [json_decode($res, true), $code, $err];
}

// ---------- OAuth token with cache ----------
function get_oauth_token($AUTH_URL, $CLIENT_ID, $CLIENT_VERSION, $CLIENT_SECRET) {
    $cache = sys_get_temp_dir() . '/phonepe_oauth_token.json';
    
    if (file_exists($cache)) {
        $saved = json_decode(file_get_contents($cache), true);
        if (!empty($saved['access_token']) && $saved['expires_at'] > time() + 60) {
            return $saved['access_token'];
        }
    }
    
    list($resp, $code, $err) = http_post_form($AUTH_URL, [
        'client_id'      => $CLIENT_ID,
        'client_version' => $CLIENT_VERSION,
        'client_secret'  => $CLIENT_SECRET,
        'grant_type'     => 'client_credentials',
    ]);
    
    if ($err || $code < 200 || $code >= 300) {
        http_response_code(502);
        echo json_encode(['success'=>false,'step'=>'oauth','code'=>$code,'error'=>$err,'resp'=>$resp]); 
        exit;
    }
    
    if (empty($resp['access_token'])) {
        http_response_code(502);
        echo json_encode(['success'=>false,'step'=>'oauth','code'=>$code,'error'=>'No access token','resp'=>$resp]); 
        exit;
    }
    
    $resp['expires_at'] = time() + (isset($resp['expires_in']) ? intval($resp['expires_in']) : 3600);
    @file_put_contents($cache, json_encode($resp));
    
    return $resp['access_token'];
}

// ---------- routes ----------
$script = $_SERVER['SCRIPT_NAME'];
$path   = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$route  = str_replace($script, '', $path);
if ($route === '') $route = '/';
if (strpos($path, '/webhook') !== false) $route = '/webhook';

// Debug: Set JSON headers for API routes based on path
if (in_array($route, ['/createPayment', '/status', '/webhook'])) {
    // Clear any previous output
    if (ob_get_level()) ob_clean();
    
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);
    
    // Disable error display for API responses
    ini_set('display_errors', 0);
    error_reporting(0);
}

// ---------- Browser Test Page ----------
if ($route === '/' && $_SERVER['REQUEST_METHOD'] === 'GET') {
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>PhonePe API Test - AstroSidhi</title>
        <style>
            body { 
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
                margin: 0; 
                padding: 20px; 
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
            }
            .container { 
                max-width: 900px; 
                margin: 0 auto; 
                background: white; 
                padding: 30px; 
                border-radius: 15px; 
                box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            }
            .header { 
                text-align: center; 
                color: #333; 
                margin-bottom: 30px; 
                border-bottom: 2px solid #f0f0f0;
                padding-bottom: 20px;
            }
            .header h1 {
                color: #2c3e50;
                margin-bottom: 10px;
                font-size: 2.5em;
            }
            .header p {
                color: #7f8c8d;
                margin: 5px 0;
            }
            .build-info {
                background: #e8f4fd;
                padding: 10px;
                border-radius: 8px;
                border-left: 4px solid #3498db;
                margin-top: 15px;
            }
            .form-group { 
                margin-bottom: 20px; 
            }
            label { 
                display: block; 
                margin-bottom: 8px; 
                font-weight: 600; 
                color: #2c3e50;
                font-size: 14px;
            }
            input, select { 
                width: 100%; 
                padding: 12px 15px; 
                border: 2px solid #e1e8ed; 
                border-radius: 8px; 
                font-size: 16px; 
                transition: all 0.3s ease;
                box-sizing: border-box;
            }
            input:focus, select:focus {
                border-color: #3498db;
                outline: none;
                box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
            }
            button { 
                background: linear-gradient(45deg, #3498db, #2980b9);
                color: white; 
                padding: 15px 25px; 
                border: none; 
                border-radius: 8px; 
                cursor: pointer; 
                font-size: 16px; 
                font-weight: 600;
                margin-right: 15px; 
                margin-bottom: 10px;
                transition: all 0.3s ease;
                box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
            }
            button:hover { 
                background: linear-gradient(45deg, #2980b9, #1f618d);
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
            }
            button:active {
                transform: translateY(0);
            }
            .result { 
                margin-top: 25px; 
                padding: 20px; 
                background: #f8f9fa; 
                border-radius: 10px; 
                border-left: 5px solid #3498db;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .error { 
                border-left-color: #e74c3c; 
                background: #fdf2f2; 
            }
            .success { 
                border-left-color: #27ae60; 
                background: #f0f9f0; 
            }
            .info {
                border-left-color: #f39c12;
                background: #fefbf0;
            }
            pre { 
                background: #2c3e50; 
                color: #ecf0f1;
                padding: 15px; 
                border-radius: 8px; 
                overflow-x: auto; 
                font-size: 14px;
                margin: 10px 0;
            }
            .url-box { 
                background: #ecf0f1; 
                padding: 15px; 
                border-radius: 8px; 
                word-break: break-all; 
                font-family: 'Courier New', monospace;
                font-size: 14px;
                border: 1px solid #bdc3c7;
                margin: 10px 0;
            }
            .form-row {
                display: flex;
                gap: 15px;
            }
            .form-row .form-group {
                flex: 1;
            }
            .status-badge {
                display: inline-block;
                padding: 5px 12px;
                border-radius: 20px;
                font-size: 12px;
                font-weight: 600;
                text-transform: uppercase;
            }
            .status-pending { background: #fff3cd; color: #856404; }
            .status-success { background: #d4edda; color: #155724; }
            .status-failed { background: #f8d7da; color: #721c24; }
            .amount-display {
                font-size: 24px;
                font-weight: bold;
                color: #27ae60;
            }
            @media (max-width: 768px) {
                .container { padding: 20px; margin: 10px; }
                .form-row { flex-direction: column; }
                button { width: 100%; margin-right: 0; }
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>🔧 PhonePe API Test</h1>
                <p>Test PhonePe Payment Gateway Integration</p>
                <p><strong>Build:</strong> <?php echo BUILD_VERSION; ?></p>
            </div>
            
            <form id="paymentForm">
                <div class="form-group">
                    <label>Amount (₹):</label>
                    <input type="number" id="amount" value="1" min="1" step="0.01">
                </div>
                
                <div class="form-group">
                    <label>Customer Name:</label>
                    <input type="text" id="customerName" value="Test User">
                </div>
                
                <div class="form-group">
                    <label>Customer Mobile:</label>
                    <input type="text" id="customerMobile" value="9828479035">
                </div>
                
                <div class="form-group">
                    <label>Customer Email:</label>
                    <input type="email" id="customerEmail" value="test@astro.com">
                </div>
                
                <div class="form-group">
                    <label>Description:</label>
                    <input type="text" id="description" value="Test Payment">
                </div>
                
                <button type="button" onclick="createPayment()">🚀 Create Payment</button>
                <button type="button" onclick="checkStatus()">📊 Check Status</button>
                <button type="button" onclick="clearResults()">🗑️ Clear</button>
            </form>
            
            <div id="result"></div>
        </div>
        
        <script>
            let currentOrderId = null;
            
            async function createPayment() {
                const amount = document.getElementById('amount').value;
                const customerName = document.getElementById('customerName').value;
                const customerMobile = document.getElementById('customerMobile').value;
                const customerEmail = document.getElementById('customerEmail').value;
                const description = document.getElementById('description').value;
                
                const data = {
                    amount: Math.round(amount * 100), // Convert to paise
                    customerName: customerName,
                    customerMobile: customerMobile,
                    customerEmail: customerEmail,
                    description: description,
                    merchantOrderId: 'BROWSER-' + Date.now() + '-' + Math.floor(Math.random() * 1000),
                    webhookUrl: window.location.origin + window.location.pathname + '/webhook'
                };
                
                showResult('Creating payment...', 'info');
                
                try {
                    const response = await fetch(window.location.pathname + '/createPayment', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });
                    
                    const result = await response.json();
                    
                    if (response.ok && result.redirectUrl) {
                        currentOrderId = result.orderId;
                        showResult(`
                            <h3>✅ Payment Created Successfully!</h3>
                            <p><strong>Order ID:</strong> ${result.orderId}</p>
                            <p><strong>State:</strong> ${result.state}</p>
                            <p><strong>Amount:</strong> ₹${amount}</p>
                            <p><strong>Redirect URL:</strong></p>
                            <div class="url-box">${result.redirectUrl}</div>
                            <br>
                            <button onclick="window.open('${result.redirectUrl}', '_blank')">🌐 Open Payment Page</button>
                            <button onclick="copyToClipboard('${result.redirectUrl}')">📋 Copy URL</button>
                        `, 'success');
                    } else {
                        showResult(`
                            <h3>❌ Payment Creation Failed</h3>
                            <pre>${JSON.stringify(result, null, 2)}</pre>
                        `, 'error');
                    }
                } catch (error) {
                    showResult(`
                        <h3>❌ Error</h3>
                        <p>${error.message}</p>
                    `, 'error');
                }
            }
            
            async function checkStatus() {
                if (!currentOrderId) {
                    showResult('❌ No order ID available. Create a payment first.', 'error');
                    return;
                }
                
                showResult('Checking status...', 'info');
                
                try {
                    const response = await fetch(window.location.pathname + '/status', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ merchantOrderId: currentOrderId })
                    });
                    
                    const result = await response.json();
                    
                    if (response.ok) {
                        showResult(`
                            <h3>📊 Payment Status</h3>
                            <p><strong>Order ID:</strong> ${result.orderId}</p>
                            <p><strong>State:</strong> ${result.state}</p>
                            <p><strong>Amount:</strong> ₹${(result.amount / 100).toFixed(2)}</p>
                            <pre>${JSON.stringify(result, null, 2)}</pre>
                        `, 'success');
                    } else {
                        showResult(`
                            <h3>❌ Status Check Failed</h3>
                            <pre>${JSON.stringify(result, null, 2)}</pre>
                        `, 'error');
                    }
                } catch (error) {
                    showResult(`
                        <h3>❌ Error</h3>
                        <p>${error.message}</p>
                    `, 'error');
                }
            }
            
            function showResult(content, type) {
                const resultDiv = document.getElementById('result');
                resultDiv.innerHTML = `<div class="result ${type}">${content}</div>`;
            }
            
            function clearResults() {
                document.getElementById('result').innerHTML = '';
                currentOrderId = null;
            }
            
            function copyToClipboard(text) {
                navigator.clipboard.writeText(text).then(() => {
                    alert('URL copied to clipboard!');
                });
            }
        </script>
    </body>
    </html>
    <?php
    exit;
}

// ---------- debug route ----------
if ($route === '/debug' && $_SERVER['REQUEST_METHOD'] === 'GET') {
    echo json_encode([
        'route' => $route,
        'path' => $path,
        'script' => $script,
        'method' => $_SERVER['REQUEST_METHOD'],
        'headers_sent' => headers_sent(),
        'content_type' => headers_list()
    ]);
    exit;
}

// ---------- create payment ----------
if ($route === '/createPayment' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $in = json_decode(file_get_contents('php://input'), true) ?: [];
        
        $merchantOrderId = $in['merchantOrderId'] ?? 'BROWSER-' . time() . '-' . random_int(1000, 9999);
        $amountPaise     = intval($in['amount'] ?? 0);
        $webhookUrl      = $in['webhookUrl'] ?? 'https://astro.siddharthnahar.in/astro_admin/api/phonepe_v2_backend.php/webhook';
        
        if ($amountPaise < 100) {
            http_response_code(400);
            echo json_encode(['success'=>false,'message'=>'amount (>=100 paise) required']); 
            exit;
    }
    
    $token = get_oauth_token($AUTH_URL, $CLIENT_ID, $CLIENT_VERSION, $CLIENT_SECRET);
    
    // V2 API Payload Structure
    $body = [
        'merchantOrderId' => $merchantOrderId,
        'amount'          => $amountPaise,
        'paymentFlow'     => [
            'type' => 'PG_CHECKOUT',
            'merchantUrls' => [
                'webhookUrl'  => $webhookUrl,
                'successUrl'  => 'https://astro.siddharthnahar.in/astro_admin/api/payment-success.php',
                'failureUrl'  => 'https://astro.siddharthnahar.in/astro_admin/api/payment-failed.php'
            ]
        ]
    ];
    
    list($resp, $code, $err) = http_post_json($PAY_URL, $body, [
        "Authorization: O-Bearer $token",
        "X-Version: 2.0",
        "X-Request-ID: " . uniqid(),
        "User-Agent: AstroSidhi/1.0",
        "Accept: application/json"
    ]);
    
    if ($err) {
        http_response_code(502);
        echo json_encode(['success'=>false,'error'=>$err]); 
        exit;
    }
    
    if ($code < 200 || $code >= 300) {
        http_response_code(502);
        echo json_encode(['success'=>false,'code'=>$code,'error'=>'HTTP Error','resp'=>$resp]); 
        exit;
    }
    
    echo json_encode($resp); 
    exit;
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success'=>false,'error'=>'Server Error','message'=>$e->getMessage()]);
        exit;
    }
}

// ---------- status ----------
if ($route === '/status' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $in = json_decode(file_get_contents('php://input'), true) ?: [];
        $orderId = $in['merchantOrderId'] ?? '';
        
        if ($orderId === '') { 
            http_response_code(400); 
            echo json_encode(['success'=>false,'message'=>'orderId required']); 
            exit; 
        }
    
    $token = get_oauth_token($AUTH_URL, $CLIENT_ID, $CLIENT_VERSION, $CLIENT_SECRET);
    
    $url = $STATUS_URL_BASE . rawurlencode($orderId) . '/status?details=false';
    
    list($resp, $code, $err) = http_get_json($url, [
        "Authorization: O-Bearer $token"
    ]);
    
    echo json_encode($resp); 
    exit;
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success'=>false,'error'=>'Server Error','message'=>$e->getMessage()]);
        exit;
    }
}

// ---------- webhook ----------
if ($route === '/webhook') {
    $raw = file_get_contents('php://input');
    $webhookData = json_decode($raw, true);
    $orderId = $webhookData['orderId'] ?? '';
    $state = $webhookData['state'] ?? '';
    
    error_log("Webhook Data: orderId=$orderId, state=$state");
    
    http_response_code(200);
    echo json_encode(['ok'=>true, 'received'=>true]); 
    exit;
}

http_response_code(404);
echo json_encode(['error'=>'Endpoint not found']);
?>
