<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once('../database/config.php');
require_once('../partner/rspay/config.php');

// Check if the token is provided
if (isset($_REQUEST['token'])) {
$token = $_REQUEST['token'];

// Fetch token data from the database
$token_data_query = $conn->prepare("SELECT * FROM create_orders WHERE token = ?");
// Debug Logging
function log_message($msg) {
    $logFile = __DIR__ . '/payment_debug.log';
    file_put_contents($logFile, date('Y-m-d H:i:s') . " - " . $msg . "\n", FILE_APPEND);
}

$token_data_query->bindParam(1, $token, PDO::PARAM_STR);
$token_data_query->execute();
$token_data = $token_data_query->fetch();

if ($token_data) {
// Check if token has expired
if (time() > $token_data['expiration_time']) {
$res = [
"status" => "FAILED",
"message" => "Token has expired."
];
} else {
// Fetch required details from the token data
$orderid = $token_data['orderid'];
$amount = $token_data['amount'];
$customer_name = $token_data['customer_name'];
$merchant_name = $token_data['merchant_name'];
$upi_id = $token_data['upi_id'];
$user = $token_data['user'];
$redirect_url = $token_data['redirect_url'];

// Helper function for cURL request with timeout
if (!function_exists('fetch_url_content')) {
    function fetch_url_content($url) {
        if (function_exists('curl_init')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $data = curl_exec($ch);
            $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpcode >= 200 && $httpcode < 300) {
                return $data;
            }
        }
        $ctx = stream_context_create(array('http'=>
            array('timeout' => 5)
        ));
        return @file_get_contents($url, false, $ctx);
    }
}

// ============================================
// UPI POOL SYSTEM - Gateway Selection
// ============================================
// ============================================
// UPI POOL SYSTEM - Gateway Selection
// ============================================
try {
    $upiManager = null;
    $poolManagerPath = '../database/UpiPoolManager.php';
    
    if (file_exists($poolManagerPath)) {
        require_once($poolManagerPath);
        if (class_exists('UpiPoolManager')) {
            $upiManager = new UpiPoolManager($conn);
            $gateway_settings = $upiManager->getGatewaySettings();
        } else {
            throw new Exception("Class UpiPoolManager not found");
        }
    } else {
        throw new Exception("File UpiPoolManager.php not found");
    }

    // Determine which gateway to use
    $use_bank_upi = false;
    // Default to RSPay/others if settings are missing/default
    $selected_gateway = $gateway_settings['default_gateway'] ?? 'rspay'; 
    
    // Check if RSPay is configured
    // If RSPay credentials missing, force Bank UPI
    if (!isset($rspay_merchant_id) || empty($rspay_merchant_id) || !isset($rspay_key) || empty($rspay_key)) {
        $selected_gateway = 'bank_upi';
    }

    if ($selected_gateway == 'bank_upi') {
        $use_bank_upi = true;
    } elseif ($selected_gateway == 'auto') {
        // Smart selection - use bank UPI for amounts < 5000
        if ($amount < 5000) {
            $use_bank_upi = true;
        }
    }
} catch (Throwable $e) {
    log_message("CRITICAL ERROR in UPI Manager: " . $e->getMessage());
    $use_bank_upi = false; // Fallback silently
    $gateway_settings = ['default_gateway' => 'rspay', 'bank_upi_commission' => 2.00, 'bank_upi_fixed' => 0];
}

// Function to execute Bank UPI logic (reusable)
function executeBankUpiLogic($upiManager, $conn, $orderid, $amount, $customer_name, $token_data, $gateway_settings) {
    log_message("Executing Bank UPI Logic for Order: " . $orderid);
    
    if (!$upiManager) {
        log_message("UPI Manager is null in execution function.");
        return null; // Should ideally throw or return error specific
    }

    $upi_data = $upiManager->getNextUPI();
    
    if ($upi_data) {
        // Log UPI assignment
        $upiManager->logUPIAssignment($upi_data['upi_id'], $orderid, $amount);
        
        $upi_id = $upi_data['upi_id'];
        $display_merchant_name = $upi_data['upi_name'];
        $db_merchant_name = 'Bank UPI - ' . $upi_data['upi_name'];
        $merchant_name = $display_merchant_name; 
        
        // Calculate commission
        $commission_percent = $gateway_settings['bank_upi_commission'] ?? 0;
        $fixed_fee = $gateway_settings['bank_upi_fixed'] ?? 0;
        $commission = ($amount * $commission_percent / 100) + $fixed_fee;
        
        // Generate UPI payment URL
        $upi_url = 'upi://pay?pa=' . urlencode($upi_id) .
                   '&pn=' . urlencode($customer_name) .
                   '&am=' . urlencode($amount) .
                   '&tid=' . urlencode($orderid) .
                   '&tr=' . urlencode($orderid) .
                   '&tn=' . urlencode('Payment for ' . $orderid) .
                   '&cu=INR';
        
        // Generate QR code using generic public API (Client-side load)
        // We use api.qrserver.com which is reliable and supports HTTPS
        $qr_code_url = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&margin=10&data=' . urlencode($upi_url);
        
        log_message("QR Code URL generated (Client-side): " . $qr_code_url);
        
        $clientIP = $_SERVER['REMOTE_ADDR']; 
        $timestamp = time(); 
        $combinedData = "orderid=" . $orderid . 
                        "&timestamp=" . $timestamp . 
                        "&user=" . $token_data['user'] . 
                        "&ip_address=" . $clientIP;
        $encodedData = base64_encode($combinedData);

        // Update order with UPI details
        $stmt = $conn->prepare("UPDATE create_orders SET upi_id = ?, merchant_name = ? WHERE orderid = ?");
        $stmt->execute([$upi_id, $db_merchant_name, $orderid]);
        
        log_message("Bank UPI assigned: " . $upi_id);

        return [
            "status" => "SUCCESS",
            "message" => "Payment link generated",
            "orderid" => $orderid,
            "amount" => $amount,
            "customer_name" => $customer_name,
            "merchant_name" => $merchant_name,
            "upi_id" => $upi_id,
            "payment_link" => $upi_url,
            "qr_code" => $qr_code_url,
            "expiration_time" => date('Y-m-d H:i:s', $token_data['expiration_time']),
            "gateway" => "bank_upi",
            "commission" => $commission,
            "encoded_data" => $encodedData,
            "is_hdfc" => false
        ];
    } else {
        log_message("No Active UPIs found in pool.");
        return null;
    }
}

// If Bank UPI is selected, process with UPI pool
if ($use_bank_upi) {
    if (isset($upiManager) && $upiManager) {
        $bank_res = executeBankUpiLogic($upiManager, $conn, $orderid, $amount, $customer_name, $token_data, $gateway_settings);
        if ($bank_res) {
            $res = $bank_res;
            // Set variables for view
            $upi_id = $res['upi_id'];
            $merchant_name = $res['merchant_name'];
            $encodedData = $res['encoded_data'];
        } else {
            // Fallback if Bank UPI selected but no UPI available? 
            // Maybe try RSPay as last resort?
            $use_bank_upi = false; 
            log_message("Bank UPI selected but returned null (no UPIs?). Trying fallback to RSPay.");
        }
    } else {
        $use_bank_upi = false;
    }
}
log_message("Finished Bank UPI Check. Use Bank UPI: " . ($use_bank_upi ? 'Yes' : 'No'));

// Check if merchant is RSPAY or fallback from Bank UPI
if (!$use_bank_upi && strtoupper($merchant_name) == 'RSPAY') {
    log_message("Processing RSPay for Order: " . $orderid);
    
    // Logic for RSPay
    $merchantOrderId = $orderid; 
    
    // Ensure amount is formatted correctly (e.g. 100.00)
    $formatted_amount = sprintf('%.2f', floatval($amount));

    $params = [
        'merchantId' => $rspay_merchant_id,
        'merchantOrderId' => $merchantOrderId,
        'amount' => $formatted_amount,
        'type' => 2, // Fixed at 2 for UPI/Pay-in
        'paymentCurrency' => 'INR',
        'notifyUrl' => $callback_url,
        'userName' => $customer_name ?: 'User', // Fallback if empty
        'redirectUrl' => $redirect_url,
        'ext' => 'test' // Adding ext as seen in other files
    ];

    // Remove empty values to ensure signature matches payload
    $params = array_filter($params, function($v) {
        return $v !== null && $v !== '';
    });

    $sign = generateRspaySign($params, $rspay_key);
    $params['sign'] = $sign;
    
    log_message("RSPay Request Params: " . json_encode($params));

    $response = callRspayApi('/apii/in/createOrder', $params);
    
    log_message("RSPay API Response: " . json_encode($response));
    
    if(isset($response['status']) && $response['status'] == '200') {
        $payUrl = $response['data']['payUrl'];
        $qr_api_url = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' . urlencode($payUrl);
        $qr_image = fetch_url_content($qr_api_url);
        $qr_image_data_uri = 'data:image/png;base64,' . base64_encode($qr_image);
        
        $clientIP = $_SERVER['REMOTE_ADDR']; 
        $timestamp = time(); 
        $combinedData = "orderid=" . $orderid . 
        "&timestamp=" . $timestamp . 
        "&user=" . $user . 
        "&ip_address=" . $clientIP;
        $encodedData = base64_encode($combinedData);

        $res = [
            "status" => "SUCCESS",
            "message" => "Token is valid.",
            "orderid" => $orderid,
            "amount" => $amount,
            "customer_name" => $customer_name,
            "txn_status" => 'PENDING',
            "merchant_name" => $merchant_name,
            "upi_id" => "N/A",
            "payment_link" => $payUrl,
            "qr_code" => $qr_image_data_uri,
            "expiration_time" => date('Y-m-d H:i:s', $token_data['expiration_time']),
            "encoded_data" => $encodedData,
            "is_hdfc" => false
        ];
        
        // COMMENTED OUT: Direct redirect shows RSPay branding
        // Instead, we show pay2inr payment page with embedded RSPay link
        // header("Location: " . $payUrl);
        // exit;
    } else {
        // RSPay Failed - Log and Attempt Fallback to Bank UPI if available
        $errorMsg = "Failed to generate RSPay order: " . ($response['message'] ?? 'Unknown');
        log_message("RSPay Error: " . $errorMsg);
        
        // Attempt Fallback logic
        log_message("Attempting Fallback to Bank UPI due to RSPay failure.");
        $use_bank_upi_fallback = true;
    }

} 

// Fallback Block (Executed if RSPay failed or was skipped)
if ((isset($use_bank_upi_fallback) && $use_bank_upi_fallback) || (!isset($res) && !$use_bank_upi && strtoupper($merchant_name) != 'HDFC')) {
    
    // Check if we can use Bank UPI (UPI Pool)
    // We reuse the logic from above but need to ensure variables are set
    if (!isset($upiManager) || !$upiManager) {
        if (file_exists('../database/UpiPoolManager.php')) {
            require_once('../database/UpiPoolManager.php');
            if (class_exists('UpiPoolManager')) {
                $upiManager = new UpiPoolManager($conn);
                // Refresh gateway settings if needed, or use defaults
                if (!isset($gateway_settings)) {
                    $gateway_settings = $upiManager->getGatewaySettings();
                }
            }
        }
    }

    if (isset($upiManager) && $upiManager) {
        $bank_res = executeBankUpiLogic($upiManager, $conn, $orderid, $amount, $customer_name, $token_data, $gateway_settings ?? []);
        
        if ($bank_res) {
            $res = $bank_res;
            // Set variables for view
            $upi_id = $res['upi_id'];
            $merchant_name = $res['merchant_name'];
            $encodedData = $res['encoded_data'];
            log_message("Fallback to Bank UPI Successful. UPI ID: " . $upi_id);
        } else {
             $res = [
                "status" => "FAILED",
                "message" => "Payment Gateway Unavailable (RSPay failed and No Bank UPI available)",
                "expiration_time" => date('Y-m-d H:i:s', $token_data['expiration_time'])
            ];
            log_message("Fallback failed: No UPIs available.");
        }
    } else {
        // UpiPoolManager not available
        $res = [
            "status" => "FAILED",
            "message" => "Payment System Error: UPI Manager Not Available",
             "expiration_time" => date('Y-m-d H:i:s', $token_data['expiration_time'])
        ];
    }
} elseif (strtoupper($merchant_name) == 'HDFC') {
// Fetch terminal_id and session_id from add_merchant table
$merchant_query = $conn->prepare("SELECT terminal_id, session_id FROM add_merchant WHERE user = ? AND UPPER(merchant_name) = 'HDFC' ORDER BY id DESC LIMIT 1");
$merchant_query->bindParam(1, $user, PDO::PARAM_STR);
$merchant_query->execute();
$merchant_data = $merchant_query->fetch();

if ($merchant_data) {
$terminalId = $merchant_data['terminal_id'];
$sessionid = $merchant_data['session_id'];
$appTxnid = time() . mt_rand(1000000000, 9999999999);

$amount = $token_data['amount'];
$amount_integer = (int)round(floatval($amount)); // Convert "1.00" to 1


// Make API call to HDFC QR code generator
$hdfc_api_url = "https://smartupi.in.net/merchantapi/HDFCSoft/hdfc_qr.php?terminalId=$terminalId&amount=$amount_integer&description=$orderid&customerMobileNumber=$user&appTxnid=$appTxnid&sessionid=$sessionid";

$hdfc_response = fetch_url_content($hdfc_api_url);
//echo $hdfc_api_url;
$hdfc_data = json_decode($hdfc_response, true);

if ($hdfc_data && isset($hdfc_data['status']) && $hdfc_data['status'] == 'success') {
$hdfcqr_image_data_uri = $hdfc_data['qr_code'];

$clientIP = $_SERVER['REMOTE_ADDR']; 
$timestamp = time(); 
$combinedData = "orderid=" . $orderid . 
"&timestamp=" . $timestamp . 
"&user=" . $user . 
"&ip_address=" . $clientIP;
$encodedData = base64_encode($combinedData);

$res = [
"status" => "SUCCESS",
"message" => "Token is valid.",
"orderid" => $orderid,
"amount" => $amount,
"customer_name" => $customer_name,
"txn_status" => 'PENDING',
"merchant_name" => $merchant_name,
"upi_id" => $upi_id,
"qr_code" => $hdfcqr_image_data_uri,
"expiration_time" => date('Y-m-d H:i:s', $token_data['expiration_time']),
"encoded_data" => $encodedData,
"is_hdfc" => true
];
} else {
$res = [
"status" => "FAILED",
"message" => "Failed to generate HDFC QR code."
];
}
} else {
$res = [
"status" => "FAILED",
"message" => "No HDFC merchant configuration found for this user."
];
}
} elseif (!isset($res)) {
    
                            // For non-HDFC merchants, proceed with normal QR code generation
                            
                            $transaction_ref_no = 'REF' . rand(100000, 999999); 
                            $transaction_note = "Bill Payment";
                            
                            // Fix: Handle null values for urlencode
                            $upi_url = 'upi://pay?pa=' . urlencode($upi_id ?? '') . 
                                       '&pn=' . urlencode($customer_name ?? '') . 
                                       '&am=' . urlencode($amount ?? '') . 
                                       '&tid=' . urlencode($orderid ?? '') . 
                                       '&tr=' . urlencode($orderid ?? '') . 
                                       '&tn=' . urlencode($transaction_note ?? '') . 
                                       '&cu=INR';
                            
                            $upi_url_encoded = urlencode($upi_url);
                            $qr_api_url = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' . $upi_url_encoded;
                            $qr_image = fetch_url_content($qr_api_url);
                            
                            if ($qr_image !== false) {
                                $qr_image_base64 = base64_encode($qr_image);
                                $qr_image_data_uri = 'data:image/png;base64,' . $qr_image_base64;
                                
                                $clientIP = $_SERVER['REMOTE_ADDR']; 
                                $timestamp = time(); 
                                $combinedData = "orderid=" . ($orderid ?? '') . 
                                                "&timestamp=" . $timestamp . 
                                                "&user=" . ($user ?? '') . 
                                                "&ip_address=" . $clientIP;
                                $encodedData = base64_encode($combinedData);
                                
                                $res = [
                                    "status" => "SUCCESS",
                                    "message" => "Token is valid.",
                                    "orderid" => $orderid,
                                    "amount" => $amount,
                                    "customer_name" => $customer_name,
                                    "txn_status" => 'PENDING',
                                    "merchant_name" => $merchant_name,
                                    "upi_id" => $upi_id,
                                    "payment_link" => $upi_url,
                                    "qr_code" => $qr_image_data_uri,
                                    "expiration_time" => date('Y-m-d H:i:s', $token_data['expiration_time']),
                                    "encoded_data" => $encodedData,
                                    "is_hdfc" => false
                                ];
                            } else {
                                $res = [
                                    "status" => "FAILED",
                                    "message" => "Failed to generate QR code."
                                ];
                            }
                        }
                    }
                } else {
                    $res = [
                        "status" => "FAILED",
                        "message" => "Invalid Token"
                    ];
                }
            } else {
                $res = [
                    "status" => "FAILED",
                    "message" => "Missing or Invalid Token"
                ];
            }

            // Fetch checkout page data if needed
            // FIX: Table checkout_page does not exist, using defaults
            /*
            $sql = "SELECT * FROM `checkout_page` WHERE `user` = :user";
            $stmt = $conn->prepare($sql);
            $stmt->bindParam(":user", $user);
            $stmt->execute();
            $checkout = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$checkout) {
                $checkout = [];
            }
            */
            $checkout = [];

            // Ensure defaults to prevent warnings/errors
            $checkout_defaults = [
                'brand_name' => '',
                'paytm_button' => 'off', 
                'gpay_button' => 'off'
            ];
            $checkout = array_merge($checkout_defaults, $checkout);

// Output the response in JSON format
// header('Content-Type: application/json');
// echo json_encode($res);

// REDIRECT LOGIC: If Gateway is RSPay, redirect immediately
if (isset($res) && $res['status'] == 'SUCCESS' && isset($merchant_name) && strtoupper($merchant_name) == 'RSPAY') {
    // Double check we are NOT in Bank UPI mode
    if (isset($use_bank_upi) && $use_bank_upi === true) {
        log_message("Redirect skipped: Bank UPI mode is active.");
    } else {
        if (!empty($res['payment_link'])) {
            log_message("Redirecting to RSPay Link: " . $res['payment_link']);
            header("Location: " . $res['payment_link']);
            exit;
        }
    }
} else {
    log_message("Redirect checks failed. Merchant: " . ($merchant_name ?? 'N/A'));
}
?>



<?php 
log_message("Starting View Logic...");
// ini_set('display_errors', 1); // Commenting out to avoid interference if headers already sent
ob_start(); // Buffer output to prevent premature sending if that's the issue, or to catch it.


if (isset($res['status']) && $res['status'] == 'SUCCESS') {
    log_message("Status is SUCCESS. Preparing view variables.");
    
    // Ensure variables are defined to avoid warnings/errors
    $safe_upi_id = $upi_id ?? '';
    $safe_merchant_name = $merchant_name ?? '';
    $safe_orderid = $orderid ?? '';
    $safe_amount = $amount ?? '0';

    if (strtoupper($safe_merchant_name) == 'RSPAY') {
        $link = $res['payment_link'] ?? '#';
        $paytmintent = $link;
        $bhim = $link;
        $gpay = $link;
        $orders = $link;
    } else {
        // Use single quotes or complex curly syntax to be safe
        // And URL encode parameters properly
        log_message("Building UPI Intents for: " . $safe_upi_id);
        
        $paytmintent = "paytmmp://cash_wallet?pa={$safe_upi_id}&pn={$safe_merchant_name}&mc=3526&tid={$safe_orderid}&tr={$safe_orderid}&am={$safe_amount}&cu=INR&tn={$safe_orderid}&url=&mode=02&purpose=00";
        $bhim = "upi://pay?pa={$safe_upi_id}&pn={$safe_merchant_name}&mc=3526&tid={$safe_orderid}&tr={$safe_orderid}&am={$safe_amount}&cu=INR&tn={$safe_orderid}&url=&mode=02&purpose=00";
        $gpay= "upi://pay?pa={$safe_upi_id}&pn={$safe_merchant_name}&mc=02&tr={$safe_orderid}&tid={$safe_orderid}&tn={$safe_orderid}&am={$safe_amount}&cu=INR";
        $orders = "gpay://upi/pay?pa={$safe_upi_id}&am={$safe_amount}&pn={$safe_merchant_name}&tn={$safe_orderid}&tid={$safe_orderid}&tr={$safe_orderid}"; 
    }
    log_message("View Variables Prepared.");

} else {
    $paytmintent = '#';
    $bhim = '#';
    $gpay = '#';
    $orders = '#';
    log_message("Status is NOT SUCCESS or RES not set.");
}
?>

<?php
log_message("Outputting HTML...");
ob_end_flush(); // Send buffer
?>
<?php
// Build UPI intent URLs for each app
$phonepe_intent = '#';
$gpay_intent = '#';
$paytm_intent_url = '#';
$generic_upi = '#';

if (isset($res) && $res['status'] == 'SUCCESS') {
    $s_upi = $safe_upi_id ?? '';
    $s_name = urlencode($safe_merchant_name ?? 'Merchant');
    $s_amt = $safe_amount ?? '0';
    $s_oid = $safe_orderid ?? '';
    
    if (strtoupper($safe_merchant_name ?? '') == 'RSPAY' && !empty($res['payment_link'])) {
        $phonepe_intent = $res['payment_link'];
        $gpay_intent = $res['payment_link'];
        $paytm_intent_url = $res['payment_link'];
        $generic_upi = $res['payment_link'];
    } else {
        $generic_upi = "upi://pay?pa={$s_upi}&pn={$s_name}&am={$s_amt}&tr={$s_oid}&tid={$s_oid}&tn=Payment+for+{$s_oid}&cu=INR";
        $phonepe_intent = "phonepe://pay?pa={$s_upi}&pn={$s_name}&am={$s_amt}&tr={$s_oid}&tid={$s_oid}&tn=Payment+for+{$s_oid}&cu=INR";
        $gpay_intent = "tez://upi/pay?pa={$s_upi}&pn={$s_name}&am={$s_amt}&tr={$s_oid}&tid={$s_oid}&tn=Payment+for+{$s_oid}&cu=INR";
        $paytm_intent_url = "paytmmp://pay?pa={$s_upi}&pn={$s_name}&am={$s_amt}&tr={$s_oid}&tid={$s_oid}&tn=Payment+for+{$s_oid}&cu=INR";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>UPI Payment</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', sans-serif; }
        body { background: #f0f2f5; display: flex; justify-content: center; min-height: 100vh; }
        .container { width: 100%; max-width: 440px; background: #fff; min-height: 100vh; }

        /* Header */
        .pay-header {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            padding: 20px;
            text-align: center;
            color: #fff;
            position: relative;
        }
        .pay-header .brand { font-size: 13px; opacity: 0.8; margin-bottom: 4px; letter-spacing: 1px; }
        .pay-header .order-id { font-size: 11px; opacity: 0.6; margin-bottom: 10px; font-family: monospace; }
        .pay-header .amount { font-size: 36px; font-weight: 800; }
        .pay-header .amount span { font-size: 20px; font-weight: 600; }
        .timer-badge {
            display: inline-flex; align-items: center; gap: 6px;
            background: rgba(255,255,255,0.15); padding: 4px 14px;
            border-radius: 20px; font-size: 12px; font-weight: 600; margin-top: 10px;
        }
        .timer-badge .dot { width: 6px; height: 6px; border-radius: 50%; background: #4ade80; animation: blink 1s infinite; }
        @keyframes blink { 0%,100% { opacity: 1; } 50% { opacity: 0.3; } }

        .content { padding: 20px; }

        /* QR Section */
        .qr-section { text-align: center; margin-bottom: 20px; }
        .qr-label { font-size: 13px; color: #64748b; margin-bottom: 12px; font-weight: 500; }
        .qr-wrap {
            display: inline-block; padding: 12px; border: 2px solid #e2e8f0;
            border-radius: 16px; background: #fff; margin-bottom: 12px;
        }
        .qr-actions { display: flex; justify-content: center; gap: 8px; }
        .qr-action-btn {
            padding: 8px 18px; border: 1px solid #e2e8f0; background: #fff;
            border-radius: 8px; font-size: 12px; color: #64748b; cursor: pointer;
            font-weight: 500; text-decoration: none; transition: all 0.2s;
        }
        .qr-action-btn:hover { border-color: #4f46e5; color: #4f46e5; }

        /* App Buttons */
        .app-section { margin-bottom: 20px; }
        .app-section-title { font-size: 12px; font-weight: 600; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.8px; margin-bottom: 10px; }
        .app-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; }
        .app-btn {
            display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px;
            padding: 12px 10px; border: 1px solid #e2e8f0; border-radius: 14px;
            background: #fff; text-decoration: none; color: #1e293b; height: 60px;
            transition: all 0.25s; cursor: pointer;
        }
        .app-btn:hover, .app-btn:active { border-color: #4f46e5; background: #f5f3ff; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(79,70,229,0.1); }
        .app-btn img { max-width: 100%; height: 28px; object-fit: contain; }

        /* UPI Copy */
        .upi-copy-section { margin-bottom: 20px; }
        .copy-label { font-size: 12px; font-weight: 600; color: #64748b; margin-bottom: 6px; display: block; }
        .copy-row {
            display: flex; gap: 8px;
        }
        .copy-row input {
            flex: 1; padding: 10px 14px; border: 1px solid #e2e8f0; border-radius: 10px;
            font-size: 13px; color: #334155; background: #f8fafc; outline: none;
            font-family: monospace;
        }
        .copy-row input:focus { border-color: #4f46e5; }
        .copy-row button {
            padding: 10px 18px; background: #4f46e5; color: #fff; border: none;
            border-radius: 10px; font-size: 13px; font-weight: 600; cursor: pointer;
            transition: background 0.2s;
        }
        .copy-row button:hover { background: #4338ca; }

        /* Divider */
        .or-divider {
            display: flex; align-items: center; gap: 12px; margin: 20px 0;
            color: #cbd5e1; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px;
        }
        .or-divider::before, .or-divider::after { content: ''; flex: 1; height: 1px; background: #e2e8f0; }

        /* UTR Section */
        .utr-section { margin-top: 16px; }
        .utr-label { font-size: 13px; font-weight: 600; color: #1e293b; margin-bottom: 4px; }
        .utr-sublabel { font-size: 11px; color: #ef4444; margin-bottom: 10px; display: block; }
        .utr-input {
            width: 100%; padding: 14px; border: 1px solid #e2e8f0; border-radius: 12px;
            text-align: center; font-size: 16px; font-family: monospace; letter-spacing: 2px;
            outline: none; background: #f8fafc; margin-bottom: 12px; transition: border 0.2s;
        }
        .utr-input:focus { border-color: #4f46e5; box-shadow: 0 0 0 3px rgba(79,70,229,0.08); }
        .submit-btn {
            width: 100%; padding: 14px; background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: #fff; border: none; border-radius: 12px; font-size: 15px; font-weight: 700;
            cursor: pointer; transition: all 0.25s; box-shadow: 0 4px 12px rgba(79,70,229,0.25);
        }
        .submit-btn:hover { transform: translateY(-1px); box-shadow: 0 6px 20px rgba(79,70,229,0.3); }

        /* Instructions */
        .notice-box {
            margin-top: 20px; padding: 14px; background: #fffbeb; border: 1px solid #fef3c7;
            border-radius: 12px; font-size: 11px; color: #92400e; line-height: 1.6;
        }
        .notice-box strong { font-size: 12px; display: block; margin-bottom: 4px; }

        /* Expired overlay */
        .expired-overlay {
            position: fixed; inset: 0; background: rgba(255,255,255,0.97);
            display: none; flex-direction: column; justify-content: center; align-items: center; z-index: 100;
        }
        .expired-overlay h2 { color: #ef4444; margin-bottom: 8px; }
        .expired-overlay p { color: #64748b; }

        /* Error state */
        .error-page { text-align: center; padding: 60px 20px; }
        .error-page h3 { color: #ef4444; margin-bottom: 10px; }
        .error-page button { padding: 10px 24px; border: none; background: #4f46e5; color: #fff; border-radius: 10px; cursor: pointer; font-weight: 600; }
    </style>
</head>
<body>

<?php if (isset($res) && isset($res['status']) && $res['status'] == 'SUCCESS'): ?>
    <div class="container">
        <!-- Header -->
        <div class="pay-header">
            <div class="brand">UPI PAYMENT</div>
            <div class="order-id"><?php echo htmlspecialchars($safe_orderid); ?></div>
            <div class="amount"><span>₹</span><?php echo number_format((float)$safe_amount, 2); ?></div>
            <div class="timer-badge"><span class="dot"></span> <span id="timerDisplay">--:--</span></div>
        </div>

        <div class="content">
            <!-- QR Code -->
            <div class="qr-section">
                <div class="qr-label">Scan QR code to pay</div>
                <div class="qr-wrap">
                    <div id="qrcode" style="width:180px;height:180px;"></div>
                </div>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
                <script>
                    window.addEventListener('load', function() {
                        new QRCode(document.getElementById("qrcode"), {
                            text: "<?php echo $res['payment_link'] ?? $generic_upi; ?>",
                            width: 180, height: 180,
                            colorDark: "#1e293b", colorLight: "#ffffff",
                            correctLevel: QRCode.CorrectLevel.H
                        });
                    });
                </script>
                <div class="qr-actions">
                    <a href="#" onclick="downloadQR(this)" class="qr-action-btn"><i class="fas fa-download" style="margin-right:4px;"></i> Save QR</a>
                    <a href="javascript:location.reload()" class="qr-action-btn"><i class="fas fa-redo" style="margin-right:4px;"></i> Refresh</a>
                </div>
            </div>

            <div class="or-divider">or pay using app</div>

            <!-- App Buttons -->
            <div class="app-section">
                <div class="app-grid">
                    <a href="<?php echo $phonepe_intent; ?>" class="app-btn" id="btnPhonePe">
                        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/71/PhonePe_Logo.svg/512px-PhonePe_Logo.svg.png" style="height:32px; width:auto;" alt="PhonePe">
                    </a>
                    <a href="<?php echo $gpay_intent; ?>" class="app-btn" id="btnGPay">
                        <img src="https://fastpay.us.cc/google-pay-gpay-logo-11530962961mwws81tde9.png" style="height:32px; width:auto;" alt="GPay">
                    </a>
                    <a href="<?php echo $paytm_intent_url; ?>" class="app-btn" id="btnPaytm">
                        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Paytm_Logo_%28standalone%29.svg/512px-Paytm_Logo_%28standalone%29.svg.png" style="height:24px; margin-top:4px; width:auto;" alt="Paytm">
                    </a>
                </div>
            </div>

            <!-- UPI Copy -->
            <div class="upi-copy-section">
                <label class="copy-label">Or copy UPI ID manually</label>
                <div class="copy-row">
                    <input type="text" id="upiId" value="<?php echo htmlspecialchars($upi_id ?? ''); ?>" readonly>
                    <button onclick="copyUpiId()"><i class="fas fa-copy"></i> Copy</button>
                </div>
            </div>

            <div class="or-divider">after payment</div>

            <!-- UTR Section -->
            <div class="utr-section">
                <div class="utr-label">Enter UTR / Reference Number</div>
                <div class="utr-sublabel">Submit the 12-digit UTR after completing payment</div>
                <form onsubmit="event.preventDefault(); submitPayment();">
                    <input type="text" class="utr-input" id="utr_number" placeholder="Enter 12-digit UTR" maxlength="12" required>
                    <input type="hidden" id="encodedData" value="<?php echo isset($encodedData) ? $encodedData : ''; ?>">
                    <button type="submit" class="submit-btn"><i class="fas fa-check-circle" style="margin-right:6px;"></i> Submit Ref Number</button>
                </form>
            </div>

            <!-- Notice -->
            <div class="notice-box">
                <strong><i class="fas fa-info-circle"></i> Important Notice</strong>
                1. Tap any app button above to pay directly from your UPI app.<br>
                2. After payment, enter the 12-digit UTR number and submit.<br>
                3. Please avoid making duplicate payments.<br>
                4. If amount not credited, submit UTR to recover your funds.
            </div>
        </div>
    </div>

    <div id="expiredOverlay" class="expired-overlay">
        <h2>⏰ Order Expired</h2>
        <p>Please initiate a new payment.</p>
    </div>

<?php else: ?>
    <div class="error-page">
        <h3>❌ Payment Failed</h3>
        <p style="color:#64748b; margin-bottom:16px;"><?php echo htmlspecialchars($res['message'] ?? 'Unknown Error'); ?></p>
        <button onclick="history.back()">Go Back</button>
    </div>
<?php endif; ?>

<script>
// === Timer ===
var expTime = "<?php echo htmlspecialchars($res['expiration_time'] ?? ''); ?>";
if(expTime) {
    var expTs = Date.parse(expTime) / 1000;
    if(!isNaN(expTs)) {
        function tick() {
            var rem = expTs - Math.floor(Date.now()/1000);
            var el = document.getElementById('timerDisplay');
            if(!el) return;
            if(rem <= 0) { el.textContent = 'Expired'; document.getElementById('expiredOverlay').style.display='flex'; clearInterval(ti); }
            else { var m = Math.floor(rem/60), s = rem%60; el.textContent = String(m).padStart(2,'0')+':'+String(s).padStart(2,'0'); }
        }
        tick(); var ti = setInterval(tick, 1000);
    }
}

// === Download QR ===
function downloadQR(el) {
    var q = document.getElementById("qrcode");
    var img = q.querySelector("img"), canvas = q.querySelector("canvas");
    if(img && img.src) { el.href=img.src; el.download="payment_qr.png"; }
    else if(canvas) { el.href=canvas.toDataURL("image/png"); el.download="payment_qr.png"; }
}

// === Copy UPI ===
function copyUpiId() {
    var v = document.getElementById("upiId").value;
    navigator.clipboard.writeText(v).then(function(){ Swal.fire({icon:'success',title:'Copied!',toast:true,position:'top-end',showConfirmButton:false,timer:1200}); });
}

// === Polling ===
var encodedData = "<?php echo isset($encodedData) ? addslashes($encodedData) : ''; ?>";
var redirectUrl = "<?php echo isset($redirect_url) ? $redirect_url : ''; ?>";
var orderid = "<?php echo isset($orderid) ? $orderid : ''; ?>";
var merchantName = "<?php echo isset($merchant_name) ? addslashes($merchant_name) : ''; ?>";

function getApiUrl(mn) {
    if(!mn) return 'payment-status/paytm-status-txid.php';
    var m = mn.toLowerCase();
    if(m.includes('paytm')) return 'payment-status/paytm-status-txid.php';
    if(m.includes('hdfc')) return 'payment-status/hdfc-status-txid.php';
    return 'payment-status/paytm-status-txid.php';
}

function submitRedirectForm() {
    var f = document.createElement('form'); f.method='POST'; f.action=redirectUrl;
    var i = document.createElement('input'); i.type='hidden'; i.name='order_id'; i.value=orderid;
    f.appendChild(i); document.body.appendChild(f); f.submit();
}

function checkOrderStatus() {
    if(!encodedData) return;
    var gt = "<?php echo $res['gateway'] ?? 'rspay'; ?>";
    var url = getApiUrl(merchantName);
    if(gt === 'bank_upi') url = 'payment-status/generic-status.php';
    setInterval(function(){
        fetch(url, {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:"data="+encodedData})
        .then(function(r){return r.json();}).then(function(d){
            if(d.status_code===200 && d.status==='Success') {
                Swal.fire({icon:'success',title:'Payment Successful',timer:1500,showConfirmButton:false}).then(function(){ submitRedirectForm(); });
            }
        }).catch(function(){});
    }, 4000);
}

function submitPayment() {
    var utr = document.getElementById('utr_number').value;
    if(!utr || utr.length < 12) { Swal.fire('Error','Please enter valid 12-digit UTR','error'); return; }
    var fd = new FormData(); fd.append('utr_number',utr); fd.append('data',encodedData);
    var gt = "<?php echo isset($res['gateway']) ? $res['gateway'] : 'rspay'; ?>";
    var sUrl = gt==='bank_upi' ? 'payment-status/bank-upi-submit.php' : 'payment-status/amazon-status.php';
    fetch(sUrl,{method:'POST',body:fd}).then(function(r){return r.json();}).then(function(d){
        if(d.status==='Success') { Swal.fire({icon:'success',title:'Submitted',text:'Please wait for verification...',timer:2000,showConfirmButton:false}).then(function(){ submitRedirectForm(); }); }
        else { Swal.fire('Info', d.message || 'Payment Pending Verification','info'); }
    }).catch(function(){ Swal.fire('Error','Submission failed','error'); });
}

// App button fallback - if app not installed, fall back to generic UPI intent
document.querySelectorAll('.app-btn').forEach(function(btn){
    btn.addEventListener('click', function(e){
        var href = this.getAttribute('href');
        if(href === '#') { e.preventDefault(); Swal.fire('Info','Payment link not available','info'); return; }
        // Try opening the app, fallback to generic UPI after delay
        var genericUrl = "<?php echo $generic_upi; ?>";
        setTimeout(function(){ window.location.href = genericUrl; }, 1500);
    });
});

checkOrderStatus();
</script>
</body>
</html>
