<?php
date_default_timezone_set("Asia/Kolkata");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

// Define the base directory constant
define('ROOT_DIR', realpath(dirname(__FILE__)) . '/../');

// Securely include files using the ROOT_DIR constant
include ROOT_DIR . 'pages/dbFunctions.php';
include ROOT_DIR . 'pages/dbInfo.php';

$link_token = sanitizeInput($_GET["token"]);

// Fetch order_id based on the token from the payment_links table
$sql_fetch_order_id = "SELECT order_id, created_at FROM payment_links WHERE link_token = '$link_token'";
$result = getXbyY($sql_fetch_order_id);

if (count($result) === 0) {
    // Token not found or expired
    echo "Token not found or expired";
    exit;
}

$order_id = $result[0]['order_id'];
$created_at = strtotime($result[0]['created_at']);
$current_time = time();

// Check if the token has expired (more than 5 minutes)
if (($current_time - $created_at) > (5 * 60)) {
    // Mark the underlying order as FAILURE instead of leaving it PENDING forever
    $safe_order_id = addslashes($order_id);
    setXbyY("UPDATE orders SET status='FAILURE' WHERE order_id='$safe_order_id'");
    include ROOT_DIR . 'includes/expired_page.php';
    exit;
}

$slq_p = "SELECT * FROM orders where order_id='$order_id'";
$res_p = getXbyY($slq_p);
$isTestOrder = !empty($res_p[0]['is_test']);
$amount = $res_p[0]['amount'];
$user_token = $res_p[0]['user_token'];
$redirect_url = $res_p[0]['redirect_url'];
$cxrkalwaremark = $res_p[0]['byteTransactionId'];  //remark
$cxrbytectxnref = $res_p[0]['paytm_txn_ref'];

if ($redirect_url == '') {
    $redirect_url = 'https://' . $_SERVER["SERVER_NAME"] . '/';
}

// Append a status flag to the redirect URL so the destination page can tell
// success apart from a failed/cancelled payment, instead of always showing "success".
function withPaymentStatus($url, $status) {
    // Don't blindly append - if the merchant's own redirect_url already has
    // payment_status / order_id in it (common when they build it dynamically
    // on their side), appending again produced duplicated params like
    // "...&order_id=X&order_id=X" in the final redirect.
    $parts = parse_url($url);
    parse_str($parts['query'] ?? '', $query);
    $query['payment_status'] = $status;
    $query['order_id'] = $GLOBALS['order_id'];
    $newQuery = http_build_query($query);

    $rebuilt = '';
    if (!empty($parts['scheme'])) $rebuilt .= $parts['scheme'] . '://';
    if (!empty($parts['host'])) $rebuilt .= $parts['host'];
    if (!empty($parts['port'])) $rebuilt .= ':' . $parts['port'];
    $rebuilt .= $parts['path'] ?? '';
    if ($newQuery !== '') $rebuilt .= '?' . $newQuery;
    if (!empty($parts['fragment'])) $rebuilt .= '#' . $parts['fragment'];

    return $rebuilt;
}
$redirect_url_success = withPaymentStatus($redirect_url, 'success');
$redirect_url_failed  = withPaymentStatus($redirect_url, 'failed');

// Fetch UPI ID
$slq_p = "SELECT * FROM fampay_tokens where user_token='$user_token'";
$res_p = getXbyY($slq_p);
$upi_id = $res_p[0]['upi_id']; // UPI ID from FamPay tokens

// Fetch user information
$slq_p = "SELECT * FROM users where user_token='$user_token'";
$res_p = getXbyY($slq_p);
$unitId = $res_p[0]['name'];

// Checkout page customization (logo / brand color / display name)
$checkoutDisplayName = !empty($res_p[0]['checkout_business_name']) ? $res_p[0]['checkout_business_name'] : $unitId;

function cxr_valid_hex($val, $default) {
    return (!empty($val) && preg_match('/^#[0-9A-Fa-f]{6}$/', $val)) ? $val : $default;
}
$checkoutPrimaryColor = cxr_valid_hex($res_p[0]['checkout_primary_color'] ?? null, '#0F6B5C');
$checkoutSecondaryColor = cxr_valid_hex($res_p[0]['checkout_secondary_color'] ?? null, '#E8A33D');
$checkoutSuccessColor = cxr_valid_hex($res_p[0]['checkout_success_color'] ?? null, '#1FAA59');
$checkoutBgColor = cxr_valid_hex($res_p[0]['checkout_bg_color'] ?? null, '#EAF3F0');
$checkoutCardBgColor = cxr_valid_hex($res_p[0]['checkout_card_bg_color'] ?? null, '#F4F6F5');
$checkoutTextColor = cxr_valid_hex($res_p[0]['checkout_text_color'] ?? null, '#0B1F1C');

$checkoutLogoUrl = !empty($res_p[0]['checkout_logo_url']) ? $res_p[0]['checkout_logo_url'] : null;
$checkoutShowQr = isset($res_p[0]['checkout_show_qr']) ? (bool)$res_p[0]['checkout_show_qr'] : true;
$checkoutShowGpay = isset($res_p[0]['checkout_show_googlepay']) ? (bool)$res_p[0]['checkout_show_googlepay'] : true;
$checkoutShowPhonepe = isset($res_p[0]['checkout_show_phonepe']) ? (bool)$res_p[0]['checkout_show_phonepe'] : true;
$checkoutShowOtherUpi = isset($res_p[0]['checkout_show_other_upi']) ? (bool)$res_p[0]['checkout_show_other_upi'] : true;
// Safety net: if somehow everything got turned off, force the QR back on
// so the customer always has a way to pay.
if (!$checkoutShowQr && !$checkoutShowGpay && !$checkoutShowPhonepe && !$checkoutShowOtherUpi) {
    $checkoutShowQr = true;
}

// Derive a slightly darker shade of the brand color for hover/gradient states
function cxr_darken_hex($hex, $percent = 0.18) {
    $hex = ltrim($hex, '#');
    if (strlen($hex) !== 6) return '#0A4F44';
    $r = max(0, (int)round(hexdec(substr($hex, 0, 2)) * (1 - $percent)));
    $g = max(0, (int)round(hexdec(substr($hex, 2, 2)) * (1 - $percent)));
    $b = max(0, (int)round(hexdec(substr($hex, 4, 2)) * (1 - $percent)));
    return sprintf('#%02X%02X%02X', $r, $g, $b);
}
$checkoutPrimaryColorDark = cxr_darken_hex($checkoutPrimaryColor);

// Generate a unique transaction remark
$asdasd23 = "TXN" . rand(111, 999) . time() . rand(1, 100);

$orders = "upi://pay?pa=$upi_id&am=$amount&pn=$unitId&tn=$asdasd23&tr=$cxrbytectxnref";

// GoQR API URL generate karna
$qrCodeUrl = "https://api.qrserver.com/v1/create-qr-code/?data=" . urlencode($orders) . "&size=300x300&ecc=M";

// Generate UPI links for PhonePe and Google Pay
$phonepe_link   = "phonepe://pay?pa=$upi_id&am=$amount&pn=$unitId&tn=$asdasd23&tr=$cxrbytectxnref";
$googlepay_link = "tez://upi/pay?pa=$upi_id&am=$amount&pn=$unitId&tn=$asdasd23&tr=$cxrbytectxnref";

// Real remaining time (server-side truth) instead of always resetting to 5:00
$expirySeconds = max(0, (5 * 60) - ($current_time - $created_at));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Checkout...</title>
<link rel="icon" href="https://panel.mgamer.online/assets/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="https://panel.mgamer.online/assets/favicon-192x192.png" sizes="192x192" type="image/png">
<link rel="apple-touch-icon" href="https://panel.mgamer.online/assets/favicon-192x192.png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@500;600;700;800&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://panel.mgamer.online/assets/brite-dialog.css">
<style>
:root {
<?php
$cxr_success_dark = cxr_darken_hex($checkoutSuccessColor, 0.4);
$cxr_error_color  = '#D64545'; // failed/error stays a fixed, universally-understood red
?>
            --zap-c1:<?php echo $checkoutPrimaryColor; ?>;
        --zap-c2:<?php echo $checkoutPrimaryColorDark; ?>;
        --zap-c3:<?php echo $checkoutSecondaryColor; ?>;
        --zap-c4:<?php echo $checkoutBgColor; ?>;
        --zap-c5:<?php echo $checkoutTextColor; ?>;
        --zap-c6:<?php echo $checkoutTextColor; ?>;
        --zap-c7:<?php echo $checkoutBgColor; ?>;
        --zap-c8:<?php echo $checkoutPrimaryColor; ?>;
        --primary:<?php echo $checkoutPrimaryColor; ?>;
        --primary-light:<?php echo $checkoutSecondaryColor; ?>;
        --primary: var(--zap-c8, <?php echo $checkoutPrimaryColor; ?>);
    --primary-light: var(--zap-c8, <?php echo $checkoutSecondaryColor; ?>);
    --success: <?php echo $checkoutSuccessColor; ?>;
    --error: <?php echo $cxr_error_color; ?>;
    --warning: #C9971F;
    --dark-bg: #0B1512;
    --light-bg: <?php echo $checkoutBgColor; ?>;
    --card-dark: #12211D;
    --card-light: #ffffff;
    --text-dark: <?php echo $checkoutTextColor; ?>;
    --text-light: #EAF3F0;
    --shadow: 0 8px 30px rgba(11,21,18,0.08);
    --transition: all 0.25s cubic-bezier(0.22, 1, 0.36, 1);
}

html {
    box-sizing: border-box;
}

body {
    margin: 0;
    padding: 0;
    background: var(--light-bg);
    color: var(--text-dark);
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    font-family: 'Inter', system-ui, -apple-system, sans-serif;
    transition: var(--transition);
}

body.dark-mode {
    background: var(--dark-bg);
    color: var(--text-light);
}

.container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0;
    width: 100%;
}

/* PAGE LOADER */
.page-loader {
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: var(--np-card-bg, #F4F6F5);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    transition: opacity 0.45s cubic-bezier(0.22, 1, 0.36, 1);
}
.page-loader.hidden { opacity: 0; pointer-events: none; }
.mini-coin {
    width: 54px; height: 54px;
    border-radius: 50%;
    margin-bottom: 18px;
    background: #ffffff;
    border: 2px solid rgba(15,107,88,0.14);
    box-shadow: 0 8px 22px rgba(11,21,18,0.07);
    display: flex; align-items: center; justify-content: center;
    position: relative;
}
.mini-coin::before {
    content: '';
    position: absolute; top: -3px; left: -3px; right: -3px; bottom: -3px;
    border-radius: 50%;
    border: 2.5px solid transparent;
    border-top-color: var(--np-primary, #0F6B58);
    border-right-color: var(--np-primary, #0F6B58);
    animation: loaderSpin 0.85s linear infinite;
}
.mini-coin::after {
    content: '₹';
    font-size: 20px;
    font-weight: 700;
    font-family: 'Sora', 'Inter', sans-serif;
    color: var(--np-primary, #0F6B58);
}
@keyframes loaderSpin { 100% { transform: rotate(360deg); } }
.loader-text { font-size: 0.92rem; font-weight: 500; letter-spacing: 0.2px; color: var(--np-primary, #0F6B58); }


/* ===== STATUS BADGE RESULT SHEET ===== */
.coin-sheet {
    position: fixed;
    left: 50%;
    bottom: 0;
    width: 100%;
    max-width: 420px;
    transform: translate(-50%, 115%);
    background: rgba(255, 255, 255, 0.98);
    border-radius: 28px 28px 0 0;
    box-shadow: 0 -12px 60px rgba(11,21,18,0.14), 0 0 0 1px rgba(255,255,255,0.5);
    z-index: 1500;
    padding: 28px 22px 30px;
    box-sizing: border-box;
    overflow: hidden;
    transition: transform 0.5s cubic-bezier(0.22, 1, 0.36, 1);
    max-height: 88vh;
    overflow-y: auto;
}
.coin-sheet.open { transform: translate(-50%, 0%); }
.coin-sheet .handle {
    width: 42px; height: 5px; border-radius: 20px;
    background: rgba(0,0,0,0.08); margin: 0 auto 20px;
}
.coin-sheet .stage {
    width: 148px; height: 148px;
    margin: 4px auto 10px;
    display: flex; align-items: center; justify-content: center;
    position: relative;
}
.coin-sheet .coin-wrapper {
    width: 108px; height: 108px;
    position: relative;
    transition: transform 0.55s cubic-bezier(0.34,1.56,0.64,1);
}
.coin-sheet .coin { width: 100%; height: 100%; position: relative; }
.coin-sheet .coin-face {
    position: absolute; inset: 0; border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    background: #ffffff;
    border: 2px solid rgba(15,107,88,0.14);
    box-shadow: 0 10px 28px rgba(11,21,18,0.07);
    transition: background 0.45s cubic-bezier(0.22,1,0.36,1), border-color 0.45s ease, box-shadow 0.45s ease;
}
.coin-sheet .coin-front .rupee {
    font-size: 36px; font-weight: 700; font-family: 'Sora', 'Inter', sans-serif; color: var(--np-primary, #0F6B58);
    letter-spacing: -1px;
    transition: opacity 0.3s cubic-bezier(0.22,1,0.36,1), transform 0.3s cubic-bezier(0.22,1,0.36,1), color 0.3s ease;
}
.coin-sheet .coin-edge,
.coin-sheet .rim-highlight,
.coin-sheet .gloss { display: none; }
.coin-sheet .progress-ring {
    position: absolute; top: -7px; left: -7px; width: calc(100% + 14px); height: calc(100% + 14px);
    transform: rotate(-90deg); pointer-events: none; z-index: 2;
}
.coin-sheet .progress-ring .bg { fill: none; stroke: rgba(15,107,88,0.10); stroke-width: 3; }
.coin-sheet .progress-ring .progress {
    fill: none; stroke: var(--np-primary, #0F6B58); stroke-width: 3; stroke-linecap: round;
    stroke-dasharray: 380.133; stroke-dashoffset: 380.133;
    transition: stroke 0.35s ease;
}
.coin-sheet .progress-ring.spinning .progress {
    stroke-dashoffset: 300; animation: ringSpin 1s linear infinite;
    transform-origin: 50% 50%;
}
@keyframes ringSpin { 100% { transform: rotate(360deg); } }
.coin-sheet .glow-ring {
    position: absolute; top: 50%; left: 50%; width: 108px; height: 108px;
    transform: translate(-50%, -50%) scale(1); border-radius: 50%;
    pointer-events: none; opacity: 0;
    border: 2px solid transparent;
}
.coin-sheet .glow-ring.active { opacity: 1; }
.coin-sheet .coin.success ~ .glow-ring.active,
.coin-sheet .glow-ring.active.ripple-success {
    border-color: rgba(27,143,90,0.4);
    animation: statusRipple 1.4s cubic-bezier(0.22,1,0.36,1) 1;
}
.coin-sheet .glow-ring.active.ripple-failed {
    border-color: rgba(214,69,69,0.35);
    animation: statusRipple 0.7s cubic-bezier(0.22,1,0.36,1) 1;
}
@keyframes statusRipple {
    0%   { transform: translate(-50%, -50%) scale(0.85); opacity: 0.9; }
    100% { transform: translate(-50%, -50%) scale(1.9); opacity: 0; }
}
.coin-sheet .coin-wrapper.result-success { transform: scale(1.08); }
.coin-sheet .coin-wrapper.result-success .coin-face {
    background: linear-gradient(155deg, var(--np-success, #1FA366), var(--np-primary-dark, #14704A));
    border-color: transparent;
    box-shadow: 0 12px 32px rgba(27,143,90,0.3);
}
.coin-sheet .coin-wrapper.result-failed { transform: scale(1); animation: badgeShake 0.5s cubic-bezier(0.36,0.07,0.19,0.97); }
.coin-sheet .coin-wrapper.result-failed .coin-face {
    background: linear-gradient(155deg, #E0554F, #B03636);
    border-color: transparent;
    box-shadow: 0 12px 32px rgba(214,69,69,0.28);
}
@keyframes badgeShake {
    0%,100% { transform: translateX(0) scale(1); }
    20% { transform: translateX(-6px) scale(1.02); } 40% { transform: translateX(6px) scale(1.02); }
    60% { transform: translateX(-4px) scale(1.01); } 80% { transform: translateX(4px) scale(1.01); }
}
.coin-sheet .check-engrave, .coin-sheet .x-engrave {
    position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%) scale(0.4);
    width: 46px; height: 46px; z-index: 3; pointer-events: none; opacity: 0;
}
.coin-sheet .check-engrave.show, .coin-sheet .x-engrave.show {
    opacity: 1; transform: translate(-50%,-50%) scale(1);
    transition: transform 0.5s cubic-bezier(0.34,1.56,0.64,1), opacity 0.3s ease;
}
.coin-sheet .check-engrave svg, .coin-sheet .x-engrave svg {
    width: 100%; height: 100%; stroke: white; stroke-width: 5; fill: none;
    stroke-linecap: round; stroke-linejoin: round;
    stroke-dasharray: 44; stroke-dashoffset: 44;
    transition: stroke-dashoffset 0.55s cubic-bezier(0.65,0,0.35,1) 0.15s;
}
.coin-sheet .check-engrave svg.draw, .coin-sheet .x-engrave svg.draw { stroke-dashoffset: 0; }
#coin-fx-canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1; }
.coin-sheet .cn-status-text {
    text-align: center; color: rgba(16,36,31,0.45); font-weight: 600; letter-spacing: 0.1px;
    font-family: 'Sora', 'Inter', sans-serif;
    font-size: 1.12rem; margin-top: 16px;
    transition: color 0.3s ease;
}
.coin-sheet .cn-status-text.success { color: #14704A; }
.coin-sheet .cn-status-text.failed { color: #B03636; }
.coin-sheet .cn-sub-text { text-align: center; font-size: 0.84rem; color: #8A968F; margin-top: 4px; }
.coin-sheet .details-card { opacity: 0; transform: translateY(10px); transition: opacity .5s ease, transform .5s ease; }
.coin-sheet .details-card.show { opacity: 1; transform: translateY(0); }
.coin-sheet .detail-item { opacity: 0; transform: translateY(6px); transition: opacity .4s ease, transform .4s ease; }
.coin-sheet .detail-item.visible { opacity: 1; transform: translateY(0); }
.coin-sheet .countdown-box, .coin-sheet .action-btn-primary { opacity: 0; transform: translateY(10px); transition: opacity .4s ease, transform .4s ease; }
.coin-sheet .countdown-box.show, .coin-sheet .action-btn-primary.show { opacity: 1; transform: translateY(0); }

/* OVERLAY — click behaviour controlled via JS flags */
.sheet-overlay {
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: rgba(26,26,36,0.45);
    z-index: 1499;
    opacity: 0;
    pointer-events: none;
    backdrop-filter: blur(0px);
    -webkit-backdrop-filter: blur(0px);
    transition: opacity 0.3s, backdrop-filter 0.3s, -webkit-backdrop-filter 0.3s;
}
.sheet-overlay.active { opacity: 1; pointer-events: all; backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(3px); }

.sheet-body { padding: 0 24px 24px; }
.details-card {
    background: rgba(15,107,88,0.04);
    border: 1px solid rgba(15,107,88,0.08);
    border-radius: 16px;
    padding: 16px;
    margin: 20px 0;
}
.detail-item {
    display: flex; justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid rgba(15,107,88,0.08);
}
.detail-item:last-child { border-bottom: none; }
.detail-label { font-size: 0.85rem; font-weight: 500; color: #5B6B66; }
.detail-value { font-size: 0.9rem; font-weight: 600; color: var(--np-primary, #0F6B58); font-family: 'SFMono-Regular', Menlo, monospace; }

.countdown-box {
    text-align: center; font-size: 0.9rem;
    padding: 14px;
    background: rgba(15,107,88,0.07);
    border-radius: 14px;
    margin: 20px 0;
    font-weight: 500;
    color: var(--np-text-dark, #10241F);
}
.countdown-number { color: var(--np-primary, #0F6B58); font-weight: 700; font-size: 1rem; }

.action-btn-primary {
    width: 100%; padding: 15px;
    background: linear-gradient(155deg, var(--np-primary, #0F6B58), var(--np-primary-dark, #0B5245)); color: #fff;
    border: none; border-radius: 100px;
    font-size: 14px; font-weight: 600;
    cursor: pointer; font-family: 'Inter', inherit;
    box-shadow: 0 8px 20px -4px rgba(15,107,88,0.45);
    transition: transform 0.15s cubic-bezier(0.22,1,0.36,1), filter 0.15s;
}
.action-btn-primary:hover { filter: brightness(1.1); }
.action-btn-primary:active { transform: scale(0.98); }

/* TIMEOUT SCREEN */
.timeout-screen {
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: var(--np-card-bg, #F4F6F5);
    display: flex; flex-direction: column;
    align-items: center; justify-content: center;
    z-index: 3000;
    opacity: 0; pointer-events: none;
    transition: opacity 0.4s;
    text-align: center;
    padding: 20px;
    box-sizing: border-box;
}
.timeout-screen.active { opacity: 1; pointer-events: all; }
.timeout-icon { font-size: 4rem; color: var(--error); margin-bottom: 20px; animation: shake 0.5s ease-in-out infinite alternate; }
@keyframes shake { 0%{transform:translateX(-2px)} 100%{transform:translateX(2px)} }
.timeout-title { font-family: 'Sora', sans-serif; font-size: 1.35rem; font-weight: 700; margin-bottom: 12px; color: var(--error); }
.timeout-text { font-size: 0.9rem; max-width: 400px; margin-bottom: 30px; color: #5B6B66; line-height: 1.6; }
.refresh-btn {
    padding: 14px 32px;
    background: linear-gradient(155deg, var(--np-primary, #0F6B58), var(--np-primary-dark, #0B5245)); color: #fff;
    border: none; border-radius: 100px;
    font-size: 0.9rem; font-weight: 600;
    cursor: pointer; display: flex; align-items: center; gap: 8px;
    font-family: 'Inter', inherit;
    box-shadow: 0 8px 20px -4px rgba(15,107,88,0.45);
    transition: transform 0.15s cubic-bezier(0.22,1,0.36,1);
}
.refresh-btn:active { transform: scale(0.97); }
.status-success .timeout-icon, .status-success .timeout-title { color: #16A34A; }
.status-pending .timeout-icon, .status-pending .timeout-title { color: #C9971F; }
.status-failed  .timeout-icon, .status-failed  .timeout-title { color: #D64545; }
.status-error   .timeout-icon, .status-error    .timeout-title { color: #A5322B; }

/* TEST FAB */
.test-mode-fab {
    position: fixed; right: 30px; bottom: 30px;
    background: linear-gradient(155deg, var(--np-primary, #0F6B58), var(--np-primary-dark, #0B5245));
    border-radius: 30px; padding: 10px 16px;
    display: flex; align-items: center; gap: 8px;
    color: #fff; font-size: 14px; font-weight: 600;
    cursor: pointer;
    box-shadow: 0 8px 20px rgba(15,107,88,0.35);
    z-index: 4000; transition: 0.25s cubic-bezier(0.22,1,0.36,1);
    opacity: 0; visibility: hidden; transform: scale(0.85); pointer-events: none;
}
.test-mode-fab.show { opacity: 1; visibility: visible; transform: scale(1); pointer-events: auto; }
.fab-text { white-space: nowrap; }
.test-mode-overlay {
    position: fixed; inset: 0;
    background: rgba(11,21,18,0.45);
    z-index: 3999; opacity: 0; pointer-events: none; transition: 0.3s;
}
.test-mode-overlay.active { opacity: 1; pointer-events: auto; }
.test-mode-dialog {
    position: fixed; right: 20px; bottom: 90px;
    background: #ffffff;
    padding: 18px; border-radius: 16px;
    box-shadow: 0 12px 32px rgba(15,107,88,0.18); width: 220px;
    z-index: 4000; transform: scale(0.8) translateY(8px);
    opacity: 0; pointer-events: none; transition: 0.28s cubic-bezier(0.22,1,0.36,1);
}
.test-mode-dialog.active { transform: scale(1) translateY(0); opacity: 1; pointer-events: auto; }

.confirm-overlay {
    position: fixed; inset: 0;
    background: rgba(11,21,18,0.55);
    z-index: 4998; opacity: 0; pointer-events: none; transition: 0.25s;
    backdrop-filter: blur(2px); -webkit-backdrop-filter: blur(2px);
}
.confirm-overlay.active { opacity: 1; pointer-events: auto; }
.confirm-dialog {
    position: fixed; top: 50%; left: 50%;
    transform: translate(-50%,-50%) scale(0.9);
    background: #fff; border-radius: 22px; padding: 32px 26px 26px;
    width: 90%; max-width: 340px; text-align: center;
    box-shadow: 0 20px 60px rgba(11,21,18,0.22);
    z-index: 4999; opacity: 0; pointer-events: none; transition: 0.3s cubic-bezier(0.22,1,0.36,1);
}
.confirm-dialog.active { transform: translate(-50%,-50%) scale(1); opacity: 1; pointer-events: auto; }
.confirm-icon-wrap {
    width: 68px; height: 68px; border-radius: 50%; margin: 0 auto 18px;
    display: flex; align-items: center; justify-content: center;
    background: linear-gradient(145deg, #E88A80, #D64545);
    box-shadow: 0 8px 22px -8px rgba(214,69,69,0.55);
}
.confirm-icon-wrap i { color: #fff; font-size: 26px; }
.confirm-dialog h3 { font-size: 20px; color: var(--np-text-dark, #10241F); margin-bottom: 10px; font-family: 'Sora', sans-serif; font-weight: 700; }
.confirm-dialog p { font-size: 14px; color: var(--np-text-muted, #5B6B66); margin-bottom: 24px; line-height: 1.5; }
.confirm-btn-row { display: flex; gap: 12px; }
.confirm-btn-no, .confirm-btn-yes {
    flex: 1; padding: 13px; border-radius: 100px; border: none;
    font-size: 14px; font-weight: 700; cursor: pointer; transition: .15s;
    font-family: 'Inter', sans-serif;
}
.confirm-btn-no { background: rgba(15,107,88,0.08); color: var(--np-text-dark, #10241F); }
.confirm-btn-no:active { transform: scale(.97); }
.confirm-btn-yes { background: var(--np-primary, #0F6B58); color: #fff; box-shadow: 0 8px 18px -4px rgba(15,107,88,0.5); }
.confirm-btn-yes:active { transform: scale(.97); }
.test-mode-dialog h3 { font-size: 14px; margin-bottom: 12px; text-align: center; color: var(--np-primary, #0F6B58); font-family: 'Sora', sans-serif; font-weight: 600; }
.test-btn {
    width: 100%; padding: 10px; border-radius: 10px;
    border: none; font-weight: 600; margin-bottom: 8px;
    cursor: pointer; display: flex; align-items: center; gap: 8px;
    font-size: 13px; font-family: inherit;
}
.test-btn.success { background: rgba(22,163,74,0.12); color: #16A34A; }
.test-btn.failed  { background: rgba(239,68,68,0.12); color: #EF4444; }
.test-btn.timeout { background: rgba(245,158,11,0.15); color: #F59E0B; }

@media (max-width: 768px) {
    .progress-bar-container:nth-child(4),
    .progress-bar-container:nth-child(5) { display: none; }
    .verification-bottom-sheet { padding: 20px 0px 25px; }
    .step-icon { width: 35px; height: 35px; font-size: 1rem; }
    .sheet-header, .sheet-body { padding: 20px; }
    .timeout-screen { padding: 24px 18px; }
    .timeout-icon { font-size: 4rem; }
    .refresh-btn { width: 100%; max-width: 280px; justify-content: center; }
}
@media (max-width: 480px) {
    .result-title { font-size: 1.2rem; }
    .step-text { font-size: 0.7rem; }
}

@media (hover: hover) {
    .t5-app-btn,
    #zap-upiBtn,
    .t5-action-btn,
    #zap-qrDownloadBtn,
    button {
        cursor: pointer;
    }
}

.t5-app-btn,
#zap-upiBtn,
.t5-action-btn,
#zap-qrDownloadBtn,
button {
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
}
</style>
</head>
<body>

<div class="page-loader" id="pageLoader">
    <div class="mini-coin"></div>
    <div class="loader-text">Verifying transaction...</div>
</div>

<div class="timeout-screen" id="timeoutScreen">
    <i class="fas fa-exclamation-circle timeout-icon"></i>
    <h2 class="timeout-title" id="timeoutTitle"></h2>
    <p class="timeout-text" id="timeoutText"></p>
    <button class="refresh-btn" id="refreshButton"><i class="fas fa-redo"></i> Refresh Page</button>
</div>

<div class="sheet-overlay" id="sheetOverlay"></div>

<div class="coin-sheet" id="coinSheet">
    <div class="handle"></div>
    <div class="stage">
        <div class="coin-wrapper" id="coinWrapper">
            <div class="coin" id="coin">
                <div class="coin-face coin-front">
                    <span class="rupee" id="rupeeSymbol">₹</span>
                    <div class="gloss" id="glossReflection"></div>
                    <div class="rim-highlight"></div>
                    <div class="check-engrave" id="checkEngrave">
                        <svg viewBox="0 0 60 60"><polyline points="14,32 28,48 48,16" /></svg>
                    </div>
                    <div class="x-engrave" id="xEngrave">
                        <svg viewBox="0 0 60 60">
                            <line x1="14" y1="14" x2="46" y2="46" />
                            <line x1="46" y1="14" x2="14" y2="46" />
                        </svg>
                    </div>
                </div>
                <div class="coin-edge"></div>
            </div>
            <svg class="progress-ring" id="progressRing" viewBox="0 0 136 136">
                <circle class="bg" cx="68" cy="68" r="60" />
                <circle class="progress" cx="68" cy="68" r="60" />
            </svg>
            <div class="glow-ring" id="glowRing"></div>
        </div>
        <canvas id="coin-fx-canvas"></canvas>
    </div>
    <div class="cn-status-text" id="cnStatusText">Securing Payment</div>
    <div class="cn-sub-text" id="cnSubText">Please wait while we verify your transaction</div>

    <div class="sheet-body">
        <div class="details-card" id="txContainer">
            <div class="detail-item" id="rowTxn">
                <span class="detail-label">TXN ID</span>
                <span class="detail-value" id="txnId">-</span>
            </div>
            <div class="detail-item" id="utrRow">
                <span class="detail-label" id="utrLabel">UTR Number</span>
                <span class="detail-value" id="utrNumber">-</span>
            </div>
            <div class="detail-item" id="rowAmount">
                <span class="detail-label">Amount</span>
                <span class="detail-value" id="amountValue">-</span>
            </div>
            <div class="detail-item" id="rowDate">
                <span class="detail-label" id="dateLabel">Date &amp; Time</span>
                <span class="detail-value" id="dateTime">-</span>
            </div>
        </div>
        <div class="countdown-box" id="btnContainer" style="display:none">
            Redirecting in <span class="countdown-number" id="countdownNumber">5</span> seconds...
        </div>
        <button class="action-btn-primary" id="okButton" style="display:none">OK</button>
    </div>
</div>

<div class="test-mode-fab" id="testModeFab">
    <i class="fas fa-flask"></i>
    <span class="fab-text">Test Action</span>
</div>
<div class="test-mode-overlay" id="testModeOverlay"></div>
<div class="test-mode-dialog" id="testModeDialog">
    <h3>Test Payment Mode</h3>
    <button class="test-btn success" id="testSuccess"><i class="fas fa-check-circle"></i> Success Payment</button>
    <button class="test-btn failed"  id="testFailed"><i class="fas fa-times-circle"></i> Failed Payment</button>
    <button class="test-btn timeout" id="testTimeout"><i class="fas fa-clock"></i> Timeout Payment</button>
</div>

<div class="confirm-overlay" id="cancelConfirmOverlay"></div>
<div class="confirm-dialog" id="cancelConfirmDialog">
    <div class="confirm-icon-wrap"><i class="fas fa-triangle-exclamation"></i></div>
    <h3>Cancel Payment?</h3>
    <p>Are you sure you want to cancel this payment?</p>
    <div class="confirm-btn-row">
        <button class="confirm-btn-no" id="cancelConfirmNo">No</button>
        <button class="confirm-btn-yes" id="cancelConfirmYes">Yes, Cancel</button>
    </div>
</div>

<div class="container">
    <!-- <button id="cancelPaymentBtn">CANCEL</button> -->
    <main>
        <style>
/* Font Awesome icon fix */
i[class^="fa"], i[class*=" fa"] {
  font-family: "Font Awesome 6 Free" !important;
  font-weight: 900;
}

:root {
  --np-primary: <?php echo $checkoutPrimaryColor; ?>;
  --np-primary-dark: <?php echo $checkoutPrimaryColorDark; ?>;
  --np-gold: <?php echo $checkoutSecondaryColor; ?>;
  --np-bg: <?php echo $checkoutBgColor; ?>;
  --np-card-bg: <?php echo $checkoutCardBgColor; ?>;
  --np-text-dark: <?php echo $checkoutTextColor; ?>;
  --np-text-muted: #5B6B66;
  --np-success: <?php echo $checkoutSuccessColor; ?>;
  --np-success-light: #EBF7F0;
  --np-heading-font: 'Sora', 'Inter', system-ui, sans-serif;
}

.container { padding: 0 !important; max-width: 100% !important; }
main { padding: 0 !important; }

.t3 * { box-sizing: border-box; }

.t3 {
  min-height: 100vh;
  background: var(--np-bg);
  display: flex;
  justify-content: center;
  padding: 0;
  font-family: 'Inter', 'Segoe UI', system-ui, sans-serif;
}

.np-app {
  width: 100%;
  max-width: 430px;
  background-color: var(--np-card-bg);
  min-height: 100vh;
  position: relative;
  overflow-x: hidden;
  box-shadow: 0 0 32px rgba(11,21,18,0.06);
  padding-bottom: 32px;
}

/* Animations */
.np-fade { opacity: 0; transform: translateY(14px); animation: npFadeUp 0.65s cubic-bezier(0.22,1,0.36,1) forwards; }
@keyframes npFadeUp { to { opacity: 1; transform: translateY(0); } }
.np-d1 { animation-delay: .06s; }
.np-d2 { animation-delay: .13s; }
.np-d3 { animation-delay: .2s; }
.np-d4 { animation-delay: .28s; }
.np-d5 { animation-delay: .36s; }
.np-d6 { animation-delay: .44s; }
.np-d7 { animation-delay: .52s; }

/* Header */
.np-header { display: flex; align-items: center; padding: 24px 20px 16px; }
.np-logo-box {
  width: 44px; height: 44px; background: linear-gradient(155deg, var(--np-primary), var(--np-primary-dark)); border-radius: 13px;
  display: flex; align-items: center; justify-content: center; margin-right: 14px;
  box-shadow: 0 4px 12px rgba(15,107,88,0.25); overflow: hidden; flex-shrink: 0;
}
.np-logo-box img { width: 100%; height: 100%; object-fit: contain; }
.np-header-info { flex: 1; min-width: 0; }
.np-header-title {
  font-family: var(--np-heading-font); font-size: 17px; font-weight: 700; color: var(--np-text-dark); line-height: 1.25;
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.np-header-sub { font-size: 11px; color: var(--np-text-muted); margin-top: 2px; letter-spacing: 0.1px; }
.np-close-btn {
  width: 38px; height: 38px; border-radius: 50%; background: #fff;
  display: flex; align-items: center; justify-content: center; border: none;
  box-shadow: 0 2px 12px rgba(15,107,88,0.1); color: var(--np-primary);
  cursor: pointer; transition: 0.18s cubic-bezier(0.22,1,0.36,1); flex-shrink: 0;
}
.np-close-btn:hover { background: rgba(214,69,69,0.08); color: #D64545; }
.np-close-btn:active { transform: scale(0.92); }

/* Merchant card */
.np-merchant-card {
  background: #fff; margin: 8px 20px; padding: 12px 16px; border-radius: 16px;
  display: flex; align-items: center; box-shadow: 0 6px 20px rgba(15,107,88,0.05);
  border: 1px solid rgba(15,107,88,0.04);
}
.np-merchant-icon {
  width: 44px; height: 44px; background: linear-gradient(155deg, var(--np-primary), var(--np-primary-dark)); border-radius: 50%;
  display: flex; align-items: center; justify-content: center; color: #fff;
  margin-right: 14px; box-shadow: 0 4px 10px rgba(15,107,88,0.2); flex-shrink: 0; font-size: 18px;
}
.np-merchant-details { flex: 1; min-width: 0; }
.np-merchant-name {
  font-size: 13px; font-weight: 600; color: var(--np-text-dark); display: flex;
  align-items: center; gap: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.np-merchant-name i { color: var(--np-success); font-size: 12px; }
.np-merchant-sub { font-size: 11px; color: var(--np-text-muted); margin-top: 2px; }
.np-secure-badge {
  background: var(--np-success-light); color: var(--np-success); padding: 6px 10px;
  border-radius: 20px; font-size: 10px; font-weight: 600; display: flex; align-items: center;
  gap: 4px; white-space: nowrap; flex-shrink: 0;
}

/* Amount */
.np-amount-section { text-align: center; margin-top: 30px; padding: 0 20px; }
.np-amount-label { font-size: 13px; color: var(--np-text-muted); font-weight: 500; }
.np-amount-value {
  font-family: var(--np-heading-font); font-size: 42px; font-weight: 700; color: var(--np-text-dark); line-height: 1.1;
  margin-top: 6px; letter-spacing: -0.8px; font-variant-numeric: tabular-nums;
}
.np-amount-value::first-letter { color: var(--np-primary); }
.np-txn-pill {
  display: inline-flex; align-items: center; gap: 5px; margin-top: 12px; padding: 4px 12px;
  border-radius: 20px; background: rgba(201,151,31,0.08); border: 1px solid rgba(201,151,31,0.22);
  font-size: 10px; color: #8A6A12; font-family: 'SFMono-Regular', Menlo, monospace; letter-spacing: 0.2px;
}

.np-divider { display: flex; align-items: center; justify-content: center; margin: 20px 80px 16px; }
.np-divider::before, .np-divider::after { content: ''; flex: 1; height: 1px; background: rgba(15,107,88,0.15); }
.np-divider svg { width: 13px; height: 13px; fill: var(--np-gold); margin: 0 10px; }

/* QR */
.np-qr-section { position: relative; display: flex; justify-content: center; margin-top: 16px; }
.np-qr-card-wrapper { animation: npQrFloat 6s ease-in-out infinite; }
@keyframes npQrFloat { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-6px); } }
.np-qr-card {
  background: #fff; padding: 18px; border-radius: 22px; box-shadow: 0 16px 40px rgba(15,107,88,0.12);
  border: 1px solid rgba(15,107,88,0.06); width: 240px; height: 240px;
  display: flex; align-items: center; justify-content: center; position: relative;
}
.np-qr-card::before {
  content: ''; position: absolute; inset: -1px; border-radius: 23px; padding: 1px;
  background: linear-gradient(135deg, rgba(201,151,31,0.35), rgba(15,107,88,0.15));
  -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  -webkit-mask-composite: xor; mask-composite: exclude; pointer-events: none;
}
.np-qr-card > div { display: flex !important; align-items: center; justify-content: center; width: 100%; height: 100%; }
.np-qr-card canvas { max-width: 100%; max-height: 100%; }

.np-timer { display: flex; align-items: center; justify-content: center; gap: 6px; margin-top: 22px; color: var(--np-primary); font-size: 13px; font-weight: 500; }
#zap-qrTimer.urgent { color: #D64545 !important; animation: npBlink 1s ease infinite; }
@keyframes npBlink { 0%,100% { opacity: 1; } 50% { opacity: 0.3; } }

.np-download-btn {
  display: flex; align-items: center; justify-content: center; gap: 8px; margin: 16px auto 0;
  padding: 10px 24px; border: 1.5px solid rgba(15,107,88,0.2); border-radius: 100px;
  background: transparent; color: var(--np-primary); font-size: 13px; font-weight: 600;
  font-family: inherit; cursor: pointer; transition: 0.2s;
}
.np-download-btn:hover { background: rgba(15,107,88,0.04); }
.np-download-btn:active { transform: scale(0.97); }

.np-text-divider { display: flex; align-items: center; justify-content: center; margin: 32px 24px 24px; color: var(--np-text-muted); font-size: 12px; font-weight: 500; }
.np-text-divider::before, .np-text-divider::after { content: ''; flex: 1; height: 1px; background: rgba(0,0,0,0.06); margin: 0 12px; }

/* Payment options */
.np-options { padding: 0 20px; display: flex; flex-direction: column; gap: 10px; }
.np-option-card {
  background: #fff; border-radius: 16px; padding: 14px 16px; display: flex; align-items: center;
  box-shadow: 0 3px 10px rgba(11,21,18,0.03); cursor: pointer; border: 1px solid rgba(11,21,18,0.04);
  transition: 0.2s cubic-bezier(0.22,1,0.36,1); width: 100%; text-align: left; font-family: inherit;
  -webkit-tap-highlight-color: transparent;
}
.np-option-card:hover { box-shadow: 0 10px 24px rgba(15,107,88,0.08); border-color: rgba(15,107,88,0.12); transform: translateY(-2px); }
.np-option-card:active { transform: scale(0.98); }
.np-option-icon {
  width: 42px; height: 42px; border-radius: 50%; display: flex; align-items: center;
  justify-content: center; margin-right: 15px; box-shadow: 0 4px 12px rgba(0,0,0,0.04);
  flex-shrink: 0; background: #fff; border: 1px solid rgba(11,21,18,0.05);
}
.np-option-icon svg { width: 22px; height: 22px; }
.np-option-info { flex: 1; min-width: 0; }
.np-option-title { font-size: 14px; font-weight: 600; color: var(--np-text-dark); }
.np-option-sub { font-size: 12px; color: var(--np-text-muted); margin-top: 2px; }
.np-option-chevron { color: #8A968F; font-size: 14px; flex-shrink: 0; transition: transform 0.2s ease; }
.np-option-card:hover .np-option-chevron { transform: translateX(2px); color: var(--np-primary); }

/* Footer */
.np-footer-card {
  background: var(--np-success-light); margin: 24px 20px 0; padding: 16px; border-radius: 12px;
  display: flex; align-items: center; gap: 12px; border: 1px solid rgba(22,163,74,0.1);
}
.np-footer-icon {
  width: 32px; height: 32px; background: var(--np-success); border-radius: 50%;
  display: flex; align-items: center; justify-content: center; color: #fff; flex-shrink: 0; font-size: 14px;
}
.np-footer-info { flex: 1; }
.np-footer-title { font-size: 12px; font-weight: 600; color: var(--np-success); }
.np-footer-lock { color: var(--np-success); opacity: 0.8; font-size: 18px !important; }
</style>

<div class="t3">
<div class="np-app" id="mainContainer">

  <!-- SENTINEL — index.php yahi hide/show karta hai, layout pe koi asar nahi -->
  <div id="zap-removeQrCode" style="position:fixed;width:0;height:0;overflow:hidden;pointer-events:none;opacity:0;z-index:-1;"></div>

  <!-- HEADER -->
  <div class="np-header np-fade np-d1">
    <div class="np-logo-box">
      <img id="zap-companyLogo" src="" alt="Logo" style="display:none;">
      <i class="fa-solid fa-store" id="t3LogoIco" style="color:#fff;font-size:18px;"></i>
    </div>
    <div class="np-header-info">
      <div class="np-header-title" id="zap-companyName">Loading...</div>
      <div class="np-header-sub">Secure. Instant. UPI Payments</div>
    </div>
    <button class="np-close-btn" id="cancelPaymentBtn" aria-label="Cancel Payment" type="button">
      <i class="fa-solid fa-xmark"></i>
    </button>
  </div>

  <!-- MERCHANT INFO -->
  <div class="np-merchant-card np-fade np-d2">
    <div class="np-merchant-icon"><i class="fa-solid fa-shield-halved"></i></div>
    <div class="np-merchant-details">
      <div class="np-merchant-name">Verified Merchant <i class="fa-solid fa-circle-check"></i></div>
      <div class="np-merchant-sub">Secure payments powered by UPI</div>
    </div>
    <div class="np-secure-badge"><i class="fa-solid fa-lock"></i> 100% Secure</div>
  </div>

  <!-- AMOUNT -->
  <div class="np-amount-section np-fade np-d3">
    <div class="np-amount-label">Pay to <span id="zap-companyName2">Merchant</span></div>
    <div class="np-amount-value">&#8377;<span id="zap-payAmount">0.00</span></div>
    <div class="np-txn-pill"><i class="fa-solid fa-hashtag" style="font-size:9px"></i><span id="zap-txnId">—</span></div>
  </div>

  <!-- Divider -->
  <div class="np-divider np-fade np-d4">
    <svg viewBox="0 0 24 24"><path d="M12 0C12 10 22 12 22 12C22 12 12 14 12 24C12 14 2 12 2 12C2 12 12 10 12 0Z"/></svg>
  </div>

  <!-- QR CODE (shown/hidden by CHECKOUT_SHOW_QR toggle) -->
  <div class="np-qr-section np-fade np-d4" id="t3-pc-qr-card">
    <div class="np-qr-card-wrapper">
      <div class="np-qr-card" id="zap-qrCodeBox">
        <div id="zap-qrCode"></div>
      </div>
    </div>
  </div>
  <!-- hidden secondary render target kept for engine compatibility -->
  <div id="t3-qrCode-mobile" style="display:none;"></div>

  <!-- TIMER -->
  <div class="np-timer np-fade np-d5">
    <i class="fa-solid fa-clock"></i>
    <span>Payment expires in <strong id="zap-qrTimer">08:00</strong></span>
  </div>

  <!-- DOWNLOAD QR -->
  <button class="np-download-btn np-fade np-d6" id="zap-qrDownloadBtn" type="button">
    <i class="fa-solid fa-download"></i> Download QR
  </button>

  <div class="np-text-divider np-fade np-d6">or choose a payment option</div>

  <!-- PAYMENT OPTIONS -->
  <div class="np-options np-fade np-d7" id="zap-payButtons">

    <button class="np-option-card" id="zap-gpayBtn" type="button">
      <div class="np-option-icon">
        <svg width="24" height="24" viewBox="0 0 48 48" fill="none">
          <path d="M44 24.5c0-1.4-.1-2.7-.4-4H24v7.6h11.3a9.7 9.7 0 01-4.2 6.4v5.3h6.8C41.8 36.1 44 30.8 44 24.5z" fill="#4285F4"/>
          <path d="M24 45c5.7 0 10.5-1.9 14-5.1l-6.8-5.3c-1.9 1.3-4.3 2-7.2 2-5.5 0-10.2-3.7-11.9-8.8H5.1v5.5A21 21 0 0024 45z" fill="#34A853"/>
          <path d="M12.1 27.8A12.7 12.7 0 0111.4 24c0-1.3.2-2.6.7-3.8v-5.5H5.1A21 21 0 003 24c0 3.4.8 6.6 2.1 9.3l7-5.5z" fill="#FBBC05"/>
          <path d="M24 11.4c3.1 0 5.9 1.1 8.1 3.1l6-6A21 21 0 0024 3 21 21 0 005.1 14.7l7 5.5c1.7-5.1 6.4-8.8 11.9-8.8z" fill="#EA4335"/>
        </svg>
      </div>
      <div class="np-option-info">
        <div class="np-option-title">Google Pay</div>
        <div class="np-option-sub">Instant Payment</div>
      </div>
      <i class="fa-solid fa-chevron-right np-option-chevron"></i>
    </button>

    <button class="np-option-card" id="zap-paytmBtn" type="button">
      <div class="np-option-icon" style="padding:8px;">
        <svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" x="0" y="0" style="enable-background:new -164 191.6 512 193" version="1.1" viewBox="-164 191.6 512 193">
          <g>
            <path d="M229.8,243.2c2-1.6,3-2.4,4-3.2c13.9-11.8,31.7-10.5,43.6,3.5c1.2,1.4,1.8,1.5,3,0.3c0.8-0.9,1.7-1.6,2.5-2.5   c9.3-9.1,21.6-11.8,33.1-6.7c12.1,5.4,18.6,14.9,18.7,28.2c0.2,28.7,0.1,57.3,0.1,86c0,10.2-6.3,16.6-16.4,16.6c-4,0-8-0.3-12,0.1   c-4.1,0.4-5.3-0.9-5.3-5.2c0.2-28,0.1-56,0.1-84c0-1.2,0-2.3,0-3.5c-0.1-6.5-2.7-9.2-8.9-9.5c-5.6-0.3-9.5,3.1-10.1,8.8   c-0.1,1.3,0,2.7,0,4c0,24.2,0,48.3,0,72.5c0,10.6-6.1,16.8-16.7,16.7c-5.4-0.1-12.7,2.4-15.8-1.1c-2.7-3-0.9-10.1-0.9-15.4   c0-24.8,0-49.7,0-74.5c0-8.8-5.7-13.3-13.1-10.3c-4.6,1.9-6.1,5.6-6.1,10.4c0.1,23.2,0,46.3,0,69.5c0,1.8,0,3.7,0,5.5   c-0.3,9.7-6.5,15.8-16.1,15.9c-4,0.1-8-0.3-12,0.1c-4.3,0.4-5.6-0.8-5.5-5.4c0.2-39.3,0.1-78.6,0.1-118c0-1.7,0.1-3.3,0-5   c-0.2-2.2,0.7-2.9,2.9-2.9c9.2,0.1,18.3,0.1,27.5,0c2.3,0,3.4,0.6,3.2,3.1C229.5,239,229.7,240.6,229.8,243.2z" style="fill:#02b9ef"></path>
            <path d="M17.8 297.4c0 13.7 0 27.3 0 41-.1 17.8-9.4 27-27.2 27.1-7.8 0-15.7.1-23.5 0-15.8-.2-27.4-10.7-28.2-26.5-.6-11.3-.7-22.7-.1-34 .8-16.2 13.2-27.6 29.6-27.8 4.3-.1 8.7 0 13 0 4.2-.1 5.8-2.5 5.7-6.5 0-4-1.8-5.8-5.8-5.6-4.5.1-9 .1-13.5 0-11-.2-17.1-6.2-17-17 0-4.4-2-10.3.9-12.9 2.5-2.2 8.2-.8 12.5-.8 11.2-.1 22.3 0 33.5 0 11.9 0 20 8.1 20.1 20.1C17.9 268.7 17.8 283.1 17.8 297.4zM-12.8 320.1c0-1.7 0-3.3 0-5 0-10.2 0-10.2-10.2-9.8-5.1.2-7.9 2.8-8 8.1-.1 4.2-.1 8.3 0 12.5.1 7.2 3.3 9.1 13.7 9.4 7.7.2 3.8-5.2 4.5-8.2C-12.4 324.9-12.9 322.4-12.8 320.1zM106.8 286.5c0 15.3.2 30.7-.1 46-.2 11.8-3 22.5-14.4 28.8-4.6 2.5-9.6 3.9-14.8 4-11.5.2-23 0-34.5.2-2.8 0-3.4-1-3.3-3.5.2-4.2-.1-8.3.1-12.5.2-8 6.3-14.1 14.3-14.4 5.2-.2 10.3-.1 15.5 0 4.2 0 6.5-1.7 6.5-6.2 0-4.6-2.2-6.2-6.4-6.3-7-.2-14 .8-20.9-1.2-11.9-3.5-20.6-13.4-20.9-25.7-.6-19.5-.2-39-.3-58.5 0-2.2.7-2.9 2.9-2.8 8.2.1 16.3.2 24.5 0 3.6-.1 3.1 1.9 3.1 4.1 0 14.7 0 29.3 0 44 0 6.4 3 9.8 8.6 10 6.6.2 9.5-2.5 9.5-9.2 0-14.8.1-29.7-.1-44.5 0-3.5.9-4.5 4.4-4.4 7.3.3 14.7.4 22 0 4-.2 4.6 1.3 4.5 4.8C106.7 254.9 106.8 270.7 106.8 286.5zM-148 309.2c0-16.3 0-32.7 0-49 0-16 9.8-26 25.9-25.8 10.5.1 21-1.2 31.4.8 13.3 2.6 21.7 12.9 21.8 26.6.1 14.5 0 29 0 43.5 0 18.2-10.7 29.3-28.9 29.8-5.5.2-11 .1-16.5 0-2.5-.1-3.6.7-3.5 3.4.2 4 .1 8 0 12-.2 8.6-6.3 14.8-14.8 14.9-5 .1-11.3 2.1-14.5-.8-3-2.7-.8-9.1-.9-13.9C-148.1 336.9-148 323-148 309.2zM-117.8 284.7c0 3.2 0 6.3 0 9.5 0 11.3 0 11.3 11.3 10.3 4.9-.4 7.2-2.8 7.3-7.7.1-5.6-.2-11.3.1-16.9.6-16.2-2.4-14.6-15.6-14.7-2.4 0-3.2.7-3.2 3.1C-117.7 273.7-117.8 279.2-117.8 284.7z" style="fill:#06306f"></path>
            <path d="M135.1,309.4c0-13.3-0.1-26.7,0.1-40c0-3.1-0.7-4.4-4.1-4.3c-4.5,0.2-10.5,1.5-13-0.7   c-3.1-2.9-0.7-9.1-1.1-13.9c0-0.3,0-0.7,0-1c0-4.7-1.5-10.2,0.5-13.7s8.1-1.3,12.4-2.4c8.5-2.2,14.9-7.1,20.1-13.9   c3.6-4.6,8.1-7.9,13.9-9c3.1-0.6,5-0.2,4.8,3.8c-0.3,5.6,0,11.3-0.1,17c-0.1,2.4,0.8,3.2,3.2,3.1c4-0.1,8,0.1,12-0.1   c2.4-0.1,3.2,0.8,3.1,3.2c-0.1,8.2-0.1,16.3,0,24.5c0,2.3-0.6,3.5-3.1,3.2c-0.5-0.1-1,0-1.5,0c-4.4,0.4-10.5-2-12.8,1   c-2.2,2.8-0.8,8.6-0.8,13.1c0,27.2-0.1,54.3,0.1,81.5c0,3.8-1,5-4.8,4.7c-3.6-0.3-7.3,0-11-0.1c-10.8-0.4-17.9-7.7-17.9-18.5   C135.1,334.4,135.1,321.9,135.1,309.4z" style="fill:#02b9ef"></path>
          </g>
        </svg>
      </div>
      <div class="np-option-info">
        <div class="np-option-title">Paytm</div>
        <div class="np-option-sub">Wallet &amp; UPI</div>
      </div>
      <i class="fa-solid fa-chevron-right np-option-chevron"></i>
    </button>

    <div id="zap-upiSection">
      <button class="np-option-card" id="zap-upiBtn" type="button">
        <div class="np-option-icon" style="border:1px solid #E5E7EB;">
          <i class="fa-solid fa-bolt" style="color:var(--np-primary);font-size:20px;"></i>
        </div>
        <div class="np-option-info">
          <div class="np-option-title">Pay with any UPI</div>
          <div class="np-option-sub">BHIM &amp; other UPI Apps</div>
        </div>
        <i class="fa-solid fa-chevron-right np-option-chevron"></i>
      </button>
    </div>

  </div>

  <!-- FOOTER -->
  <div class="np-footer-card np-fade np-d7">
    <div class="np-footer-icon"><i class="fa-solid fa-check"></i></div>
    <div class="np-footer-info">
      <div class="np-footer-title">Your payment is safe and secure</div>
    </div>
    <i class="fa-solid fa-lock np-footer-lock"></i>
  </div>

</div>
</div>

<script>
(function() {

    /* ──  CONTRAST ──  */
    function hexBrightness(hex) {
        hex = (hex || '').trim().replace('#', '');
        if (hex.length === 3) hex = hex.split('').map(function(h){ return h+h; }).join('');
        if (hex.length !== 6) return 128;
        return (parseInt(hex.substring(0,2),16)*299 + parseInt(hex.substring(2,4),16)*587 + parseInt(hex.substring(4,6),16)*114) / 1000;
    }
    function onColor(hex) { return hexBrightness(hex) > 160 ? '#333333' : '#ffffff'; }

    function applyContrast() {
        var s = getComputedStyle(document.documentElement);
        var r = document.documentElement;
        var c1 = s.getPropertyValue('--zap-c1').trim();
        var c4 = s.getPropertyValue('--zap-c4').trim();
        var c5 = s.getPropertyValue('--zap-c5').trim();
        var c7 = s.getPropertyValue('--zap-c7').trim();
        r.style.setProperty('--t3-on-c5', onColor(c5));
        r.style.setProperty('--t3-on-c7', onColor(c7));
        r.style.setProperty('--t3-on-c1', onColor(c1));
        var c7b = hexBrightness(c7) > 160;
        r.style.setProperty('--t3-inner-bg',    c7b ? 'rgba(0,0,0,0.03)'   : 'rgba(255,255,255,0.15)');
        r.style.setProperty('--t3-inner-border', c7b ? 'rgba(0,0,0,0.08)'   : 'rgba(255,255,255,0.25)');
        r.style.setProperty('--t3-hint-color',  c7b ? 'rgba(51,51,51,0.5)' : 'rgba(255,255,255,0.6)');
        r.style.setProperty('--wm-color', hexBrightness(c4) > 128 ? 'rgba(51,51,51,0.5)' : 'rgba(255,255,255,0.6)');
    }

    /* ──  LOGO ──  */
    var logo = document.getElementById('zap-companyLogo');
    var ico  = document.getElementById('t3LogoIco');
    if (logo && ico) {
        logo.onload  = function() { logo.style.display='block'; ico.style.display='none'; };
        logo.onerror = function() { logo.style.display='none';  ico.style.display='block'; };
    }

    /* ──  NAME SYNC ──  */
    var n1 = document.getElementById('zap-companyName');
    var n2 = document.getElementById('zap-companyName2');
    if (n1 && n2) {
        new MutationObserver(function() { n2.textContent = n1.textContent; })
            .observe(n1, { childList: true, characterData: true, subtree: true });
    }

    /* ──  TIMER SYNC ──  */
    // var t1 = document.getElementById('zap-qrTimer');
    // var t2 = document.getElementById('zap-qrTimer2');
    // if (t1 && t2) {
    //     new MutationObserver(function() { t2.textContent = t1.textContent; })
    //         .observe(t1, { childList: true, characterData: true, subtree: true });
    // }

    /* ──  DUAL QR RENDER ──  */
    /* index.php ka QR render intercep karo — dono targets pe render karo */
    window.zapRenderQR = function(qrText) {
        var pcDiv = document.getElementById('zap-qrCode');
        var moDiv = document.getElementById('t3-qrCode-mobile');

        function makeQR(target) {
            if (!target) return;
            target.innerHTML = '';
            new QRCode(target, {
                text: qrText,
                width: 200, height: 200,
                colorDark: '#000000', colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H
            });
        }

        makeQR(pcDiv);
        makeQR(moDiv);
    };

    /* Mobile download — PC canvas se */
    var mobileDl = document.getElementById('t3-dl-mobile');
    if (mobileDl) {
        mobileDl.onclick = function() {
            /* Mobile QR canvas pehle try karo, phir PC */
            var canvas = document.querySelector('#t3-qrCode-mobile canvas')
                      || document.querySelector('#zap-qrCode canvas');
            if (!canvas) return;
            var pad = 20, nc = document.createElement('canvas');
            nc.width = canvas.width + pad*2; nc.height = canvas.height + pad*2;
            var ctx = nc.getContext('2d');
            ctx.fillStyle = '#ffffff'; ctx.fillRect(0,0,nc.width,nc.height);
            ctx.drawImage(canvas, pad, pad);
            var a = document.createElement('a');
            a.download = 'QR.png'; a.href = nc.toDataURL('image/png'); a.click();
        };
    }

    /* ──  SENTINEL OBSERVER ──  */
    /* index.php _hide('zap-removeQrCode') ➡ sentinel hide ➡ dono cards hide */
    var sentinel  = document.getElementById('zap-removeQrCode');
    var pcCard    = document.getElementById('t3-pc-qr-card');
    var mobCard   = document.getElementById('t3-mobile-qr-wrap');
    var dlBtn     = document.getElementById('zap-qrDownloadBtn');

    function syncQrVisibility() {
        if (!sentinel) return;
        var hidden = sentinel.style.display === 'none';
        if (pcCard)   pcCard.style.display   = hidden ? 'none' : '';
        if (mobCard)  mobCard.style.display  = hidden ? 'none' : '';
        if (dlBtn)    dlBtn.style.display     = hidden ? 'none' : '';
        if (mobileDl) mobileDl.style.display  = hidden ? 'none' : '';
    }

    if (sentinel) {
        new MutationObserver(syncQrVisibility)
            .observe(sentinel, { attributes: true, attributeFilter: ['style'] });
    }
    syncQrVisibility();

    applyContrast();
    new MutationObserver(function(ms) {
        ms.forEach(function(m) { if (m.attributeName === 'style') applyContrast(); });
    }).observe(document.documentElement, { attributes: true });

})();
</script>    </main>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script src="https://panel.mgamer.online/assets/brite-dialog.js"></script>
<script>
<?php
$cxr_dark_c5 = cxr_darken_hex($checkoutPrimaryColor, 0.55);
$cxr_dark_c6 = cxr_darken_hex($checkoutSecondaryColor, 0.55);
$serverDataArr = [
    "status" => "success",
    "payment" => "pending",
    "data" => [
        "templateId" => "template-3",
        "companyName" => $checkoutDisplayName,
        "companyLogo" => $checkoutLogoUrl ?: '',
        "colors" => [
            "color1" => $checkoutPrimaryColor,
            "color2" => $checkoutPrimaryColorDark,
            "color3" => $checkoutSecondaryColor,
            "color4" => $checkoutBgColor,
            "color5" => $cxr_dark_c5,
            "color6" => $cxr_dark_c6,
            "color7" => "#FFFFFF",
            "color8" => $checkoutPrimaryColor,
        ],
        "amount" => number_format((float)$amount, 2, '.', ''),
        "pay_amount" => number_format((float)$amount, 2, '.', ''),
        "autoCode" => "tr",
        "upi_id" => $upi_id,
        "encodedTxnId" => $cxrkalwaremark,
        "txnId" => $cxrkalwaremark,
        "txnRef" => $cxrbytectxnref,
        "remainingSeconds" => $expirySeconds,
    ],
];
?>
const serverData = <?php echo json_encode($serverDataArr); ?>;
let countdownTimer, redirectStatus='success', redirectReason = '', redirectURL=<?php echo json_encode($redirect_url_failed); ?>, orderId=<?php echo json_encode($order_id); ?>;
const REAL_REDIRECT_SUCCESS = <?php echo json_encode($redirect_url_success); ?>;
const REAL_REDIRECT_FAILED  = <?php echo json_encode($redirect_url_failed); ?>;
const REAL_ORDER_ID = <?php echo json_encode($order_id); ?>;
const REAL_TXN_ID = <?php echo json_encode($cxrkalwaremark); ?>;
const REAL_AMOUNT_DISPLAY = <?php echo json_encode('₹' . number_format((float)$amount, 2)); ?>;
const REAL_IS_TEST_ORDER = <?php echo $isTestOrder ? 'true' : 'false'; ?>;
const CHECKOUT_SHOW_GPAY = <?php echo $checkoutShowGpay ? 'true' : 'false'; ?>;
const CHECKOUT_SHOW_OTHER_UPI = <?php echo $checkoutShowOtherUpi ? 'true' : 'false'; ?>;
const CHECKOUT_SHOW_QR = <?php echo $checkoutShowQr ? 'true' : 'false'; ?>;
const SERVER_NAME_JS = <?php echo json_encode($_SERVER['SERVER_NAME']); ?>;

if (REAL_IS_TEST_ORDER) {
    document.addEventListener('DOMContentLoaded', function() {
        var fab = document.getElementById('testModeFab');
        if (fab) fab.classList.add('show');
    });
    if (document.readyState !== 'loading') {
        var fabNow = document.getElementById('testModeFab');
        if (fabNow) fabNow.classList.add('show');
    }
}

/*
 * OVERLAY CLICK BEHAVIOUR — 3 states:
 *   'none'       ➡ overlay click kuch nahi karega
 *   'ver-only'   ➡ sirf verification sheet close hoga (VPA waiting state)
 *   'all'        ➡ dono sheets close honge
 *
 * Default: 'none'
 * VPA pending state mein 'ver-only' set hoga
 * Result sheet aane ke baad 'none' set hoga — outside click disabled
 */
let overlayClickMode = 'none';

function hexToRgb(hex) {
    hex = hex.replace('#', '');
    if (hex.length === 3) hex = hex.split('').map(function(h){ return h+h; }).join('');
    return {
        r: parseInt(hex.substring(0,2), 16),
        g: parseInt(hex.substring(2,4), 16),
        b: parseInt(hex.substring(4,6), 16)
    };
}

function darkenHex(hex, amount) {
    var rgb = hexToRgb(hex);
    var r = Math.max(0, Math.round(rgb.r * (1 - amount / 100)));
    var g = Math.max(0, Math.round(rgb.g * (1 - amount / 100)));
    var b = Math.max(0, Math.round(rgb.b * (1 - amount / 100)));
    return '#' + [r,g,b].map(function(v){ return v.toString(16).padStart(2,'0'); }).join('');
}

function applyThemeColors(colors) {
    var c = [];
    if (Array.isArray(colors)) {
        c = colors;
    } else if (colors && typeof colors === 'object') {
        c = [
            colors.color1||'', colors.color2||'', colors.color3||'', colors.color4||'',
            colors.color5||'', colors.color6||'', colors.color7||'', colors.color8||''
        ];
    }
    if (c.filter(Boolean).length < 8) return;

    var r = document.documentElement;
    r.style.setProperty('--zap-c1', c[0]);
    r.style.setProperty('--zap-c2', c[1]);
    r.style.setProperty('--zap-c3', c[2]);
    r.style.setProperty('--zap-c4', c[3]);
    r.style.setProperty('--zap-c5', c[4]);
    r.style.setProperty('--zap-c6', c[5]);
    r.style.setProperty('--zap-c7', c[6]);
    r.style.setProperty('--zap-c8', c[7]);
    r.style.setProperty('--primary', c[7]);
    r.style.setProperty('--primary-light', darkenHex(c[7], 20));
}

/* ──  HELPERS ──  */
function pageLoaderHide() {
    document.getElementById('pageLoader').classList.add('hidden');
}

function showTimeoutScreen(title, text, iconClass, btnShow, type) {
    iconClass = iconClass || 'fa-exclamation-circle';
    btnShow   = (btnShow !== false);
    type      = type || 'error';
    const sc  = document.getElementById('timeoutScreen');
    document.getElementById('timeoutTitle').textContent = title;
    document.getElementById('timeoutText').textContent  = text;
    sc.querySelector('.timeout-icon').className = 'fas timeout-icon ' + iconClass;
    sc.classList.remove('status-success','status-pending','status-failed','status-error');
    sc.classList.add('status-' + type);
    document.getElementById('refreshButton').style.display = btnShow ? 'flex' : 'none';
    sc.classList.add('active');
}

document.getElementById('refreshButton').addEventListener('click', function() {
    document.getElementById('timeoutScreen').classList.remove('active');
    location.reload();
});

/* ──  GOLD COIN SHEET & OVERLAY ──  */
const coinSheet     = document.getElementById('coinSheet');
const overlay       = document.getElementById('sheetOverlay');
const coinWrapperEl = document.getElementById('coinWrapper');
const coinEl        = document.getElementById('coin');
const rupeeEl       = document.getElementById('rupeeSymbol');
const glowRingEl    = document.getElementById('glowRing');
const progressRingEl= document.getElementById('progressRing');
const checkEngraveEl= document.getElementById('checkEngrave');
const xEngraveEl    = document.getElementById('xEngrave');
const cnStatusEl    = document.getElementById('cnStatusText');
const cnSubEl       = document.getElementById('cnSubText');
const txContainerEl = document.getElementById('txContainer');
const btnContainerEl= document.getElementById('btnContainer');
const okButtonEl    = document.getElementById('okButton');

const coinCanvas = document.getElementById('coin-fx-canvas');
const coinCtx    = coinCanvas.getContext('2d');
let coinFxParticles = [];
let coinFxFrame = null;

function resizeCoinCanvas() {
    const rect = coinSheet.querySelector('.stage').getBoundingClientRect();
    coinCanvas.width  = rect.width  * devicePixelRatio;
    coinCanvas.height = rect.height * devicePixelRatio;
    coinCanvas.style.width  = rect.width + 'px';
    coinCanvas.style.height = rect.height + 'px';
    coinCtx.setTransform(1,0,0,1,0,0);
    coinCtx.scale(devicePixelRatio, devicePixelRatio);
}

function resetCoinVisuals() {
    coinEl.classList.remove('success', 'failed', 'shake');
    coinWrapperEl.classList.remove('result-success', 'result-failed');
    checkEngraveEl.classList.remove('show');
    xEngraveEl.classList.remove('show');
    checkEngraveEl.querySelector('svg').classList.remove('draw');
    xEngraveEl.querySelector('svg').classList.remove('draw');
    rupeeEl.style.opacity = '1';
    rupeeEl.style.transform = 'scale(1)';
    glowRingEl.classList.remove('active', 'ripple-success', 'ripple-failed');
    cnStatusEl.classList.remove('success', 'failed');
    txContainerEl.classList.remove('show');
    [...txContainerEl.children].forEach(function(row){ row.classList.remove('visible'); });
    btnContainerEl.classList.remove('show');
    btnContainerEl.style.display = 'none';
    okButtonEl.classList.remove('show');
    okButtonEl.style.display = 'none';
    coinFxParticles = [];
}

function openCoinSheet() {
    resizeCoinCanvas();
    overlay.classList.add('active');
    overlay.style.pointerEvents = 'auto';
    requestAnimationFrame(function(){ coinSheet.classList.add('open'); });
}

function closeCoinSheet() {
    coinSheet.classList.remove('open');
    stopCoinSpin();
    overlay.classList.remove('active');
    overlay.style.pointerEvents = 'none';
}

function startCoinSpin() {
    progressRingEl.classList.add('spinning');
}

function stopCoinSpin() {
    progressRingEl.classList.remove('spinning');
}

function showVerificationSheet(title, sub) {
    resetCoinVisuals();
    cnStatusEl.textContent = title;
    cnSubEl.textContent = sub;
    cnSubEl.style.display = '';
    openCoinSheet();
    startCoinSpin();
}

function hideVerificationSheet() {
    /* Same sheet morphs into the result view next, so just stop the spin
       loop here instead of closing - avoids a close-then-reopen flicker. */
    stopCoinSpin();
}

/* Overlay click — mode ke hisab se behave karta hai */
overlay.addEventListener('click', function() {
    if (overlayClickMode === 'ver-only') {
        closeCoinSheet();
        overlayClickMode = 'none';
    } else if (overlayClickMode === 'all') {
        closeCoinSheet();
        clearInterval(countdownTimer);
        overlayClickMode = 'none';
    }
    /* 'none' mode mein kuch nahi hota */
});

function spawnCoinParticles(colors, count) {
    const rect = coinSheet.querySelector('.stage').getBoundingClientRect();
    const cx = rect.width / 2, cy = rect.height / 2 - 4;
    for (let i = 0; i < count; i++) {
        const angle = Math.random() * 2 * Math.PI;
        const speed = 0.5 + Math.random() * 4;
        coinFxParticles.push({
            x: cx, y: cy,
            vx: Math.cos(angle) * speed,
            vy: Math.sin(angle) * speed - 1.2,
            life: 1, decay: 0.006 + Math.random() * 0.02,
            size: 2 + Math.random() * 5,
            color: colors[Math.floor(Math.random() * colors.length)],
            gravity: 0.035
        });
    }
    if (!coinFxFrame) animateCoinParticles();
}

function animateCoinParticles() {
    const rect = coinSheet.querySelector('.stage').getBoundingClientRect();
    coinCtx.clearRect(0, 0, rect.width, rect.height);
    for (let i = coinFxParticles.length - 1; i >= 0; i--) {
        const p = coinFxParticles[i];
        p.x += p.vx; p.y += p.vy; p.vy += p.gravity; p.life -= p.decay;
        if (p.life <= 0) { coinFxParticles.splice(i, 1); continue; }
        coinCtx.beginPath();
        coinCtx.arc(p.x, p.y, p.size * p.life, 0, Math.PI * 2);
        coinCtx.fillStyle = p.color;
        coinCtx.globalAlpha = p.life * 0.7;
        coinCtx.shadowColor = p.color;
        coinCtx.shadowBlur = 15;
        coinCtx.fill();
        coinCtx.shadowBlur = 0;
        coinCtx.globalAlpha = 1;
    }
    if (coinFxParticles.length > 0) {
        coinFxFrame = requestAnimationFrame(animateCoinParticles);
    } else {
        coinFxFrame = null;
    }
}

function morphCoin(status) {
    stopCoinSpin();

    rupeeEl.style.opacity = '0';
    rupeeEl.style.transform = 'scale(0.3)';

    if (status === 'success') {
        coinEl.classList.add('success');
        coinWrapperEl.classList.add('result-success');
        glowRingEl.classList.add('active', 'ripple-success');
        setTimeout(function() {
            checkEngraveEl.classList.add('show');
            setTimeout(function(){ checkEngraveEl.querySelector('svg').classList.add('draw'); }, 180);
        }, 200);
        spawnCoinParticles(['#1B8F5A', '#7FCFA6', '#C9971F', '#EFD98F', '#ffffff'], 40);
        cnStatusEl.classList.add('success');
    } else {
        coinEl.classList.add('failed');
        coinWrapperEl.classList.add('result-failed');
        glowRingEl.classList.add('active', 'ripple-failed');
        setTimeout(function() {
            xEngraveEl.classList.add('show');
            setTimeout(function(){ xEngraveEl.querySelector('svg').classList.add('draw'); }, 180);
        }, 200);
        spawnCoinParticles(['#D64545', '#EFA69A', '#B03636', '#F3D0CA'], 22);
        cnStatusEl.classList.add('failed');
    }
}

function revealCoinDetails() {
    txContainerEl.classList.add('show');
    const rows = [...txContainerEl.children];
    rows.forEach(function(row, i) {
        setTimeout(function(){ row.classList.add('visible'); }, 90 * (i + 1));
    });
    setTimeout(function() {
        btnContainerEl.style.display = '';
        okButtonEl.style.display = '';
        btnContainerEl.classList.add('show');
        okButtonEl.classList.add('show');
    }, 90 * rows.length + 150);
}

function showResultSheet(status, txn, val, amount, paidAt) {
    resetCoinVisuals();
    cnSubEl.style.display = 'none';

    if (status === 'success') {
        cnStatusEl.textContent = 'Payment Successful';
        document.getElementById('utrLabel').textContent = 'UTR Number';
        document.getElementById('utrRow').style.display = 'flex';
        document.getElementById('dateLabel').textContent = 'Paid At';
        document.getElementById('rowDate').style.display = 'flex';
        document.getElementById('utrNumber').textContent = val;
        document.getElementById('dateTime').textContent  = paidAt || '';
    } else if (status === 'failed') {
        cnStatusEl.textContent = 'Payment Failed';
        document.getElementById('utrLabel').textContent = 'Reason';
        document.getElementById('utrRow').style.display = 'flex';
        document.getElementById('utrNumber').textContent = val;
        document.getElementById('rowDate').style.display = 'none';
    } else {
        cnStatusEl.textContent = 'Payment Timeout';
        document.getElementById('utrLabel').textContent = 'Reason';
        document.getElementById('utrRow').style.display = 'flex';
        document.getElementById('utrNumber').textContent = val;
        document.getElementById('rowDate').style.display = 'none';
    }

    document.getElementById('txnId').textContent        = txn;
    document.getElementById('amountValue').textContent  = amount;
    document.getElementById('countdownNumber').textContent = '5';

    /* Result sheet pe overlay active rakho lekin click disable */
    overlay.classList.add('active');
    overlay.style.pointerEvents = 'auto';
    overlayClickMode = 'none'; /* Result sheet ke baad outside click BILKUL nahi */

    openCoinSheet();
    morphCoin(status === 'success' ? 'success' : 'failed');
    setTimeout(revealCoinDetails, 650);
    startCountdown();
}

function startCountdown() {
    var s = 5;
    clearInterval(countdownTimer);
    countdownTimer = setInterval(function() {
        s--;
        document.getElementById('countdownNumber').textContent = s;
        if (s <= 0) { clearInterval(countdownTimer); doRedirect(); }
    }, 1000);
}

document.getElementById('okButton').addEventListener('click', doRedirect);

function doRedirect() {

    var isAndroid = (typeof AndroidBridge !== 'undefined');
    if (isAndroid) {
        AndroidBridge.onPaymentResult(redirectStatus, orderId);
        return;
    }
 
    var isIOS = window.webkit &&
                window.webkit.messageHandlers &&
                window.webkit.messageHandlers.paymentResult;
    if (isIOS) {
        window.webkit.messageHandlers.paymentResult
              .postMessage({ status: redirectStatus, order_id: orderId });
        return;
    }
 
    var inIframe = (window.parent && window.parent !== window);

    if (inIframe) {

        try {
            if (window.parent.NeoPay && typeof window.parent.NeoPay._trigger === 'function') {
                window.parent.NeoPay._trigger(redirectStatus, orderId, redirectReason);
                return;
            }
            if (window.parent.ZapUPI && typeof window.parent.ZapUPI._trigger === 'function') {
                window.parent.ZapUPI._trigger(redirectStatus, orderId, redirectReason);
                return; 
            }
        } catch (e) {
          
        }

        window.parent.postMessage(
            { _neopay: true, _zapupi: true, type: redirectStatus, reason: redirectReason, orderId: orderId },
            '*'
        );
        return;
    }
 
    if (redirectStatus === 'success' && redirectURL && orderId) {
        var url = redirectURL.includes('?')
            ? redirectURL + '&order_id=' + encodeURIComponent(orderId)
            : redirectURL + '?order_id='  + encodeURIComponent(orderId);
        window.location.replace(url);
        return;
    }

    // On failure/timeout, send the customer back too (using the merchant's
    // redirect_url with a failed status flag) rather than leaving them
    // stranded on this page with a non-functional OK button/countdown.
    if (REAL_REDIRECT_FAILED && orderId) {
        var failUrl = REAL_REDIRECT_FAILED.includes('?')
            ? REAL_REDIRECT_FAILED + '&order_id=' + encodeURIComponent(orderId)
            : REAL_REDIRECT_FAILED + '?order_id='  + encodeURIComponent(orderId);
        window.location.replace(failUrl);
    }
}

function setCurrentDateTime() {
    return new Date().toLocaleDateString('en-IN', {
        day:'numeric', month:'short', year:'numeric', hour:'2-digit', minute:'2-digit'
    });
}

/* ──  TEST MODE ──  */
var testFab    = document.getElementById('testModeFab');
var testDialog = document.getElementById('testModeDialog');
var testOvl    = document.getElementById('testModeOverlay');

function openTest()  { testDialog.classList.add('active');    testOvl.classList.add('active'); }
function closeTest() { testDialog.classList.remove('active'); testOvl.classList.remove('active'); }

testFab.addEventListener('click', openTest);
testOvl.addEventListener('click', closeTest);

document.getElementById('testSuccess').addEventListener('click', function() {
    closeTest();
    stopAll();
    overlayClickMode = 'none';
    showVerificationSheet('Securing Payment', 'Processing test transaction');

    setTimeout(function() {
        var fd = new FormData();
        fd.append('order_id', REAL_ORDER_ID);
        fd.append('action', 'success');
        fetch('https://' + SERVER_NAME_JS + '/includes/test_action_submit.php', { method: 'POST', body: fd })
        .then(function(r) { return r.json(); })
        .finally(function() {
            hideVerificationSheet();
            redirectStatus = 'success';
            redirectReason = '';
            redirectURL    = REAL_REDIRECT_SUCCESS;
            showResultSheet('success', REAL_TXN_ID, 'TEST-MODE', REAL_AMOUNT_DISPLAY, setCurrentDateTime());
        });
    }, 1500);
});

document.getElementById('testFailed').addEventListener('click', function() {
    closeTest();
    stopAll();
    overlayClickMode = 'none';
    showVerificationSheet('Verifying Payment', 'Running failure test');

    setTimeout(function() {
        var fd = new FormData();
        fd.append('order_id', REAL_ORDER_ID);
        fd.append('action', 'failed');
        fetch('https://' + SERVER_NAME_JS + '/includes/test_action_submit.php', { method: 'POST', body: fd })
        .then(function(r) { return r.json(); })
        .finally(function() {
            hideVerificationSheet();
            redirectStatus = 'failed';
            redirectReason = '';
            redirectURL    = REAL_REDIRECT_FAILED;
            showResultSheet('failed', REAL_TXN_ID, 'Bank Declined (Test)', REAL_AMOUNT_DISPLAY);
        });
    }, 1500);
});

document.getElementById('testTimeout').addEventListener('click', function() {
    closeTest();
    stopAll();
    overlayClickMode = 'none';
    showVerificationSheet('Processing Payment', 'Testing timeout scenario');

    setTimeout(function() {
        var fd = new FormData();
        fd.append('order_id', REAL_ORDER_ID);
        fd.append('action', 'timeout');
        fetch('https://' + SERVER_NAME_JS + '/includes/test_action_submit.php', { method: 'POST', body: fd })
        .then(function(r) { return r.json(); })
        .finally(function() {
            hideVerificationSheet();
            redirectStatus = 'failed';
            redirectReason = 'timeout';
            redirectURL    = REAL_REDIRECT_FAILED;
            showResultSheet('timeout', REAL_TXN_ID, 'Payment Timeout (Test)', REAL_AMOUNT_DISPLAY);
        });
    }, 1500);
});

/* ──  MAIN INIT ──  */
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initPage);
} else {
    initPage();
}

function initPage() {
    setTimeout(function() {
        pageLoaderHide();

        if (serverData.status === 'error') {
            showTimeoutScreen('Error', serverData.message || 'Something went wrong', 'fa-exclamation-circle', false, 'error');
            return;
        }

        var statusMap = {
            success: { title:'Payment Success',  icon:'fa-check-circle',   type:'success' },
            failed:  { title:'Payment Failed',   icon:'fa-times-circle',   type:'failed'  },
            expire:  { title:'Order Expired',    icon:'fa-hourglass-end',  type:'failed'  },
            unknown: { title:'Payment Unknown',  icon:'fa-question-circle',type:'pending' }
        };

        var pay = serverData.payment || 'unknown';
        if (pay !== 'pending') {
            var cfg = statusMap[pay] || statusMap.unknown;
            showTimeoutScreen(cfg.title, serverData.message || '', cfg.icon, false, cfg.type);
            return;
        }

        var inp = serverData.data;

        /* 1. Colors */
        if (inp.colors) applyThemeColors(inp.colors);

        /* 2. Company info */
        var nameEl = document.getElementById('zap-companyName');
        var logoEl = document.getElementById('zap-companyLogo');
        var txnEl  = document.getElementById('zap-txnId');
        var amtEl  = document.getElementById('zap-payAmount');
        if (nameEl) nameEl.textContent = inp.companyName || '--';
        if (txnEl)  txnEl.textContent  = inp.txnId || '--';
        if (amtEl)  amtEl.textContent  = parseFloat(inp.pay_amount || 0).toFixed(2);
        if (logoEl && inp.companyLogo) {
            logoEl.src = inp.companyLogo;
            logoEl.onerror = function() { logoEl.style.display = 'none'; };
        }

        /* 3. Show/Hide */
        var isMobile = /Android|iPhone|iPad|iPod|IEMobile/i.test(navigator.userAgent);
        function _hide(id) { var el = document.getElementById(id); if (el) el.style.display = 'none'; }
        function _show(id) { var el = document.getElementById(id); if (el) el.style.display = '';    }

        /* QR Card - controlled by the merchant's Customize Page toggle */
        if (CHECKOUT_SHOW_QR) {
            _show('t3-pc-qr-card');
            _show('zap-removeQrCode2');
        } else {
            _hide('t3-pc-qr-card');
            _hide('zap-removeQrCode2');
        }

        /* Pay via App buttons - each controlled independently */
        if (CHECKOUT_SHOW_GPAY || CHECKOUT_SHOW_OTHER_UPI) {
            _show('zap-payButtons');
            if (!CHECKOUT_SHOW_GPAY) _hide('zap-gpayBtn');
            if (!CHECKOUT_SHOW_OTHER_UPI) _hide('zap-paytmBtn');
        } else {
            _hide('zap-payButtons');
        }

        /* VPA collect-request and self-serve UTR verification aren't wired to a
           real bank/PSP API yet, so they stay hidden rather than pretending to work. */
        _hide('zap-vpaSection');
        _hide('zap-utrSection');

        /* 4. QR Code — sirf ek baar */
        var qrPayload =
            'upi://pay' +
            '?pa='   + encodeURIComponent(inp.upi_id) +
            '&pn='  + encodeURIComponent(inp.companyName) +
            '&cu=INR' +
            '&am='  + encodeURIComponent(parseFloat(inp.pay_amount).toFixed(2)) +
            '&tn='  + encodeURIComponent(inp.txnId) +
            '&'     + encodeURIComponent(inp.autoCode) + '=' + encodeURIComponent(inp.txnRef);

        function _renderQR(targetId, qrText) {
            var el = document.getElementById(targetId);
            if (!el || el.dataset.done) return;
            el.dataset.done = '1';
            el.innerHTML = '';
            new QRCode(el, {
                text: qrText, width: 200, height: 200,
                colorDark: '#000000', colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H
            });
        }

        /* PC QR — har template ka primary target */
        _renderQR('zap-qrCode', qrPayload);

        /* Mobile QR — template-3 specific (dono mein fresh render) */
        _renderQR('t3-qrCode-mobile', qrPayload);

        /* 5. QR Download */
        var dlBtn = document.getElementById('zap-qrDownloadBtn');
        if (dlBtn) {
            dlBtn.onclick = function() {
                var canvas = document.querySelector('#zap-qrCode canvas');
                if (!canvas) return;
                var pad = 20;
                var nc  = document.createElement('canvas');
                nc.width  = canvas.width  + pad * 2;
                nc.height = canvas.height + pad * 2;
                var ctx = nc.getContext('2d');
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(0, 0, nc.width, nc.height);
                ctx.drawImage(canvas, pad, pad);
                var a = document.createElement('a');
                a.download = 'QR_' + inp.txnId + '.png';
                a.href = nc.toDataURL('image/png');
                a.click();
            };
        }

        /* 6. Timer */
        var remaining = parseInt(inp.remainingSeconds) || 0;
        if (remaining <= 5) {
            showTimeoutScreen('Timeout', 'This order has been timed out. Please create a new order.', 'fa-clock', false, 'failed');
        } else {
            startTimer(remaining);
        }

        /* 7. VPA Submit */
        var vpaBtn = document.getElementById('zap-vpaSubmitBtn');
        if (vpaBtn) {
            vpaBtn.onclick = function() {
                var vpaInp = document.getElementById('zap-vpaInput');
                var val    = vpaInp ? vpaInp.value.trim() : '';
                if (!val) {
                    BriteDialog.show({type:'error', title:'VPA Required', message:'Please enter your UPI VPA address.', confirmText:'OK'});
                    return;
                }
                if (!/^[a-zA-Z0-9.\-_]{2,}@[a-zA-Z]{2,}$/.test(val)) {
                    BriteDialog.show({type:'error', title:'Invalid VPA', message:'Please enter a valid UPI ID (example@bank).', confirmText:'Retry'});
                    return;
                }
                var ld = BriteDialogLoading.show({title:'Validating VPA', message:'Checking payment availability...', allowOutsideClick:false});

                fetch('https://pay.mgamer.online/pay/vpa-check-WkFQVVBSRjc5NTUwNjc3ODJBNzZDMg-' + encodeURIComponent(val), {method:'GET', cache:'no-store'})
                .then(function(r) { return r.json(); })
                .then(function(d) {
                    ld.close();
                    if (d.status === 'error') {
                        BriteDialog.show({type:'error', title:'Verification Failed', message:d.message||'Unable to verify VPA.', confirmText:'Retry'});
                        return;
                    }
                    if (d.status === 'success') {
                        /* VPA accept hua — verification sheet dikhao, OVERLAY CLICK ALLOWED (ver-only) */
                        overlayClickMode = 'ver-only';
                        showVerificationSheet('Securing Payment', 'Waiting for customer authorization');
                        return;
                    }
                    BriteDialog.show({type:'warning', title:'Pending Verification', message:'Payment verification pending. Please try again.', confirmText:'Retry'});
                })
                .catch(function() {
                    ld.close();
                    BriteDialog.show({type:'error', title:'Network Error', message:'Unable to connect. Please try again.', confirmText:'Retry'});
                });
            };
        }

        /* 8. UTR Submit */
        var utrBtn = document.getElementById('zap-utrSubmitBtn');
        if (utrBtn) {
            utrBtn.onclick = function() {
                var utrInp = document.getElementById('zap-utrInput');
                var val    = utrInp ? utrInp.value.trim() : '';
                if (!val) {
                    BriteDialog.show({type:'error', title:'UTR Required', message:'Please enter your UTR number.', confirmText:'OK'});
                    return;
                }
                if (!/^[0-9A-Za-z]{10,30}$/.test(val)) {
                    BriteDialog.show({type:'error', title:'Invalid UTR', message:'Please enter a valid UTR number.', confirmText:'Retry'});
                    return;
                }
                var ld = BriteDialogLoading.show({title:'Verifying Payment', message:'Checking transaction status...', allowOutsideClick:false});

                fetch('https://pay.mgamer.online/pay/utr-check-WkFQVVBSRjc5NTUwNjc3ODJBNzZDMg-' + encodeURIComponent(val), {method:'GET', cache:'no-store'})
                .then(function(r) { return r.json(); })
                .then(function(d) {
                    ld.close();
                    if (d.status === 'SUCCESS') {
                        stopAll();
                        overlayClickMode = 'none';
                        showVerificationSheet('Securing Payment', 'Fast-tracking bank verification');
                        setTimeout(function() {
                            hideVerificationSheet();
                            redirectStatus = 'success';
                            redirectReason = '';
                            redirectURL    = 'https://vipbothosting.online/plan_success.php?oid=ORD_1783937841_THJ5TDNF';
                            showResultSheet('success', 'ZAPUPIF7955067382A76C2', d.utr||'N/A', '₹49', d.paid_at||'N/A');
                        }, 2000);
                    } else if (d.status === 'FAILED') {
                        stopAll();
                        overlayClickMode = 'none';
                        showVerificationSheet('Securing Payment', 'Fast-tracking bank verification');
                        setTimeout(function() {
                            hideVerificationSheet();
                            redirectStatus = 'failed';
                            redirectReason = '';
                            redirectURL    = 'https://vipbothosting.online/plan_failed.php';
                            showResultSheet('failed', 'ZAPUPIF7955067382A76C2', d.reason||'N/A', '₹49');
                        }, 2000);
                    } else if (d.status === 'disable') {
                        BriteDialog.show({type:'info', title:'UTR Disabled', message:'UTR payments are not supported.', confirmText:'OK'});
                    } else {
                        BriteDialog.show({type:'warning', title:'Verification Pending', message:'Invalid UTR or payment still pending. Please try again.', confirmText:'Retry', showCancel:true, cancelText:'Cancel', allowOutsideClick:false});
                    }
                })
                .catch(function() {
                    ld.close();
                    BriteDialog.show({type:'error', title:'Network Error', message:'Unable to connect. Please try again.', confirmText:'Retry'});
                });
            };
        }

        /* 9. Intent buttons */
        var gb = document.getElementById('zap-gpayBtn');
        var pb = document.getElementById('zap-paytmBtn');
        var ub = document.getElementById('zap-upiBtn');
        
        if (gb) gb.onclick = function() {

            function shareQR(canvas) {
                canvas.toBlob(function(blob) {
                    var file = new File([blob], 'payment-qr.png', { type: 'image/png' });
                    if (navigator.share && navigator.canShare && navigator.canShare({ files: [file] })) {
                        navigator.share({
                            title: 'Scan to Pay',
                            files: [file]
                        }).catch(function() {
                            /* Share cancel ya fail — fallback */
                            window.location.href = qrPayload;
                        });
                    } else {
                        /* Share API support nahi — fallback */
                        window.location.href = qrPayload;
                    }
                }, 'image/png');
            }

            /* Pehle existing canvas try karo */
            var canvas = document.querySelector('#zap-qrCode canvas');
            if (canvas) {
                shareQR(canvas);
                return;
            }

            /* Canvas nahi mila — background mein generate karo */
            var tempDiv = document.createElement('div');
            tempDiv.style.cssText = 'position:absolute;left:-9999px;top:-9999px;';
            document.body.appendChild(tempDiv);

            new QRCode(tempDiv, {
                text: qrPayload,
                width: 200, height: 200,
                colorDark: '#000000', colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H
            });

            setTimeout(function() {
                var tempCanvas = tempDiv.querySelector('canvas');
                if (tempCanvas) {
                    shareQR(tempCanvas);
                } else {
                    window.location.href = qrPayload;
                }
                document.body.removeChild(tempDiv);
            }, 150);
        };

        if (pb) pb.onclick = function() {
            var paytmUrl = qrPayload
                .replace('upi://pay?pa=', 'paytmmp://cash_wallet?featuretype=money_transfer&pa=');
            window.location.href = paytmUrl;
        };

        if (ub) ub.onclick = function() { window.location.href = qrPayload; };

    }, 1500);

    /* SANDBOX */
    
    /* PREVIEW */
    
    /* NEOPAY design is light-themed end-to-end; dark-mode intentionally disabled */
}

/* ──  TIMER + POLLING ──  */
var timerInterval = null, paymentInterval = null, isReqInProgress = false, isCancelling = false;

function startTimer(seconds) {
    var t  = seconds;
    clearInterval(timerInterval); clearInterval(paymentInterval);

    timerInterval = setInterval(function() {
        /* Dono timers update karo — PC + Mobile */
        document.querySelectorAll('#zap-qrTimer').forEach(function(el) {
            el.textContent = String(Math.floor(t / 60)).padStart(2,'0') + ':' + String(t % 60).padStart(2,'0');
            el.classList.toggle('urgent', t <= 60);
        });

        if (t <= 0) {
            clearInterval(timerInterval); clearInterval(paymentInterval);
            overlayClickMode = 'none';
            showVerificationSheet('Processing Payment', 'Accelerated gateway connection');
            triggerRealTimeout();
        }
        t--;
    }, 1000);

    if ('On' === 'On' && !isCancelling) {
        paymentInterval = setInterval(checkPayment, 2000);
    }
}

function checkPayment() {
    if (isReqInProgress || isCancelling) return;
    isReqInProgress = true;
    fetch('https://' + SERVER_NAME_JS + '/order9/payment-status', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'byte_order_status=' + encodeURIComponent(REAL_TXN_ID),
        cache: 'no-store'
    })
    .then(function(r) { return r.text(); })
    .then(function(txt) {
        txt = (txt || '').trim();
        if (txt === 'success') {
            stopAll(); overlayClickMode = 'none';
            showVerificationSheet('Verifying Payment', 'Fast-tracking bank verification');
            setTimeout(function() {
                hideVerificationSheet();
                redirectStatus = 'success'; redirectReason = ''; redirectURL = REAL_REDIRECT_SUCCESS;
                showResultSheet('success', REAL_TXN_ID, 'N/A', REAL_AMOUNT_DISPLAY, setCurrentDateTime());
            }, 2000);
        } else if (txt === 'FAILURE') {
            stopAll(); overlayClickMode = 'none';
            showVerificationSheet('Verifying Payment', 'Fast-tracking bank verification');
            setTimeout(function() {
                hideVerificationSheet();
                redirectStatus = 'failed'; redirectReason = ''; redirectURL = REAL_REDIRECT_FAILED;
                showResultSheet('failed', REAL_TXN_ID, 'Payment not received', REAL_AMOUNT_DISPLAY);
            }, 2000);
        }
        /* else still PENDING - keep polling */
    })
    .catch(function(e) { console.error('API:', e); })
    .finally(function() { isReqInProgress = false; });
}

function triggerRealTimeout() {
    var fd = new FormData();
    fd.append('order_id', REAL_ORDER_ID);
    fd.append('action', 'timeout');
    fetch('https://' + SERVER_NAME_JS + (REAL_IS_TEST_ORDER ? '/includes/test_action_submit.php' : '/payment9/mark_failed.php'), {
        method: 'POST',
        body: REAL_IS_TEST_ORDER ? fd : ('byte_order_status=' + encodeURIComponent(REAL_TXN_ID)),
        headers: REAL_IS_TEST_ORDER ? undefined : { 'Content-Type': 'application/x-www-form-urlencoded' }
    }).catch(function(){}).finally(function() {
        hideVerificationSheet();
        redirectStatus = 'failed';
        redirectReason = 'timeout';
        redirectURL    = REAL_REDIRECT_FAILED;
        showResultSheet('timeout', REAL_TXN_ID, 'Payment Timeout', REAL_AMOUNT_DISPLAY);
    });
}

function stopAll() {
    clearInterval(timerInterval);
    clearInterval(paymentInterval);
}

/* ================================================================
   CANCEL PAYMENT BUTTON
   ================================================================ */
(function () {

    var cancelBtn = document.getElementById('cancelPaymentBtn');
    if (!cancelBtn) return;

    cancelBtn.addEventListener('click', function (e) {
        document.getElementById('cancelConfirmOverlay').classList.add('active');
        document.getElementById('cancelConfirmDialog').classList.add('active');
    });

    document.getElementById('cancelConfirmNo').addEventListener('click', function() {
        document.getElementById('cancelConfirmOverlay').classList.remove('active');
        document.getElementById('cancelConfirmDialog').classList.remove('active');
    });
    document.getElementById('cancelConfirmOverlay').addEventListener('click', function() {
        document.getElementById('cancelConfirmOverlay').classList.remove('active');
        document.getElementById('cancelConfirmDialog').classList.remove('active');
    });
    document.getElementById('cancelConfirmYes').addEventListener('click', function() {
        document.getElementById('cancelConfirmOverlay').classList.remove('active');
        document.getElementById('cancelConfirmDialog').classList.remove('active');
        doCancelPayment();
    });

    function resumeAutoCheck() {
        isCancelling = false;
        if ('On' === 'On') {
            clearInterval(paymentInterval);
            paymentInterval = setInterval(checkPayment, 2000);
        }
    }

    function doCancelPayment() {
        isCancelling = true;        
        clearInterval(paymentInterval);
        overlayClickMode = 'none';
        showVerificationSheet('Cancelling Payment', 'Please wait...');

        var ld = { close: function(){} }; // no-op - the verification sheet already shown covers this UI

        fetch('https://' + SERVER_NAME_JS + '/payment9/mark_failed.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'byte_order_status=' + encodeURIComponent(REAL_TXN_ID),
            cache: 'no-store'
        })
        .then(function (r) { return r.json(); })
        .then(function (d) {
            ld.close();
            if (d.status === 'SUCCESS') {
                stopAll();
                overlayClickMode = 'none';
                showVerificationSheet('Verifying Payment', 'Processing transaction status');
                setTimeout(function () {
                    hideVerificationSheet();
                    redirectStatus = 'success';
                    redirectReason = '';
                    redirectURL    = REAL_REDIRECT_SUCCESS;
                    showResultSheet('success', REAL_TXN_ID, d.utr || 'N/A', REAL_AMOUNT_DISPLAY, setCurrentDateTime());
                }, 1500);
            } else {
                stopAll();
                overlayClickMode = 'none';
                showVerificationSheet('Cancelling Payment', 'Processing your cancellation request');
                setTimeout(function () {
                    hideVerificationSheet();
                    redirectStatus = 'failed';
                    redirectReason = 'cancelled';
                    redirectURL    = REAL_REDIRECT_FAILED;
                    showResultSheet('failed', REAL_TXN_ID, 'Cancelled by user', REAL_AMOUNT_DISPLAY);
                }, 1500);
            }
        })
        .catch(function () {
            ld.close();
            resumeAutoCheck();
            if (window.confirm('Network Error\n\nUnable to connect. Try again?')) {
                doCancelPayment();
            }
        });
    }
})();


/* ================================================================
   MOBILE MINIMIZE FIX
   ================================================================ */
(function () {
    var _timerStartedAt   = 0;
    var _timerInitSeconds = 0;
    var _orig = startTimer;

    startTimer = function (seconds) {
        if (_timerStartedAt <= 0) {
            _timerStartedAt   = Date.now();
            _timerInitSeconds = seconds;
        }
        _orig(seconds);
    };

    document.addEventListener('visibilitychange', function () {
        if (document.visibilityState === 'hidden') {
            clearInterval(timerInterval);
            clearInterval(paymentInterval);
        } else if (document.visibilityState === 'visible') {
            if (_timerStartedAt <= 0) return;
            if (isCancelling) return;

            var elapsed      = Math.floor((Date.now() - _timerStartedAt) / 1000);
            var newRemaining = Math.max(0, _timerInitSeconds - elapsed);
            if (newRemaining <= 0) {
                stopAll();
                overlayClickMode = 'none';
                showVerificationSheet('Payment Timeout', 'Transaction time limit exceeded');
                triggerRealTimeout();
            } else {
                startTimer(newRemaining);
            }
        }
    });
})();
</script>
</body>
</html>

<script>
    document.addEventListener("contextmenu", e => e.preventDefault());
    document.onkeydown = function(e){
        if(e.keyCode===123) return false;
        if(e.ctrlKey && e.shiftKey && e.keyCode==73) return false;
        if(e.ctrlKey && e.keyCode==85) return false;
    };
    </script>