<?php include("../serive/samparka.php"); ?>
<?php 
// Process amount parameter
if(isset($_GET['amount'])){
    $ramt = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['amount']));
} else {
    $ramt = 0;
}

// Format amount with two decimal places
$dot_pos = strpos($ramt, '.');
if ($dot_pos === false) {
    $ramt = $ramt . '.00';
} else {
    $after_dot = substr($ramt, $dot_pos + 1);
    $after_dot_length = strlen($after_dot);
    if ($after_dot_length > 2) {
        $after_dot = substr($after_dot, 0, 2);
        $ramt = substr($ramt, 0, $dot_pos + 1) . $after_dot;
    } elseif ($after_dot_length < 2) {
        $zeros_to_add = 2 - $after_dot_length;
        $ramt = $ramt . str_repeat('0', $zeros_to_add);
    }
}

// Generate serial number
$date = date("Ymd");
$time = time();
$serial = 'P' . $date . $time . rand(1000,9999);

// Get other parameters
$tyid = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['tyid']));
$uid = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['uid']));
$sign = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['sign']));
$urlInfo = htmlspecialchars(mysqli_real_escape_string($conn, $_GET['urlInfo']));

// Fetch UPI details
$s_upi = "SELECT maulya FROM deyya WHERE sthiti='1'";
$r_upi = mysqli_query($conn, $s_upi);
$f_upi = mysqli_fetch_array($r_upi);
$upi_id = $f_upi['maulya'];

// Fetch QR code image
$selectupi_two = mysqli_query($conn, "select * from `images` where `status`=1");
$selectupiresult_two = mysqli_fetch_array($selectupi_two);
?>

<?php
// Security validation
$res = [
    'code' => 405,
    'message' => 'Illegal access!',
];

if (isset($_GET['tyid']) && isset($_GET['amount']) && isset($_GET['uid']) && isset($_GET['sign']) && isset($_GET['urlInfo'])) {
    $userId = $uid;
    $userPhoto = '1';
    
    $numquery = "SELECT mobile, codechorkamukala FROM shonu_subjects WHERE id = ".$userId;
    $numresult = $conn->query($numquery);
    $numarr = mysqli_fetch_array($numresult);
    
    $userName = '91'.$numarr['mobile'];
    $nickName = $numarr['codechorkamukala'];
    
    $creaquery = "SELECT createdate FROM shonu_subjects WHERE id = ".$userId;
    $crearesult = $conn->query($creaquery);
    $creaarr = mysqli_fetch_array($crearesult);
    
    $knbdstr = '{"userId":'.$userId.',"userPhoto":"'.$userPhoto.'","userName":'.$userName.',"nickName":"'.$nickName.'","createdate":"'.$creaarr['createdate'].'"}';
    $shonusign = strtoupper(hash('sha256', $knbdstr));
    
    $urlarr = explode(",", $urlInfo);
    $theirurl = $urlarr[0];
    $myurl = 'https://jaiclub67.com';
    
    if($shonusign == $sign && $theirurl == $myurl){
?>
<!DOCTYPE html>
<html>
<head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
    <title>UPIPAY Checkout</title>
    <meta content="width=device-width,initial-scale=1,user-scalable=0" name="viewport">
    <link rel="icon" href="/favicon.ico">
    <!-- Tailwind CSS CDN -->
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <script src="assets/js/wepay/jquery-2.2.4.min.js"></script>
    <script src="assets/js/wepay/clipboard.min.js"></script>
    <script src="assets/js/wepay/layer.js"></script>
    <link rel="stylesheet" href="assets/css/wepay/layer.css" id="layuicss-layer">
    <style type="text/css">
        /* Custom Tailwind overrides and animations */
        @keyframes vibrate {
            0%, 100% { transform: translate(0, 0); }
            25% { transform: translate(-2px, -2px); }
            50% { transform: translate(2px, 2px); }
            75% { transform: translate(-2px, 2px); }
        }
        .vibrating {
            animation: vibrate 0.3s infinite;
        }
        
        /* Custom styles */
        body {
            font-family: Arial, sans-serif;
        }
        
        .qr-code-container {
            display: inline-block;
            padding: 10px;
            background-color: #fff;
            border: 2px outset #ccc;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        
        .instruction-container {
            padding: 20px;
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin: 20px auto;
            font-family: Arial, sans-serif;
        }

        .instruction-title {
            font-size: 1.2em;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .instruction-list {
            list-style-type: decimal;
            padding-left: 20px;
        }

        .instruction-item {
            margin-bottom: 10px;
        }

        .highlight {
            font-weight: bold;
            color: red;
        }
        
        .utr-input-container {
            position: relative;
            border: 2px solid #ff00ff;
            background-color: #fff;
            border-radius: 8px;
            padding: 10px;
            box-shadow: 0 0 10px rgba(255, 0, 255, 0.5);
        }
        
        .utr-label {
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 18px;
            color: #000;
            pointer-events: none;
        }
        
        .utr-input {
            border: none;
            outline: none;
            text-align: left;
            font-size: 18px;
            color: #0000FF;
            background-color: transparent;
            margin-left: 70px;
            width: calc(100% - 70px);
        }
    </style>
</head>
<body class="bg-gray-100">
<div id="wraper_all" class="max-w-2xl mx-auto bg-white rounded-lg shadow-lg p-4 sm:p-6 mt-4">
    <!-- Header -->
    <div class="flex items-center justify-center bg-gradient-to-r from-green-400 to-green-600 text-white text-2xl font-bold rounded-t-lg h-12">
        <span>UPI PAYMENT</span>
    </div>
    
    <!-- Transfer Amount -->
    <div id="copyAmount" class="flex items-center justify-between bg-gray-50 rounded-lg p-4 my-4">
        <div class="text-lg font-semibold text-gray-700">Payment Amount👉</div>
        <div class="text-2xl font-bold text-gray-900">
            <span>₹</span> 
            <span class="moeny"><?php echo $ramt; ?></span> 
        </div>
    </div>
    
    <!-- Countdown Timer -->
    <div id="timer" class="text-center text-red-500 font-semibold mb-4">
        Time remaining: <span id="countdown">10:00</span>
    </div>
    
    <!-- Step 1: UPI Payment -->
    <div class="mt-4">
        <div class="text-red-500 font-bold text-center">
            Step 1: Pay&nbsp;&nbsp;
            <span class="text-purple-500">₹<?php echo $ramt; ?> to UPI ID</span>
            <br>
            <span class="text-sm text-gray-600">Scan the QR Code or use your favorite UPI app and copy the UTR code after payment</span>
        </div>
        
        <div class="flex flex-col items-center mt-4">
            <div class="qr-code-container">
                <img src="../images/<?php echo $selectupiresult_two['filename']; ?>" id="qrCodeImage" class="w-48 h-48">
            </div>
            
            <a href="../images/<?php echo $selectupiresult_two['filename']; ?>" download="QRCodeImage" class="mt-2 bg-blue-500 text-white font-medium py-2 px-4 rounded-lg hover:bg-blue-600 transition">
                ⬇️ Download QR Code
            </a>
            
            <div class="flex items-center justify-between mt-4 p-2 bg-yellow-100 border border-gray-300 rounded-lg w-full">
                <span id="upi" class="text-gray-800 font-medium"><?php echo $upi_id; ?></span>
                <button id="btncopy" class="bg-blue-500 text-white font-medium py-1 px-3 rounded-lg hover:bg-blue-600 transition">
                    🔗 COPY
                </button>
            </div>
        </div>
    </div>
    
    <br>
    
    <!-- Payment Options -->
    <p class="text-lg font-bold text-gray-800">Choose Your UPI APP</p>
    <div class="gap-4 p-4 bg-gray-50 rounded-lg">
        <a href="upi://pay?pa=<?php echo urlencode($upi_id); ?>&am=<?php echo $ramt; ?>&cu=INR&tn=UPIPAY <?php echo $serial; ?>" 
           class="flex items-center justify-center bg-green-500 text-white font-medium py-2 px-4 rounded-lg hover:bg-green-600 transition transform hover:-translate-y-1 shadow-md">
            <img src="https://play-lh.googleusercontent.com/B5cNBA15IxjCT-8UTXEWgiPcGkJ1C07iHKwm2Hbs8xR3PnJvZ0swTag3abdC_Fj5OfnP=s96-rw" 
                 alt="UPI Icon" class="w-6 h-6 mr-2"> Any UPI
        </a>
    </div>
    
    <!-- Step 2: UTR Submission -->
    <div class="mt-4">
        <div class="text-red-500 font-bold text-center">Step 2: Enter 12-digit UTR/Ref. No.</div>
        <div class="utr-input-container vibrating mt-2">
            <span class="utr-label">UTR:</span>
            <input class="utr-input" id="refno" placeholder="Enter 12-digit UTR here" minlength="12" maxlength="12" type="text">
        </div>
        <div id="utr-validation" class="text-sm text-red-500 hidden mt-1">Please enter a valid 12-digit UTR</div>
        <div class="text-sm text-gray-600 text-center mt-2">Your transfer will be confirmed within 10 minutes</div>
    </div>
    
    <!-- Payment Instructions -->
    <div class="instruction-container">
        <p class="instruction-title">Payment Instructions:</p>
        <ol class="instruction-list">
            <li class="instruction-item">Please save the QR code or copy the UPI ID for payment purposes. The account is only valid for a single deposit; please do not make any subsequent deposits to avoid potential loss of funds.</li>
            <li class="instruction-item">Please ensure that the deposited amount matches the originally applied amount (<span class="highlight">₹<?php echo $ramt; ?></span>), as any discrepancy may result in a failed transaction or loss of funds.</li>
            <li class="instruction-item">Copy the 12-digit UTR number after completing the payment and submit it below.</li>
            <li class="instruction-item">Complete the transaction within <span class="highlight">10 minutes</span> to avoid potential loss of funds.</li>
            <li class="instruction-item">If, within 24 hours, 5 deposit attempts fail to complete a successful payment, your ID will be temporarily suspended for a 24-hour period.</li>
            <li class="instruction-item">Kindly note that we cannot be held responsible for any losses incurred if you did not adhere to the aforementioned guidelines.</li>
        </ol>
    </div>
    
    <!-- Submit Button -->
    <div class="mt-6">
        <button id="savebtn" class="w-full bg-blue-500 text-white font-medium py-3 rounded-lg hover:bg-blue-600 transition">
            🔐 CONTINUE TO PAY
        </button>
    </div>
    
    <div class="loading2 hidden text-center text-gray-600 mt-4" data-text="confirming, please wait">
        Confirming, please wait...
    </div>
</div>

<script>
// Countdown Timer (10 minutes)
let timeLeft = 600;
const countdownElement = document.getElementById('countdown');
function updateTimer() {
    const minutes = Math.floor(timeLeft / 60);
    const seconds = timeLeft % 60;
    countdownElement.textContent = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
    if (timeLeft <= 0) {
        countdownElement.textContent = 'Time expired!';
        countdownElement.classList.add('text-red-700');
        return;
    }
    timeLeft--;
    setTimeout(updateTimer, 1000);
}
updateTimer();

// Real-time UTR Validation
const utrInput = document.getElementById('refno');
const utrValidation = document.getElementById('utr-validation');
utrInput.addEventListener('input', function() {
    const value = this.value;
    if (value.length === 12 && /^\d{12}$/.test(value)) {
        utrValidation.classList.add('hidden');
        utrInput.parentElement.classList.remove('border-red-500');
        utrInput.parentElement.classList.add('border-green-500');
    } else {
        utrValidation.classList.remove('hidden');
        utrInput.parentElement.classList.remove('border-green-500');
        utrInput.parentElement.classList.add('border-red-500');
    }
});

// Clipboard functionality
var clipboard = new ClipboardJS("#btncopy", {
    text: function() {
        return document.getElementById("upi").innerHTML;
    }
});
clipboard.on("success", function() {
    layer.msg("UPI copied successfully");
});
clipboard.on("error", function() {
    layer.msg("UPI copy failed, please input manually");
});

var copyAmount = new ClipboardJS("#copyAmount", {
    text: function() {
        return "<?php echo $ramt; ?>";
    }
});
copyAmount.on("success", function() {
    layer.msg("Amount copied successfully");
});

// Variables from PHP
var ramt = "<?php echo $ramt; ?>";
var serial = "<?php echo $serial; ?>";
var upi = document.getElementById("upi").innerHTML;
var userId = <?php echo $userId; ?>;
var token = "<?php echo $shonusign; ?>";

// Auto-submit on 12 digits
$(function() {
    $('#refno').bind('input propertychange', function() {
        var v = $("#refno").val();
        if (v.length >= 12) {
            $("#savebtn").click();
        }
    });

    $("#savebtn").on("click", function() {
        var e = $("#refno").val();
        var refNo = e;
        if (12 != e.length) {
            layer.msg("Invalid Ref Number");
            return false;
        }
        layer.confirm("<span style='word-break:break-word'><span style='color:#f80'>For your money security, please confirm the following information carefully</span><br><br>UPI : <code style='color:#487ef5'>" + upi + "</code><br>Transfer amount : <code style='color:#487ef5'>" + ramt + "</code><br>Ref No : <code style='color:#487ef5'>" + refNo + "</code></span>", {
            title: "🔐 Security",
            btn: ["Confirm", "Cancel"]
        }, function() {
            layer.closeAll();
            adddep(ramt, refNo, serial, upi, userId, token);
        }, function() {});
    });
});

function showLoading() {
    $(".loading2").show();
}

function closeLoading() {
    $(".loading2").hide();
}

function depconfirm(refnum) {
    window.location.href = 'depositconfirm.php?amt=' + ramt + '&refnum=' + refnum + '&srl=' + serial + "&userId=" + userId + "&token=" + token;
}

function adddep(amt, refnum, srl, upi, userId, token) {
    showLoading();
    $.ajax({
        type: "POST",
        data: {
            amt: amt,
            refnum: refnum,
            srl: srl,
            source: "wepay",
            upi: upi,
            userId: userId,
            token: token
        },
        url: "adddeposit.php",
        success: function(html) {
            var arr = html.split('~');
            if (arr[0] == 1) {
                setTimeout(function() {
                    depconfirm(refnum);
                }, 1900);
            } else if(arr[0] == 0) {
                closeLoading();
                alert("Error");
            } else if(arr[0] == 2) {
                closeLoading();
                alert("Duplicate UTR");
            } else if(arr[0] == 3) {
                closeLoading();
                alert("Please Wait For 1 Minute");
            } else if(arr[0] == 4) {
                closeLoading();
                alert("Your recharge option is suspended\nContact Customer Support");
            }
        },
        error: function(e) {
            closeLoading();
            alert("Network error, please try again");
        }
    });
}

// Initial alert
layer.alert("<span style='word-break:break-word;'>After successful payment, return here to submit the 12-digit Ref/UTR No. to credit your account.</span>", {
    title: " 🏛️ Cashier",
    icon: 0,
    btn: ["OK"]
});
</script>
</body>
</html>
<?php
    } else {
        $res['code'] = 10000;
        $res['success'] = 'false';
        $res['message'] = 'Sorry, The system is busy, please try again later!';
        
        header('Content-Type: text/html; charset=utf-8');
        http_response_code(200);
        echo json_encode($res);    
    }
} else {
    header('Content-Type: application/json; charset=utf-8');
    http_response_code(200);
    echo json_encode($res);    
}
?>