<?php

date_default_timezone_set("Asia/Kolkata");

define('ROOT_DIR', realpath(dirname(__FILE__)) . '/../');
include ROOT_DIR . 'pages/dbFunctions.php';
include ROOT_DIR . 'pages/dbInfo.php';
include ROOT_DIR . 'auth/config.php';

$link_token = ($_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) {
    echo "Token not found or expired";
    exit;
}

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

if (($current_time - $created_at) > (5 * 60)) {
    echo "Token has expired";
    exit;
}

$slq_p = "SELECT * FROM orders where order_id='$order_id'";
$res_p = getXbyY($slq_p);    
$amount = $res_p[0]['amount'];
$user_token = $res_p[0]['user_token'];
$redirect_url = $res_p[0]['redirect_url'];
$payzerokalwaremark = $res_p[0]['byteTransactionId'];
$payzerobytectxnref = $res_p[0]['paytm_txn_ref'];
$payzerouser_id = $res_p[0]['user_id'];

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

$slq_p = "SELECT * FROM mobikwik_token where user_token='$user_token'";
$res_p = getXbyY($slq_p);
$upi_id = $res_p[0]['merchant_upi'];

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

$asdasd23 = "ARC" . rand(111, 999) . time() . rand(1, 100);

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

$paytmintent = "paytmmp://cash_wallet?pa=$upi_id&pn=$unitId&am=$amount&cu=INR&tn=$payzerobytectxnref&tr=$payzerobytectxnref&mc=4722&&sign=AAuN7izDWN5cb8A5scnUiNME+LkZqI2DWgkXlN1McoP6WZABa/KkFTiLvuPRP6/nWK8BPg/rPhb+u4QMrUEX10UsANTDbJaALcSM9b8Wk218X+55T/zOzb7xoiB+BcX8yYuYayELImXJHIgL/c7nkAnHrwUCmbM97nRbCVVRvU0ku3Tr&featuretype=money_transfer";

// Redirect URL for payment confirmation
$payment_verification_url = "https://".$_SERVER["SERVER_NAME"]."/payment8/verify/" . ($link_token);

// Your custom QR code API URL
$url = 'https://' . $_SERVER["SERVER_NAME"] . '/payment/sys/';

// Data to be sent in the POST request
$data = [
    'data' => $orders, // The data to encode in the QR
    'ecc' => 'M',      // Error correction level ('L', 'M', 'Q', 'H')
    'size' => 8        // Size of the QR code
];

// Convert the data array into a JSON string
$jsonData = json_encode($data);

// Initialize cURL session
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_POST, true);  // Set method to POST
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);  // Set content type to JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);  // Send data as JSON

// Execute the cURL request
$response = curl_exec($ch);

// Check for errors
if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
} else {
    // Decode the JSON response
    $result = json_decode($response, true);

    // Check if there is an error in the response
    if (isset($result['error'])) {
        echo 'Error: ' . $result['error'];
    } else {
        // Success! The QR code is in base64 format.
        $qrCodeBase64 = $result['qr_code'];

        // Display the QR code image in the browser
        // echo '<img src="' . $qrCodeBase64 . '" alt="QR Code" />';
    }
}

// Close the cURL session
curl_close($ch);

?>
    
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pay0 Payment Page</title>
    <link rel="stylesheet" href="/../common/css.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
         <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>
<style>
    .box-container {
        width: 350px;
        margin: 20px auto;
        padding: 20px;
        border: 1px solid #dcdcdc;
        border-radius: 8px;
        background-color: #fff;
        text-align: center;
        box-sizing: border-box;

    }

    .box-title {
        font-size: 20px;
        color: #333;
        margin-bottom: 15px;
        font-weight: bold;
    }

    .logo1 {
        max-width: 100%;
        height: auto;
        margin-bottom: 15px;
    }

    .box-message {
        color: red;
        font-size: 16px;
        font-weight: normal;
        margin-top: 15px;
    }
        
         @media (min-width: 768px) {
            .mobile-only {
                display: none;
            }
        }
</style>

<body style="
    background-color: #272727;
    display: flex;
    align-items: center;
    min-height: 100dvh;">

    <div style="
    background-color: #ffffff;
    width: 100%;
    position: relative;
    max-width: 360px;
    height: auto;
    min-height: auto;
    align-items: center;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
    margin: 24px auto;
    box-sizing: border-box;
    border-radius: 12px">


        <!-- Header -->
        <header style="
    border-top-left-radius: 12px;
    border-top-right-radius: 12px;">
            <h1><?php echo $unitId?></h1>
            <span class="timer" id="timeout"></span>
        </header>

        <!-- Main Content -->
        <main>
            <!-- Amount Payable -->
            <div class="amount-payable">
                <p>Amount Payable</p>
                <h2 class="amount">₹<?php echo $amount?></h2>
                <p class="qr-instruction">Use Mobile Scan QR to Pay</p>

            </div>

            <div class="qr-code">
                <img id="qr-image"
                    src="<?php echo $qrCodeBase64; ?>"
                    alt="QR Code">

                <p class="qr-instruction-HDFC">Do Not Refresh The Page.</p>
            </div>


        <button class="payment-btn" onclick="payViaUPI()" style="display:flex; justify-content: center; background-color: #0DB561; font-weight: 700; color: white; margin: 20px auto; border-color: #0DB561">Confirm Payment</button>

            <div class="payment-method mobile-only">
                <p>Choose a Payment Method To Pay</p>
                <div class="buttons">
                    <button class="payment-btn"
                        onclick="window.location.href='<?=$paytmintent?>';">
                        <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUEjY90pS-UfgHJU4glc8Aiupp1xCn_jcvRQ&s"
                            alt="Paytm">
                        Paytm
                    </button>


                    <button class="payment-btn" id="shareQrButton" onclick="shareImage();">
                        <img src="https://i.pinimg.com/originals/60/5a/bd/605abdb7af3405c6b20a426b1e128322.png"
                            alt="PhonePe">
                        Google Pay
                    </button>
                    <!--<button class="payment-btn"-->
                    <!--    onclick="window.location.href='';">-->
                    <!--    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcROhknVR_0wMU1TEgiJRQ_db2ej3WADPYtF8nj9xZhTNbUD7aBYCNstoXYrE5kSMttYnbc&usqp=CAU"-->
                    <!--        alt="UPI">-->
                    <!--    Any UPI Apps-->
                    <!--</button>-->
                </div>
            </div>




        </main>




        <!-- Footer -->
        <footer>
            <div class="footer-content">
                <img src="https://cdn-icons-png.flaticon.com/512/10703/10703030.png" alt="Secure Payment">
                <p>This Payment is Secured by Pay0.</p>
            </div>
        </footer>

        <!-- Modal -->
        <div id="guideModal" class="modal">
            <div class="modal-content">
                <img src="https://upipayments.co.in/wp-content/uploads/2023/12/google-pay-UPI-Transaction-ID-1.png"
                    alt="Guide Image">
                <button class="close-btn" onclick="closeModal()">Close</button>
            </div>
        </div>


    </div>

    <!-- Countdown Timer Script -->
    <script>
        async function shareImage() {
            const imgElement = document.getElementById('qr-image');
            const response = await fetch(imgElement.src);
            const blob = await response.blob();
            const file = new File([blob], "pay0_QR.png", { type: blob.type });

            if (navigator.canShare && navigator.canShare({ files: [file] })) {
                await navigator.share({
                    title: "Pay via Google Pay",
                    text: "Scan this QR code to pay via Google Pay.",
                    files: [file],
                });
            } else {
                alert("Sharing not supported, try downloading the QR Code.");
            }
        }
    </script>
    <script>
        function payViaUPI() {
            window.location.href = "<?php echo $payment_verification_url; ?>";
        }

        window.onload = function () {
            var fiveMinutes = 60 * 5,
                display = document.querySelector('#timeout');
            startTimer(fiveMinutes, display);
        };

        function startTimer(duration, display) {
            var timer = duration, minutes, seconds;
            setInterval(function () {
                minutes = parseInt(timer / 60, 10);
                seconds = parseInt(timer % 60, 10);

                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;

                display.textContent = minutes + ":" + seconds;

                if (--timer < 0) {
                    clearInterval(this);
                }
            }, 1000);
        }
    </script>
    <script disable-devtool-auto="" src="https://<?php echo $_SERVER["SERVER_NAME"] ?>/common/disable-devtool.js" data-url="https://www.google.com/"></script> 
</body>
</html>
