<?php

// Security headers
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'https://cdn.jsdelivr.net' 'https://code.jquery.com'; img-src 'self' https://api.qrserver.com; style-src 'self'; object-src 'none'");
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: SAMEORIGIN");
header("Strict-Transport-Security: max-age=31536000; includeSubDomains");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: no-referrer-when-downgrade");
header("Permissions-Policy: geolocation='self'; microphone=()");



function RandomNumber($length)
{
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= mt_rand(0, 9);
    }
    return $str;
}



// 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 . 'auth/config.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)) {
  
    echo "Token has expired";
    exit;
}

$sql_p = "SELECT * FROM orders WHERE order_id='$order_id'";
$res_p = getXbyY($sql_p);



$amount = $res_p[0]['amount'];
$user_token = $res_p[0]['user_token'];
$redirect_url = $res_p[0]['redirect_url'];
$cnumber = $res_p[0]['customer_mobile'];



$apptxnidd = "2560".RandomNumber(7).time();
$description = RandomNumber(18);


// Update the HDFC_TXNID and description in the orders table
$update_sql = "UPDATE orders SET HDFC_TXNID='$apptxnidd', description='$description' WHERE order_id='$order_id'";
if ($conn->query($update_sql) === TRUE) {
    //echo "Record updated successfully";
}



$sql_p = "SELECT * FROM users WHERE user_token='$user_token'";
$res_p = getXbyY($sql_p);



$USERNAME = $res_p[0]['company'];

$sql_p = "SELECT * FROM hdfc WHERE user_token='$user_token'";
$res_p = getXbyY($sql_p);



$hdfc_seassion = $res_p[0]['seassion'];  // Column name is 'seassion' despite the spelling mistake
$tidList = $res_p[0]['tidlist'];


// $url = 'https://' . $_SERVER["SERVER_NAME"] . '/payment/sys/';

// // Data to be sent in the POST request
// $data = [
//     'data' => "upi://pay?pa=$upi_id&am=$amount&pn=$unitId&tn=$apptxnidd&tr=$description",
//     'ecc' => 'M',
//     'size' => 8
// ];

// // 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);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_HTTPHEADER, [
//     'Content-Type: application/json',
//     'API-Key: ' . $apiKey ,
//     'Referer: ' . $lnk // Add API key to the headers
// ]);
// curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

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

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

//     if (isset($result['error'])) {
//         echo 'Error: ' . $result['error'];
//     } else {
//         $qrCodeBase64 = $result['qr_code'];
//         // echo '<img src="' . $qrCodeBase64 . '" alt="QR Code" />';
//     }
// }

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




// Define the API endpoint
$url = 'https://imbx.in/secret/hdfc_qr';

// Create the payload array
$payloadArray = array(
    "session_id" => $hdfc_seassion,
    "tid_list" => $tidList,
    "amount" => $amount,
    "description" => $description,
    "customer_number" => $cnumber,
    "apptxn_id" => $apptxnidd
);

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

// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payloadArray));

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

// Check for cURL errors
if (curl_errno($ch)) {
    echo 'cURL Error: ' . curl_error($ch);
} else {
    // Print the response from the API
}

// Close cURL session
curl_close($ch);

// echo json_encode($payloadArray);
// exit;

// Decode the JSON response
$jsonResponse = json_decode($response, true);

if (isset($jsonResponse['qr_code'])){

    // $base64Image=$jsonResponse['qr_code'];
    $qrCodeBase64=$jsonResponse['qr_code'];
}


?>


    
<!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;
            }
        }
        
        
    .method-header {
    background-color: #2C3E88;
    color: white;
    padding: 10px 15px;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
}

input.form-control {
    width: 89%;
    border: 1px solid #080832;
    outline: none;
    padding: 10px 15px;
    border-radius: 5px;
    box-shadow: 1px 13px 20px -14px rgba(000, 000, 000, 0.6);
}
</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 $USERNAME?></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>
                
                <?php if ($qrCodeBase64): ?>
                <p class="qr-instruction">Use Mobile Scan QR to Pay</p>
                <?php endif; ?>

            </div>

            <div class="qr-code">
                <?php if ($qrCodeBase64): ?>
                     <img id="qr-image" src="<?php echo $qrCodeBase64; ?>" alt="QR Code"> 
                <?php else: ?>
                    <!--<p>Error generating QR code.</p>-->
                <?php endif; ?>

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


            
            
    <div class="payment-method">
      <div class="method-header">UPi Request</div>
      <form action="https://<?= $_SERVER["SERVER_NAME"] ?>/payment/instant-pay/hdfcupipay/<?php echo $link_token; ?>" method="post">
          <input type="hidden" name="payzero_XsRFtoken" class="form-control" value="<?php echo $nonce; ?>">
    <!-- Other input fields -->
    <input type="text" name="upiId" placeholder="Enter Your UPI Id " class="form-control">
    <input type="hidden" name="TransactionId" value="<?php echo $payzerokalwaremark; ?>">
     <button class="payment-btn" type="submit" name="subupireq" class="btn-special" style="display:flex; justify-content: center; background-color: #0DB561; font-weight: 700; color: white; margin: 8px auto; border-color: #0DB561">Pay ₹ <?php echo number_format($amount, 2); ?></button>
</form>
    </div>
    
    
            <div class="payment-method mobile-only">
                <p>Choose a Payment Method To Pay</p>
                <div class="buttons">

                    <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>
                </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>


    </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>
        var paymentProcessed = false;
        var interval;

        function startTimer(duration, display) {
            var timer = duration, minutes, seconds;
            interval = 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(interval);
                }
            }, 1000);
        }

        function check() {
            if (paymentProcessed || !interval) {
                clearInterval(interval); 
                return;
            }

            $.ajax({
                type: 'post',
                url: 'https://<?php echo $_SERVER["SERVER_NAME"] ?>/order/payment-status',
                data: { order_id: '<?php echo $order_id ?>' },
                dataType: 'text',
                success: function (data) {
                    if (data === 'success') {
                        paymentProcessed = true;
                        Swal.fire({
                            title: 'Payment Received Successfully ✅',
                            text: 'Please wait...',
                            icon: 'success'
                        }).then(() => {
                            window.location.href = "<?php echo $redirect_url ?>";
                        });
                    } else if (data === 'FAILURE' || data === 'FAILED') {
                        paymentProcessed = true;
                        Swal.fire({
                            title: 'Payment Failed',
                            icon: 'error'
                        }).then(() => {
                            window.location.href = "<?php echo $redirect_url ?>";
                        });
                    }
                },
                error: function (xhr, status, error) {
                    console.log('AJAX Error:', status, error);
                }
            });
        }

        window.onload = function () {
            var fiveMinutes = 60 * 5,
                display = document.querySelector('#timeout');
            startTimer(fiveMinutes, display);
            check();
            interval = setInterval(check, 5000);
        };
    </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>
