<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- QRCode.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <title>CWP SOLUTION Payments - Test Mode</title>
    <style>
        body {
            background: linear-gradient(to right, #764ba2, #667eea);
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
        }
        .qr-wrapper {
            padding: 10px;
            background: rgba(255,255,255,0.2);
            border-radius: 12px;
        }
        .qr-container {
            background: #fff;
            padding: 20px;
            box-shadow: 0 8px 16px rgba(0,0,0,0.1);
            text-align: center;
            width: 340px;
            border-radius: 8px;
        }
        .qr-title {
            background: #343a40;
            color: #fff;
            padding: 12px;
            font-size: 18px;
            border-radius: 8px 8px 0 0;
        }
        .qr-code {
            padding: 10px;
            margin: 20px auto;
            display: inline-block;
            border: 4px solid;
            border-image: linear-gradient(45deg, #f3ec78, #af4261) 1;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .amount {
            font-size: 17px;
            margin: 15px 0;
            color: #333;
        }
        .validity {
            font-size: 13px;
            color: #444;
        }
        .button-container {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        .pay-button, .save-button, .share-button {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            color: white;
            min-width: 140px;
        }
        .pay-button   { background: #4CAF50; }
        .save-button  { background: #2196F3; }
        .share-button { background: #673AB7; }
        @media (max-width: 480px) {
            .button-container { flex-direction: column; }
            .pay-button, .save-button, .share-button { width: 100%; }
        }
        .test-notice {
            background: #ffcc00;
            color: #000;
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 6px;
            font-weight: bold;
            font-size: 14px;
        }
        #qrcode { width: 260px; height: 260px; margin: 0 auto; }
    </style>
</head>
<body>

<?php
// ================= TESTING MODE =================
$testing_mode = true;

if ($testing_mode) {
    $order_id         = "TEST_" . rand(100000,999999);
    $amount           = 1.00;
    $user_token       = "test_user_abc123";
    $redirect_url     = "http://localhost/thank-you.php";
    $method           = "HDFC";
    $hdfc_txn         = "HDFC_" . time();
    $upi_id           = "yeamin87@ybl";          // ← YAHAN APNA REAL UPI ID DAAL DO
    $USERNAME         = "Test Merchant Rahul";
    $hdfc_description = "Test Payment " . date('Y-m-d H:i:s');

    echo '<div class="test-notice">TESTING MODE – QR browser mein bana raha hai</div>';
} else {
    // Real code (DB wala) – production mein yeh use hoga
    include "../pages/dbFunctions.php";
    include "../auth/config.php";
    include "../pages/dbInfo.php";

    $user_token = $_REQUEST["user_token"] ?? '';
    $data       = $_REQUEST["data"] ?? '';
    if (empty($user_token) || empty($data)) die("Missing parameters");

    $order_id = base64_decode($data);
    if ($order_id === false) die("Invalid data");

    $sql = "SELECT * FROM orders WHERE order_id = '$order_id'";
    $res = getXbyY($sql);
    if (empty($res)) die("Order not found");

    $amount       = $res[0]['amount'];
    $user_token   = $res[0]['user_token'];
    $redirect_url = $res[0]['redirect_url'] ?: 'https://' . $server . '/';
    $upiLink      = str_replace("https://", "", $res[0]['upiLink']);
    $method       = $res[0]['method'];
    $hdfc_txn     = $res[0]['HDFC_TXNID'];

    if ($method !== 'HDFC') { echo "error"; exit; }

    $sql = "SELECT * FROM hdfc WHERE user_token = '$user_token'";
    $res = getXbyY($sql);
    $upi_id = $res[0]['UPI'] ?? '';

    $sql = "SELECT * FROM users WHERE user_token = '$user_token'";
    $res = getXbyY($sql);
    $USERNAME = $res[0]['name'] ?? 'Merchant';

    $hdfc_description = rand(1,50) . uniqid() . time();
}

$upi_deep_link = "upi://pay?pa=$upi_id&am=$amount&pn=" . urlencode($USERNAME) . "&tn=" . urlencode($hdfc_description) . "&tr=$hdfc_txn";
?>

    <div class="qr-wrapper">
        <div class="qr-container">
            <div class="qr-title"><?php echo htmlspecialchars($USERNAME); ?></div>
            <div class="qr-code">
                <div id="qrcode"></div>
            </div>
            <div class="amount">Scan to pay ₹ <?php echo number_format($amount, 2); ?></div>

            <div class="button-container">
                <button class="pay-button"   onclick="payViaUPI()">Pay via UPI App</button>
                <button class="save-button"  onclick="downloadQR()">Save QR Code</button>
                <button class="share-button" onclick="shareQR()">Share QR</button>
            </div>

            <div class="validity">Valid until: <span id="timeout"></span></div>
        </div>
    </div>

    <script>
        const upiLink   = "<?php echo addslashes($upi_deep_link); ?>";
        const orderId   = "<?php echo $order_id; ?>";
        const amount    = <?php echo $amount; ?>;
        const username  = "<?php echo addslashes($USERNAME); ?>";
        const redirect  = "<?php echo addslashes($redirect_url); ?>";

        // QR generate
        new QRCode(document.getElementById("qrcode"), {
            text: upiLink,
            width: 260,
            height: 260,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.H
        });

        function payViaUPI() {
            window.location.href = upiLink;
        }

        function downloadQR() {
            const canvas = document.querySelector('#qrcode canvas');
            if (!canvas) return Swal.fire({title:'Error', text:'QR nahi bana', icon:'error'});

            const link = document.createElement('a');
            link.download = `UPI_QR_${orderId}.png`;
            link.href = canvas.toDataURL('image/png');
            link.click();

            Swal.fire({title:'Saved!', text:'QR download ho gaya', icon:'success', timer:1800});
        }

        async function shareQR() {
            const canvas = document.querySelector('#qrcode canvas');
            if (!canvas) return Swal.fire({title:'Error', text:'QR nahi bana', icon:'error'});

            try {
                const dataURL = canvas.toDataURL('image/png');
                const blob = await (await fetch(dataURL)).blob();
                const file = new File([blob], `UPI_QR_${orderId}.png`, {type: 'image/png'});

                if (navigator.share && navigator.canShare && navigator.canShare({files: [file]})) {
                    await navigator.share({
                        files: [file],
                        title: 'UPI Payment QR Code',
                        text: `Pay ₹${amount} to ${username}\nScan kar ke payment karo!`
                    });
                    Swal.fire({title:'Shared!', text:'QR share ho gaya', icon:'success', timer:2000});
                } else {
                    // Fallback
                    downloadQR();
                    Swal.fire({
                        title: 'Share nahi hua',
                        text: 'Browser share support nahi karta → QR download ho gaya, ab gallery se share karo',
                        icon: 'info'
                    });
                }
            } catch (err) {
                console.error(err);
                downloadQR();
                Swal.fire({
                    title: 'Share fail',
                    text: 'QR download ho gaya → manually share kar sakte ho',
                    icon: 'warning'
                });
            }
        }

        // 5 min countdown
        function upiCountdown(elm, minute, second) {
            document.getElementById(elm).innerHTML = `${minute}:${second.toString().padStart(2,'0')}`;
            const timer = setInterval(() => {
                second--;
                if (second < 0) { second = 59; minute--; }
                if (minute < 0) {
                    clearInterval(timer);
                    Swal.fire({title:'Timeout!', text:'Time khatam', icon:'error'})
                        .then(() => window.location.href = redirect);
                    return;
                }
                document.getElementById(elm).innerHTML = `${minute}:${second.toString().padStart(2,'0')}`;
            }, 1000);
        }
        upiCountdown("timeout", 5, 0);

        // Payment status (testing mein dummy)
        setInterval(() => {
            console.log("[TEST MODE] Payment check skip");
        }, 2000);
    </script>
</body>
</html>