<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="robots" content="nofollow, noindex">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Include SweetAlert2 and jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <title>kajal24pay. Payments</title>
   <style>
        body {
            background: #667eea;
            background: -webkit-linear-gradient(to right, #764ba2, #667eea);
            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: 300px;
            border-radius: 8px;
        }
        
        .qr-title {
            background: #343a40;
            color: #fff;
            padding: 10px;
            font-size: 18px;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
        }
        
        .qr-code {
            padding: 10px;
            margin: 20px auto;
            display: inline-block;
            border: 4px solid; /* Required for gradient borders */
            border-image-slice: 1;
            border-width: 4px;
            border-image-source: linear-gradient(45deg, #f3ec78, #af4261); /* Gradient border */
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        
        .amount {
            font-size: 16px;
            margin: 20px 0;
            color: #343a40;
        }
        
        .validity {
            font-size: 12px;
            color: #000000; /* Changing color to black */
            /* Other properties remain unchanged */
        }

        .pay-button {
            display: none;
        }
    </style>
</head>
<?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]['name'];

$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'];





// Define the API endpoint
$url = 'https://miniapi.in/api/hdfc/upiqr';

// Create the payload array
$payloadArray = array(
    "seassion" => $hdfc_seassion,
    "tidlist" => $tidList,
    "amount" => $amount,
    "description" => $description,
    "cnumber" => $cnumber,
    "apptxnidd" => $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, http_build_query($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);

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

if ($jsonResponse['status']==true){

    $base64Image=$jsonResponse['base64'];
}

else {

    echo "merchant session invalid";
}




 


?>

<body>
    <div class="qr-wrapper">
        <div class="qr-container">
            <div class="qr-title"><?php echo htmlspecialchars($USERNAME); ?></div>
            <div class="qr-code">
                <?php if ($base64Image): ?>
                    <img src="data:image/png;base64,<?php echo $base64Image; ?>" alt="QR Code" style="max-width: 100%;">
                <?php else: ?>
                    <p>Error generating QR code.</p>
                <?php endif; ?>
            </div>
            <div class="amount">Scan to pay ₹ <?php echo number_format($amount, 2); ?></div>
            <button class="pay-button" onclick="payViaUPI()">Pay via UPI App</button>
            <div class="validity">Valid until: <span id="timeout"></span></div>
        </div>
    </div>

    <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://pephon.printsarvice.site/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>
</body>
</html>
