
<?php
ob_start(); // Buffer output so header() redirect works even after HTML
include('header.php');

// NiceUPI Gateway Configuration
$niceupi_token = "f140ca65f39a434a587ced6fa63e9272";
$niceupi_create_url = "https://qr.niceupi.com/api/create-order";
// Redirect URL - order_id will be appended as GET param for reliable tracking
$niceupi_redirect_url_base = "https://dc.crsorgi.gov.in.verfy.cc/crs/qrnice/callback.php";

// Auto-migrate: add status and utr columns if missing
$col_check = mysqli_query($conn, "SHOW COLUMNS FROM `onlinepay` LIKE 'status'");
if($col_check && mysqli_num_rows($col_check) == 0){
    mysqli_query($conn, "ALTER TABLE `onlinepay` ADD COLUMN `status` VARCHAR(20) NOT NULL DEFAULT 'PENDING'");
    mysqli_query($conn, "ALTER TABLE `onlinepay` ADD COLUMN `utr` VARCHAR(50) DEFAULT NULL");
    mysqli_query($conn, "UPDATE `onlinepay` SET `status`='SUCCESS' WHERE `status`='PENDING'");
}

$payment_error = '';

// Process payment form submission
if(isset($_POST['submit'])){
    $user = mysqli_real_escape_string($conn, $_SESSION['userid']);
    $phone = isset($_SESSION['phone']) ? mysqli_real_escape_string($conn, $_SESSION['phone']) : '9999999999';
    date_default_timezone_set('Asia/Kolkata');
    $datetime = date('d/m/Y h:i:s a', time());
    $amount = intval($_POST['remark']);
    
    if($amount < 100 || $amount > 10000){
        $payment_error = 'Amount must be between ₹100 and ₹10,000';
    } else {
        $order_id = "ORD" . time() . rand(1000,9999);
        
        $ins_query = "INSERT INTO `onlinepay`(`or id`, `user id`, `amount`, `date_time`, `status`) VALUES ('$order_id','$user','$amount','$datetime','PENDING')";
        $run = mysqli_query($conn, $ins_query);
        
        if($run){
            // Append order_id to redirect URL so callback always gets it
            $niceupi_redirect_url = $niceupi_redirect_url_base . '?order_id=' . urlencode($order_id);
            
            $post_data = array(
                'customer_mobile' => $phone,
                'user_token'      => $niceupi_token,
                'amount'          => strval($amount),
                'order_id'        => $order_id,
                'redirect_url'    => $niceupi_redirect_url,
                'remark1'         => $user,
                'remark2'         => 'wallet_recharge'
            );
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $niceupi_create_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $response = curl_exec($ch);
            $curl_error = curl_error($ch);
            curl_close($ch);
            
            @file_put_contents(__DIR__ . '/qrnice/payment_log.txt', date('Y-m-d H:i:s') . " | order: $order_id | amount: $amount | user: $user | response: $response | curl_error: $curl_error\n", FILE_APPEND | LOCK_EX);
            
            if($curl_error){
                $payment_error = 'Payment gateway connection failed. Please try again.';
            } else {
                $result = json_decode($response, true);
                
                if($result && isset($result['status']) && $result['status'] === true && isset($result['result']['payment_url'])){
                    $payment_url = $result['result']['payment_url'];
                    // Store order_id in cookie with SameSite=None (required for cross-domain redirect)
                    setcookie('pending_order_id', $order_id, ['expires' => time() + 1800, 'path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
                    setcookie('pending_order_user', $user, ['expires' => time() + 1800, 'path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
                    ob_end_clean(); // Discard buffered HTML
                    header("Location: " . $payment_url);
                    exit;
                } else {
                    $error_msg = isset($result['message']) ? $result['message'] : 'Payment gateway error';
                    @file_put_contents(__DIR__ . '/qrnice/payment_log.txt', "API ERROR: $error_msg | Raw: $response\n", FILE_APPEND | LOCK_EX);
                    $payment_error = $error_msg;
                }
            }
        } else {
            $db_err = mysqli_error($conn);
            @file_put_contents(__DIR__ . '/qrnice/payment_log.txt', "DB INSERT FAILED: $db_err\n", FILE_APPEND | LOCK_EX);
            $payment_error = 'Order creation failed. Please try again.';
        }
    }
}

// Check txn_status for success/fail messages
$show_success = false;
$show_failed = false;

if(isset($_GET['txn_status'])){
    if($_GET['txn_status'] == 'SUCCESS'){
        $show_success = true;
    } elseif($_GET['txn_status'] == 'FAILED' || $_GET['txn_status'] == 'TXN_FAILED'){
        $show_failed = true;
    }
}
ob_end_flush(); // Flush the buffered header.php HTML output
?>

<?php if($show_success): ?>
<script>
    document.addEventListener('DOMContentLoaded', function(){
        Swal.fire('Success', 'Recharge Successful! Amount added to wallet.', 'success');
    });
</script>
<?php endif; ?>

<?php if($show_failed): ?>
<script>
    document.addEventListener('DOMContentLoaded', function(){
        Swal.fire('Failed', 'Recharge Failed! Please try again.', 'error');
    });
</script>
<?php endif; ?>

<?php if(!empty($payment_error)): ?>
<script>
    document.addEventListener('DOMContentLoaded', function(){
        Swal.fire('Error', '<?php echo htmlspecialchars($payment_error, ENT_QUOTES, "UTF-8"); ?>', 'error');
    });
</script>
<?php endif; ?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <title>Payment Form</title>
    <style>
        .payment-form {
            max-width: 1000px;
            margin: auto;
            background: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgb(0 0 0 / 80%);
        }

        .payment-form input {
            width: calc(100% - 20px);
            padding: 10px;
            margin: 10px 0;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .payment-form button {
            width: 100%;
            padding: 10px;
            background: #28a745;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .payment-form button:hover {
            background: #218838;
        }

        .qr-popup {
            display: none;
            position: fixed;
            top: 70px;
            left: 50%;
            transform: translateX(-50%);
            width: 300px;
            background: rgb(255, 255, 255);
            justify-content: center;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            color: #181818;
            border: 5px solid #28a745;
            box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
        }

        .qr-popup img {
            max-width: 200px;
            margin: 10px auto;
        }

        .qr-popup button {
            margin-top: 10px;
            padding: 10px;
            background: #dc3545;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>

<body>

    <div class="payment-form">
        <h1>Recharge</h1>
         <form class="user" action="" method="POST">

				  <div class="form-group row">
                  <div class="col-sm-6 mb-3 mb-sm-0">
                    <input required="required" type="number" class="form-control" placeholder="Amount (Min ₹100 - Max ₹10,000)" name="remark" value="" min="100" max="10000" id="amountInput">
                    <small style="color: #666;">Minimum: ₹100 | Maximum: ₹10,000</small>
                  </div>
                  <br>
                  <div class="col-sm-6 mb-3 mb-sm-0">       
                    <input required="required" type="submit" name="submit" class="btn btn-primary" value="Submit" onclick="return validateAmount();">
                  </div>
				  </div> 
				  
				  
				 </form>
				 
<script>
function validateAmount() {
    var amount = parseInt(document.getElementById('amountInput').value);
    if (isNaN(amount) || amount < 100) {
        Swal.fire('Error', 'Minimum recharge amount is ₹100', 'error');
        return false;
    }
    if (amount > 10000) {
        Swal.fire('Error', 'Maximum recharge amount is ₹10,000', 'error');
        return false;
    }
    return true;
}
</script>
				 
				  <div class="col-lg-2 col-3 bg-info text-center">Note:-&nbsp;</div>        
        <div class="  col-lg-10 col-9 bg-danger">
          <marquee class="marquee" onmouseover="this.stop();" onmouseout="this.start();">
                   BALANCE ADD FULLY AUTOMATIC HOTA HAI ANY PROBLEM CONTACT WHATSAPP 9262982863                               </marquee>
        </div>
				     <br>
1.
Now online recharge will be done and after payment success, money will automatically come into your wallet. <br>  <br>
2.If you refresh or close the page while recharging, money will not come into the wallet.
<br> <br>
3. Do not close the QR code page while recharging.
<br> <br>


    </div>


    
    <script src="plugins/chart.js/Chart.min.js"></script>
    <!-- Sparkline -->
    <script src="plugins/sparklines/sparkline.js"></script>
    <!-- JQVMap -->
    <script src="plugins/jqvmap/jquery.vmap.min.js"></script>
    <script src="plugins/jqvmap/maps/jquery.vmap.usa.js"></script>
    <!-- jQuery Knob Chart -->
    <script src="plugins/jquery-knob/jquery.knob.min.js"></script>
    <!-- daterangepicker -->
    <script src="plugins/moment/moment.min.js"></script>
    <script src="plugins/daterangepicker/daterangepicker.js"></script>
    <!-- Tempusdominus Bootstrap 4 -->
    <script src="plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script>
    <!-- Summernote -->
    <script src="plugins/summernote/summernote-bs4.min.js"></script>
    <!-- overlayScrollbars -->
    <script src="plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
    <!-- AdminLTE App -->
    <script src="dist/js/adminlte.js"></script>
    <!-- AdminLTE for demo purposes -->
    <script src="dist/js/demo.js"></script>
    <!-- AdminLTE dashboard demo (This is only for demo purposes) -->
    <script src="dist/js/pages/dashboard.js"></script>

</body>

</html>