<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/header.php');
$mobileno = $udata['phone'];


function curl_get($url, $timeout = 15) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ['http_code' => $code, 'response' => $resp, 'error' => $err];
}


function wallet_txn_exists($conn, $banktxnid, $phone) {
    $sql = "SELECT COUNT(*) as cnt FROM wallet WHERE BANKTXNID = ? AND phone = ?";
    if ($stmt = mysqli_prepare($conn, $sql)) {
        mysqli_stmt_bind_param($stmt, 'ss', $banktxnid, $phone);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $cnt);
        mysqli_stmt_fetch($stmt);
        mysqli_stmt_close($stmt);
        return ($cnt > 0);
    }
    return false;
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['amount'])) {
    $amount = $_POST['amount'] ?? '';

    if (!$amount || !is_numeric($amount) || $amount <= 49) {
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Please enter a valid amount greater than $amount',
                confirmButtonColor: '#4e54c8'
            });
        </script>";
    } else {
        $url = "$tng_gatewaye_url/qr_verification?amount=" . urlencode($amount) . "&apikey=" . urlencode($tng_gatewaye_apikey);
        $res = curl_get($url, 20);
        $data = json_decode($res['response'], true);

        if (isset($data['error'])) {
            echo "<script>
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: '" . addslashes($data['error']) . "',
                    confirmButtonColor: '#4e54c8'
                });
            </script>";
        } elseif (is_array($data) && isset($data['Message']) && $data['Message'] === 'Success') {
            $_SESSION['qr_data'] = $data;
            $_SESSION['qr_amount'] = $amount;
            $_SESSION['qr_generated_time'] = time();
            
            header("Location: wallet.php?show_qr=1");
            exit();
        } else {
            echo "<script>
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Invalid response from payment gateway',
                    confirmButtonColor: '#4e54c8'
                });
            </script>";
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_payment'])) {
    $type = $_POST['type'] ?? '';
    $application_no = $_POST['application_no'] ?? '';
    $utr = $_POST['utr'] ?? '';

    unset($_SESSION['qr_data']);
    unset($_SESSION['qr_amount']);
    unset($_SESSION['qr_generated_time']);

    if (!$type || !$application_no || !$utr) {
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Please enter all required parameters including UTR number',
                confirmButtonColor: '#4e54c8'
            }).then(() => { window.location.href = 'wallet.php'; });
        </script>";
        exit();
    } else {
        $url = "$tng_gatewaye_url/bharatpaygateway_verification?type=" . urlencode($type) . "&application_no=" . urlencode($application_no) . "&utr=" . urlencode($utr) . "&apikey=" . urlencode($tng_gatewaye_apikey);

        $res = curl_get($url, 20);
        $data = json_decode($res['response'], true);

        if (isset($data['error'])) {
            echo "<script>
                Swal.fire({
                    icon: 'error',
                    title: 'Payment Failed',
                    text: '" . addslashes($data['error']) . "',
                    confirmButtonColor: '#4e54c8'
                }).then(() => { window.location.href = 'wallet.php'; });
            </script>";
            exit();
        } elseif (is_array($data) && isset($data['Message']) && $data['Message'] === 'Success' && isset($data['status']) && $data['status'] === 'SUCCESS') {
            $payerName = $data['payerName'] ?? 'QR Payment';
            $payerHandle = $data['payerHandle'] ?? 'QR';
            $txnAmount = $data['amount'];
            $utr = $data['utr'];
            $datetime = date("Y-m-d H:i:s");

            if (!wallet_txn_exists($ahk_conn, $utr, $mobileno)) {
                $stmt = mysqli_prepare($ahk_conn, "INSERT INTO wallet (phone, BANKTXNID, amount, RESPMSG, PAYMENTMODE, status, txn_date) VALUES (?, ?, ?, ?, ?, ?, ?)");
                mysqli_stmt_bind_param($stmt, 'ssissss', $mobileno, $utr, $txnAmount, $payerName, $payerHandle, $data['status'], $datetime);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);

                $stmt = mysqli_prepare($ahk_conn, "UPDATE users SET balance = balance + ? WHERE phone=?");
                mysqli_stmt_bind_param($stmt, 'is', $txnAmount, $mobileno);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);

                
            }

            echo "<script>
                Swal.fire({
                    icon: 'success',
                    title: 'Payment Successful 🎉',
                    html: '<b>Amount:</b> ₹$txnAmount<br><b>Payer:</b> $payerName<br><b>Date:</b> $datetime',
                    confirmButtonColor: '#4e54c8'
                }).then(() => { window.location.href = 'wallet.php'; });
            </script>";
            exit();
        } else {
            echo "<script>
                Swal.fire({
                    icon: 'error',
                    title: 'Payment Failed ❌',
                    text: 'Transaction failed. Please check your UTR number or try again later.',
                    confirmButtonColor: '#4e54c8'
                }).then(() => { window.location.href = 'wallet.php'; });
            </script>";
            exit();
        }
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_paytm_status'])) {
    $application_no = $_POST['application_no'] ?? '';
    
    if (!$application_no) {
        echo json_encode(['status' => 'error', 'message' => 'Missing application number']);
        exit;
    }
    
    $url = "$tng_gatewaye_url/bharatpaygateway_verification?type=paytm&application_no=" . urlencode($application_no) . "&apikey=" . urlencode($tng_gatewaye_apikey);
    $res = curl_get($url, 20);
    $data = json_decode($res['response'], true);
    
    if (isset($data['error'])) {
        echo json_encode(['status' => 'pending', 'message' => $data['error']]);
        exit;
    }
    
    if (is_array($data) && isset($data['Message']) && $data['Message'] === 'Success' && isset($data['status']) && $data['status'] === 'SUCCESS') {
        $payerName = $data['payerName'] ?? 'QR Payment';
        $payerHandle = $data['payerHandle'] ?? 'QR';
        $txnAmount = $data['amount'];
        $utr = $data['utr'];
        $datetime = date("Y-m-d H:i:s");

        if (!wallet_txn_exists($ahk_conn, $utr, $mobileno)) {
            $stmt = mysqli_prepare($ahk_conn, "INSERT INTO wallet (phone, BANKTXNID, amount, RESPMSG, PAYMENTMODE, status, txn_date) VALUES (?, ?, ?, ?, ?, ?, ?)");
            mysqli_stmt_bind_param($stmt, 'ssissss', $mobileno, $utr, $txnAmount, $payerName, $payerHandle, $data['status'], $datetime);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);

            $stmt = mysqli_prepare($ahk_conn, "UPDATE users SET balance = balance + ? WHERE phone=?");
            mysqli_stmt_bind_param($stmt, 'is', $txnAmount, $mobileno);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);

            
        }
        
    
        unset($_SESSION['qr_data']);
        unset($_SESSION['qr_amount']);
        unset($_SESSION['qr_generated_time']);
        
        echo json_encode([
            'status' => 'success', 
            'message' => 'Payment successful',
            'data' => [
                'amount' => $txnAmount,
                'payer' => $payerName,
                'date' => $datetime
            ]
        ]);
        exit;
    }
    
    echo json_encode(['status' => 'pending', 'message' => 'Waiting for payment...']);
    exit;
}


if (isset($_SESSION['qr_data']) && $_SESSION['qr_data']['type'] === 'paytm' && isset($_GET['show_qr'])) {
    $application_no = $_SESSION['qr_data']['application_no'];
    $url = "$tng_gatewaye_url/bharatpaygateway_verification?type=paytm&application_no=" . urlencode($application_no) . "&apikey=" . urlencode($tng_gatewaye_apikey);
    $res = curl_get($url, 20);
    $data = json_decode($res['response'], true);
    
    if (is_array($data) && isset($data['Message']) && $data['Message'] === 'Success' && isset($data['status']) && $data['status'] === 'SUCCESS') {
        $payerName = $data['payerName'] ?? 'QR Payment';
        $payerHandle = $data['payerHandle'] ?? 'QR';
        $txnAmount = $data['amount'];
        $utr = $data['utr'];
        $datetime = date("Y-m-d H:i:s");

        if (!wallet_txn_exists($ahk_conn, $utr, $mobileno)) {
            $stmt = mysqli_prepare($ahk_conn, "INSERT INTO wallet (phone, BANKTXNID, amount, RESPMSG, PAYMENTMODE, status, txn_date) VALUES (?, ?, ?, ?, ?, ?, ?)");
            mysqli_stmt_bind_param($stmt, 'ssissss', $mobileno, $utr, $txnAmount, $payerName, $payerHandle, $data['status'], $datetime);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);

            $stmt = mysqli_prepare($ahk_conn, "UPDATE users SET balance = balance + ? WHERE phone=?");
            mysqli_stmt_bind_param($stmt, 'is', $txnAmount, $mobileno);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);

            
        }
     
        unset($_SESSION['qr_data']);
        unset($_SESSION['qr_amount']);
        unset($_SESSION['qr_generated_time']);
     
        echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'Payment Successful 🎉',
                html: '<b>Amount:</b> ₹$txnAmount<br><b>Payer:</b> $payerName<br><b>Date:</b> $datetime',
                confirmButtonColor: '#4e54c8'
            }).then(() => { window.location.href = 'wallet.php'; });
        </script>";
        exit;
    }
}
?>

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>QR Payment System</title>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

<style>
body { 
    background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%); 
    min-height:100vh; 
    display:flex; 
    justify-content:center; 
    align-items:center; 
    padding:20px; 
}
.container { 
    background:white; 
    border-radius:15px; 
    box-shadow:0 10px 30px rgba(0,0,0,0.2); 
    width:100%; 
    max-width:900px; 
    overflow:hidden; 
}
.header { 
    background:#4e54c8; 
    color:white; 
    padding:20px; 
    text-align:center; 
}
.header h1 { 
    font-size:24px; 
    margin-bottom:5px; 
}
.form-container { 
    padding:25px; 
}
.input-group { 
    margin-bottom:20px; 
    position:relative; 
}
.input-group label { 
    display:block; 
    margin-bottom:8px; 
    font-weight:600; 
    color:#333; 
}
.input-group input { 
    width:100%; 
    padding:12px 15px; 
    border:2px solid #ddd; 
    border-radius:8px; 
    font-size:16px; 
    transition:all .3s; 
}
.input-group input:focus { 
    border-color:#4e54c8; 
    outline:none; 
    box-shadow:0 0 0 3px rgba(78,84,200,0.2); 
}
.input-group .input-icon { 
    position:absolute; 
    right:15px; 
    top:40px; 
    color:#777; 
}
.btn-custom { 
    background:#4e54c8; 
    color:white; 
    border:none; 
    padding:12px 20px; 
    width:100%; 
    border-radius:8px; 
    font-size:16px; 
    font-weight:600; 
    cursor:pointer; 
    transition:all .3s; 
    display:flex; 
    justify-content:center; 
    align-items:center; 
    gap:10px; 
}
.btn-custom:hover { 
    background:#3a3eb3; 
    transform:translateY(-2px); 
    box-shadow:0 5px 15px rgba(78,84,200,0.4); 
}
.table thead { 
    background:#4e54c8; 
    color:white; 
}
</style>
</head>
<body>
<!--start page wrapper -->
<div class="page-wrapper">
    <div class="page-content">
        <!--breadcrumb-->
        <div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
            <div class="breadcrumb-title pe-3">Wallet</div>
            <div class="ps-3">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0 p-0">
                        <li class="breadcrumb-item"><a href="javascript:;"><i class="bx bx-home-alt"></i></a>
                        </li>
                        <li class="breadcrumb-item active" aria-current="page">Wallet Management</li>
                    </ol>
                </nav>
            </div>
            <div class="ms-auto">
                <div class="btn-group">
                    <button type="button" class="btn btn-primary">Settings</button>
                    <button type="button" class="btn btn-primary split-bg-primary dropdown-toggle dropdown-toggle-split"
                        data-bs-toggle="dropdown"> <span class="visually-hidden">Toggle Dropdown</span>
                    </button>
                    <div class="dropdown-menu dropdown-menu-right dropdown-menu-lg-end"> 
                        <a class="dropdown-item" href="javascript:;">Action</a>
                        <a class="dropdown-item" href="javascript:;">Another action</a>
                        <a class="dropdown-item" href="javascript:;">Something else here</a>
                        <div class="dropdown-divider"></div> 
                        <a class="dropdown-item" href="javascript:;">Separated link</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- QR Generate Form -->
        <form method="POST" action="">
            <div class="input-group">
                <label for="amount">Enter Amount (₹)</label>
                <input type="number" id="amount" name="amount" placeholder="Enter amount in rupees" required step="1">
                <span class="input-icon"><i class="fas fa-indian-rupee-sign"></i></span>
            </div>
            
            <button type="submit" class="btn-custom">
                <i class="fas fa-qrcode"></i> Generate QR Code
            </button>
        </form>

         <h6 class="mb-0 text-uppercase">Payment List</h6>
				<hr/>
				<div class="card">
					<div class="card-body">
						<div class="table-responsive">
							<table id="example2" class="table table-striped table-bordered">
                <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th>UTR</th>
                            <th>Amount</th>
                            <th>Payer</th>
                            <th>Method</th>
                            <th>Status</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if ($udata['type'] == 'admin') {
                            $res = mysqli_query($ahk_conn, "SELECT * FROM wallet ORDER BY txn_date DESC");
                        } else {
                            $phone = mysqli_real_escape_string($ahk_conn, $udata['phone']);
                            $res = mysqli_query($ahk_conn, "SELECT * FROM wallet WHERE phone='$phone' ORDER BY txn_date DESC");
                        }

                        $i = 1;
                        while ($row = mysqli_fetch_assoc($res)) {
                            echo "<tr>
                                <td>{$i}</td>
                                <td>".htmlspecialchars($row['BANKTXNID'])."</td>
                                <td>₹".htmlspecialchars($row['amount'])."</td>
                                <td>".htmlspecialchars($row['RESPMSG'])."</td>
                                <td>".htmlspecialchars($row['PAYMENTMODE'])."</td>
                                <td><span class='badge bg-".($row['status']=='success'?'success':'danger')."'>".htmlspecialchars($row['status'])."</span></td>
                                <td>".htmlspecialchars($row['txn_date'])."</td>
                            </tr>";
                            $i++;
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>
		
					

<?php

if (isset($_GET['show_qr']) && isset($_SESSION['qr_data']) && is_array($_SESSION['qr_data']) && !isset($_POST['verify_payment'])) {
    $data = $_SESSION['qr_data'];
    $amount = $_SESSION['qr_amount'] ?? 0;
    
    $html = '
    <div style="text-align:center;">
        <p><b>Company:</b> ' . ($data['companyName'] ?? 'N/A') . '</p>
        <p><b>Amount:</b> ₹' . ($data['amount'] ?? $amount) . '</p>
        <img src="' . $data['qr'] . '" style="width:200px;height:200px;border:1px solid #eee;border-radius:8px;">
        <div id="txnStatus" style="margin-top:15px;color:#333;font-weight:bold;padding:10px;background:#f8f9fa;border-radius:8px;">Waiting for payment...</div>
    </div>';
    
    if ($data['type'] === "bharatpay") {
        $html .= '<div style="margin-top:15px;">
                    <input id="utrInput" class="swal2-input" placeholder="Enter UTR No" style="width:100%;padding:10px;">
                 </div>';
    }
    
    echo '<script>
    Swal.fire({
        title: "Scan QR to Pay",
        html: `' . $html . '`,
        showConfirmButton: ' . ($data['type'] === "bharatpay" ? 'true' : 'false') . ',
        confirmButtonText: "Verify Payment",
        confirmButtonColor: "#4e54c8",
        allowOutsideClick: false,
        didOpen: () => {
            if("' . $data['type'] . '" === "paytm"){
                // For Paytm, start checking status every 5 seconds
                checkPaytmStatus("' . $data['application_no'] . '");
            }
        }
    }).then(result => {
        if(result.isConfirmed && "' . $data['type'] . '" === "bharatpay"){
            let utr = document.getElementById("utrInput").value.trim();
            if(!utr) {
                Swal.showValidationMessage("Please enter UTR number");
                return false;
            }
            
            // Create a hidden form and submit it
            const form = document.createElement("form");
            form.method = "POST";
            form.action = "";
            
            const typeInput = document.createElement("input");
            typeInput.type = "hidden";
            typeInput.name = "type";
            typeInput.value = "bharatpay";
            form.appendChild(typeInput);
            
            const appInput = document.createElement("input");
            appInput.type = "hidden";
            appInput.name = "application_no";
            appInput.value = "' . $data['application_no'] . '";
            form.appendChild(appInput);
            
            const utrInput = document.createElement("input");
            utrInput.type = "hidden";
            utrInput.name = "utr";
            utrInput.value = utr;
            form.appendChild(utrInput);
            
            const verifyInput = document.createElement("input");
            verifyInput.type = "hidden";
            verifyInput.name = "verify_payment";
            verifyInput.value = "1";
            form.appendChild(verifyInput);
            
            document.body.appendChild(form);
            form.submit();
        }
    });
    </script>';
}
?>

<script>
function checkPaytmStatus(application_no) {
    const statusDiv = document.getElementById("txnStatus");
    let checkCount = 0;
    const maxChecks = 60; 
    
   
    const intervalId = setInterval(async () => {
        try {
            checkCount++;
            statusDiv.innerText = `Checking payment status... (${checkCount})`;
            
            const formData = new FormData();
            formData.append('check_paytm_status', '1');
            formData.append('application_no', application_no);
            
            const response = await fetch('', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (data.status === 'success') {
                clearInterval(intervalId);
                Swal.close();
                Swal.fire({
                    icon: 'success',
                    title: 'Payment Successful 🎉',
                    html: `<b>Amount:</b> ₹${data.data.amount}<br><b>Payer:</b> ${data.data.payer}<br><b>Date:</b> ${data.data.date}`,
                    confirmButtonColor: '#4e54c8'
                }).then(() => { 
                    window.location.href = 'wallet.php'; 
                });
            } else if (data.status === 'error') {
                statusDiv.innerText = data.message;
             
                if (data.message.includes('not successful') || data.message.includes('failed')) {
                    clearInterval(intervalId);
                    statusDiv.innerText = "Payment failed. Please try again.";
                }
            }
            
          
            if (checkCount >= maxChecks) {
                clearInterval(intervalId);
                statusDiv.innerText = "Payment check timeout. Please contact support if payment was made.";
            }
        } catch (error) {
            console.error('Error checking payment status:', error);
            statusDiv.innerText = "Error checking status. Retrying...";
        }
    }, 5000);
}

<?php if (isset($_SESSION['qr_data']) && $_SESSION['qr_data']['type'] === 'paytm' && isset($_GET['show_qr'])): ?>
setTimeout(function() {
    window.location.reload();
}, 5000);
<?php endif; ?>
</script>

</body>
<!--end page wrapper -->
<?php
include('../template/ahkweb/footer.php');
?>
<!-- Bootstrap JS -->
<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<!--plugins-->
<script src="../template/ahkweb/assets/js/jquery.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<!--app JS-->
<script src="../template/ahkweb/assets/js/app.js"></script>
<!-- datatable -->
<script src="../template/ahkweb/assets/plugins/datatable/js/jquery.dataTables.min.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/dataTables.bootstrap5.min.js"></script>
<script>
    $(document).ready(function() {
        $('#example').DataTable();
    } );
</script>

<script>
    $(document).ready(function() {
        var table = $('#example2').DataTable( {
            lengthChange: false,
            buttons: [ 'copy', 'excel', 'pdf', 'print']
        } );
     
        table.buttons().container()
            .appendTo( '#example2_wrapper .col-md-6:eq(0)' );
    } );
</script>
<!--app JS-->
<script src="../template/ahkweb/assets/js/app.js"></script>
</body>
</html>