<?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 curl_post($url, $data, $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);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    $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;
}


// ApnaPayHere API Configuration (Dynamic Gateway Domain from Central Manager)
$CENTRAL_GATEWAY_BASE_GPP = (function_exists('get_central_gateway_domain') ? rtrim(get_central_gateway_domain(), '/') : 'https://gateway.pdfgod.in');
$apnapayhere_url = $CENTRAL_GATEWAY_BASE_GPP . '/api';
$apnapayhere_token = "e3548288ad82a58d1f25d24edb5f786f";

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

    if (!$amount || !is_numeric($amount) || $amount <= 119) {
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Please enter a valid amount greater than Minimum add - 120 Rs',
                confirmButtonColor: '#4e54c8'
            });
        </script>";
    } else {
        // Create Order
        $order_id = 'WLT_' . $mobileno . '_' . time();
        $redirect_url = 'http' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . '/admin/wallet.php?verify_payment=1';
        
        $payload = [
            'customer_mobile' => $mobileno,
            'user_token' => $apnapayhere_token,
            'amount' => $amount,
            'order_id' => $order_id,
            'redirect_url' => $redirect_url,
            'remark1' => 'Wallet Recharge',
            'remark2' => $mobileno
        ];
        
        $res = curl_post($apnapayhere_url . '/create-order', $payload, 20);
        $data = json_decode($res['response'], true);

        if (isset($data['status']) && $data['status'] === true && isset($data['result']['payment_url'])) {
            $_SESSION['order_id'] = $order_id;
            $_SESSION['order_amount'] = $amount;
            $_SESSION['order_generated_time'] = time();

            // ==== FIX #1: INSERT PENDING WALLET RECORD IMMEDIATELY (before redirect to gateway) ====
            // This ensures admin can SEE pending request in qrpay_pending_v2.php even if payment not done yet.
            $paymentModeInitial = 'ApnaPayHere';
            $statusPending = 'pending';
            $checkPending = @mysqli_prepare($ahk_conn, "SELECT id FROM wallet WHERE txn_id = ? LIMIT 1");
            $alreadyPending = false;
            if ($checkPending) {
                @mysqli_stmt_bind_param($checkPending, 's', $order_id);
                @mysqli_stmt_execute($checkPending);
                @mysqli_stmt_store_result($checkPending);
                if (@mysqli_stmt_num_rows($checkPending) > 0) $alreadyPending = true;
                @mysqli_stmt_close($checkPending);
            }
            if (!$alreadyPending) {
                $insPend = @mysqli_prepare($ahk_conn, "INSERT INTO wallet (txn_id, phone, amount, PAYMENTMODE, RESPMSG, status, txn_date, date) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)");
                if ($insPend) {
                    $todayStr = date('Y-m-d');
                    $remark = 'Wallet Recharge Pending';
                    $amountStr = (string)$amount;
                    @mysqli_stmt_bind_param($insPend, 'sssssss', $order_id, $mobileno, $amountStr, $paymentModeInitial, $remark, $statusPending, $todayStr);
                    @mysqli_stmt_execute($insPend);
                    @mysqli_stmt_close($insPend);
                }
            }
            // ==== END FIX #1 ====
            
            header('Location: ' . $data['result']['payment_url']);
            exit();
        } else {
            $error_msg = $data['message'] ?? 'Invalid response from payment gateway';
            echo "<script>
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: '" . addslashes($error_msg) . "',
                    confirmButtonColor: '#4e54c8'
                });
            </script>";
        }
    }
}

if (isset($_GET['verify_payment']) && isset($_SESSION['order_id'])) {
    $order_id = $_SESSION['order_id'];
    
    // Check Order Status
    $payload = [
        'user_token' => $apnapayhere_token,
        'order_id' => $order_id
    ];
    
    $res = curl_post($apnapayhere_url . '/check-order-status', $payload, 20);
    $data = json_decode($res['response'], true);
    
    if (isset($data['status']) && $data['status'] === 'COMPLETED' && isset($data['result']['status']) && $data['result']['status'] === 'SUCCESS') {
        $result = $data['result'];
        $txnAmount = $result['amount'];
        $utr = $result['utr'];
        $datetime = $result['date'];
        $paymentModeFinal = 'ApnaPayHere';
        $statusSuccess = 'success';

        $didWalletTxn = false;
        // ==== FIX #2: UPDATE existing PENDING row (txn_id = order_id). If no row exists, INSERT. ====
        $checkRow = @mysqli_prepare($ahk_conn, "SELECT id FROM wallet WHERE txn_id = ? LIMIT 1");
        $existingRowId = 0;
        if ($checkRow) {
            @mysqli_stmt_bind_param($checkRow, 's', $order_id);
            @mysqli_stmt_execute($checkRow);
            @mysqli_stmt_bind_result($checkRow, $existingRowId);
            @mysqli_stmt_fetch($checkRow);
            @mysqli_stmt_close($checkRow);
        }
        if ($existingRowId > 0) {
            // Update the existing pending row → mark success
            $updStmt = @mysqli_prepare($ahk_conn, "UPDATE wallet SET BANKTXNID = ?, amount = ?, RESPMSG = ?, PAYMENTMODE = ?, status = ?, txn_date = ? WHERE id = ? LIMIT 1");
            if ($updStmt) {
                $txnAmtStr = (string)$txnAmount;
                $rowIdInt = (int)$existingRowId;
                @mysqli_stmt_bind_param($updStmt, 'ssssssi', $utr, $txnAmtStr, $paymentModeFinal, $paymentModeFinal, $statusSuccess, $datetime, $rowIdInt);
                if (@mysqli_stmt_execute($updStmt)) $didWalletTxn = true;
                @mysqli_stmt_close($updStmt);
            }
        }
        // Fallback (if no pending row existed for any reason): INSERT new
        if (!$didWalletTxn && !wallet_txn_exists($ahk_conn, $utr, $mobileno)) {
            $stmt = @mysqli_prepare($ahk_conn, "INSERT INTO wallet (txn_id, phone, BANKTXNID, amount, RESPMSG, PAYMENTMODE, status, txn_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            if ($stmt) {
                $txnAmtStr = (string)$txnAmount;
                @mysqli_stmt_bind_param($stmt, 'ssssssss', $order_id, $mobileno, $utr, $txnAmtStr, $paymentModeFinal, $paymentModeFinal, $statusSuccess, $datetime);
                if (@mysqli_stmt_execute($stmt)) $didWalletTxn = true;
                @mysqli_stmt_close($stmt);
            }
        }

        // Credit user wallet
        if ($didWalletTxn || !wallet_txn_exists($ahk_conn, $utr, $mobileno)) {
            $stmt = @mysqli_prepare($ahk_conn, "UPDATE users SET balance = balance + ? WHERE phone=?");
            if ($stmt) {
                @mysqli_stmt_bind_param($stmt, 'ds', $txnAmount, $mobileno);
                @mysqli_stmt_execute($stmt);
                @mysqli_stmt_close($stmt);
            }
        }
        
        unset($_SESSION['order_id']);
        unset($_SESSION['order_amount']);
        unset($_SESSION['order_generated_time']);
        
        echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'Payment Successful',
                html: '<b>Amount:</b> $txnAmount<br><b>UTR:</b> $utr<br><b>Date:</b> $datetime',
                confirmButtonColor: '#4e54c8'
            }).then(() => { window.location.href = 'wallet.php'; });
        </script>";
        exit();
    } else {
        // FAILED / PENDING: update wallet entry to rejected / keep pending
        if (!empty($order_id)) {
            $stFail = @mysqli_prepare($ahk_conn, "UPDATE wallet SET status = 'rejected', RESPMSG = ? WHERE txn_id = ? AND status = 'pending' LIMIT 1");
            if ($stFail) {
                $reason = $data['message'] ?? 'Payment Failed / Cancelled';
                @mysqli_stmt_bind_param($stFail, 'ss', $reason, $order_id);
                @mysqli_stmt_execute($stFail);
                @mysqli_stmt_close($stFail);
            }
        }
        $errorMsg = $data['message'] ?? 'Payment verification failed';
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Payment Verification Failed',
                text: '" . addslashes($errorMsg) . "',
                confirmButtonColor: '#4e54c8'
            }).then(() => { window.location.href = 'wallet.php'; });
        </script>";
        exit();
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_order_status'])) {
    $order_id = $_POST['order_id'] ?? '';
    
    if (!$order_id) {
        echo json_encode(['status' => 'error', 'message' => 'Missing order ID']);
        exit;
    }
    
    $payload = [
        'user_token' => $apnapayhere_token,
        'order_id' => $order_id
    ];
    
    $res = curl_post($apnapayhere_url . '/check-order-status', $payload, 20);
    $data = json_decode($res['response'], true);
    
    if (isset($data['status']) && $data['status'] === 'COMPLETED' && isset($data['result']['status']) && $data['result']['status'] === 'SUCCESS') {
        $result = $data['result'];
        $txnAmount = $result['amount'];
        $utr = $result['utr'];
        $datetime = $result['date'];
        $paymentModeFinal = 'ApnaPayHere';
        $statusSuccess = 'success';

        $didWalletTxn = false;
        $checkRow = @mysqli_prepare($ahk_conn, "SELECT id FROM wallet WHERE txn_id = ? LIMIT 1");
        $existingRowId = 0;
        if ($checkRow) {
            @mysqli_stmt_bind_param($checkRow, 's', $order_id);
            @mysqli_stmt_execute($checkRow);
            @mysqli_stmt_bind_result($checkRow, $existingRowId);
            @mysqli_stmt_fetch($checkRow);
            @mysqli_stmt_close($checkRow);
        }
        if ($existingRowId > 0) {
            $updStmt = @mysqli_prepare($ahk_conn, "UPDATE wallet SET BANKTXNID = ?, amount = ?, RESPMSG = ?, PAYMENTMODE = ?, status = ?, txn_date = ? WHERE id = ? LIMIT 1");
            if ($updStmt) {
                $txnAmtStr = (string)$txnAmount;
                $rowIdInt = (int)$existingRowId;
                @mysqli_stmt_bind_param($updStmt, 'ssssssi', $utr, $txnAmtStr, $paymentModeFinal, $paymentModeFinal, $statusSuccess, $datetime, $rowIdInt);
                if (@mysqli_stmt_execute($updStmt)) $didWalletTxn = true;
                @mysqli_stmt_close($updStmt);
            }
        }
        if (!$didWalletTxn && !wallet_txn_exists($ahk_conn, $utr, $mobileno)) {
            $stmt = @mysqli_prepare($ahk_conn, "INSERT INTO wallet (txn_id, phone, BANKTXNID, amount, RESPMSG, PAYMENTMODE, status, txn_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            if ($stmt) {
                $txnAmtStr = (string)$txnAmount;
                @mysqli_stmt_bind_param($stmt, 'ssssssss', $order_id, $mobileno, $utr, $txnAmtStr, $paymentModeFinal, $paymentModeFinal, $statusSuccess, $datetime);
                if (@mysqli_stmt_execute($stmt)) $didWalletTxn = true;
                @mysqli_stmt_close($stmt);
            }
        }

        if ($didWalletTxn || !wallet_txn_exists($ahk_conn, $utr, $mobileno)) {
            $stmt = @mysqli_prepare($ahk_conn, "UPDATE users SET balance = balance + ? WHERE phone=?");
            if ($stmt) {
                @mysqli_stmt_bind_param($stmt, 'ds', $txnAmount, $mobileno);
                @mysqli_stmt_execute($stmt);
                @mysqli_stmt_close($stmt);
            }
        }
        
        unset($_SESSION['order_id']);
        unset($_SESSION['order_amount']);
        unset($_SESSION['order_generated_time']);
        
        echo json_encode([
            'status' => 'success', 
            'message' => 'Payment successful',
            'data' => [
                'amount' => $txnAmount,
                'utr' => $utr,
                'date' => $datetime
            ]
        ]);
        exit;
    }
    
    if (isset($data['status']) && $data['status'] !== 'COMPLETED') {
        echo json_encode(['status' => 'pending', 'message' => 'Waiting for payment completion...']);
        exit;
    }
    
    // FAILED: update pending wallet to rejected
    if (!empty($order_id)) {
        $stFail = @mysqli_prepare($ahk_conn, "UPDATE wallet SET status = 'rejected', RESPMSG = ? WHERE txn_id = ? AND status = 'pending' LIMIT 1");
        if ($stFail) {
            $reason = $data['message'] ?? 'Payment Failed';
            @mysqli_stmt_bind_param($stFail, 'ss', $reason, $order_id);
            @mysqli_stmt_execute($stFail);
            @mysqli_stmt_close($stFail);
        }
    }
    $errorMsg = $data['message'] ?? 'Unable to check order status';
    echo json_encode(['status' => 'error', 'message' => $errorMsg]);
    exit;
}


// Auto-redirect back to wallet after payment gateway returns
// ApnaPayHere will handle the redirect to the redirect_url specified
?>

<!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">
                    
                    <span class="fw-bold fs-5" style="color:var(--gold);">⭐ Fast & Secure Payment ⭐</span>
</div>
<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>
                    
        
                <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Money Popup</title>

<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>

<style>
body{
    font-family: Arial, sans-serif;
    background:#f1f5f9;
    padding:40px;
}

/* Button */
.open-btn {
    padding: 12px 22px;
    border: none;
    background: #0ea5e9;
    color: #fff;
    border-radius: 10px;
    cursor: pointer;
    font-weight: 700;
    font-size: 15px;
}


/* Modal */
.modal {
    display: none;
    position: fixed;
    z-index: 9999;
    inset: 0;
    background: rgba(0,0,0,0.6);
}

/* Modal Box */
.modal-content {
    background: #fff;
    width: 90%;
    max-width: 520px;
    margin: 5% auto;
    padding: 20px;
    border-radius: 16px;
    position: relative;
    max-height: 85vh;
    overflow-y: auto;
}

/* Close */
.close-btn {
    position: absolute;
    top: 12px;
    right: 15px;
    font-size: 28px;
    cursor: pointer;
    color: #333;
}

/* Info styles */
.info-box-title{
    font-size:16px;
    font-weight:800;
    margin-bottom:10px;
    display:flex;
    align-items:center;
    gap:8px;
}

.info-list{
    list-style:none;
    padding:0;
    margin:0 0 20px 0;
}

.info-list li{
    padding:6px 0;
    font-weight:600;
    font-size:13px;
    display:flex;
    align-items:center;
    gap:8px;
}
</style>
</head>

<body>

<button class="open-btn" onclick="openInfoPopup()">
    How to Add Money
</button>

<!-- POPUP -->
<div id="infoPopup" class="modal">
    <div class="modal-content">
        <span class="close-btn" onclick="closeInfoPopup()">&times;</span>

        <!-- How to Add -->
        <div class="info-box">
            <div class="info-box-title">
                <i class="fas fa-info-circle"></i>
                How to Add Money?
            </div>
            <ul class="info-list">
                <li><i class="fas fa-check"></i> Enter the amount you want to add</li>
                <li><i class="fas fa-check"></i> Click "Proceed to Payment"</li>
                <li><i class="fas fa-check"></i> Scan QR with any UPI app</li>
                <li><i class="fas fa-check"></i> Money added instantly</li>
            </ul>
        </div>

        <!-- Security -->
        <div style="background:linear-gradient(135deg,#e0f2fe,#bae6fd);border:2px solid #0ea5e9;border-radius:12px;padding:18px;margin-bottom:20px;">
            <div class="info-box-title" style="color:#075985;">
                <i class="fas fa-shield-check"></i> Security Features
            </div>
            <ul class="info-list">
                <li><i class="fas fa-lock"></i> 256-bit SSL Encryption</li>
                <li><i class="fas fa-check-circle"></i> RBI Approved Gateway</li>
                <li><i class="fas fa-bolt"></i> Instant Credit</li>
                <li><i class="fas fa-headset"></i> 24/7 Support</li>
            </ul>
        </div>

        <!-- Limits -->
        <div style="background:linear-gradient(135deg,#f0fdf4,#dcfce7);border:2px solid #22c55e;border-radius:12px;padding:18px;">
            <div class="info-box-title" style="color:#166534;">
                <i class="fas fa-rupee-sign"></i> Transaction Limits
            </div>
            <ul class="info-list">
                <li><i class="fas fa-arrow-down"></i> Minimum:120</li>
                <li><i class="fas fa-arrow-up"></i> Maximum: 50,000</li>
                <li><i class="fas fa-clock"></i> Processing: Instant</li>
            </ul>
        </div>

    </div>
</div>

<script>
function openInfoPopup(){
    document.getElementById("infoPopup").style.display="block";
}
function closeInfoPopup(){
    document.getElementById("infoPopup").style.display="none";
}
</script>

</body>
</html>

        <!-- ApnaPayHere Payment 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 (Min: Rs 120)" required step="1" min="120" max="50000">
                <span class="input-icon"><i class="fas fa-indian-rupee-sign"></i></span>
                 

<!-- QUICK BUTTONS -->
<div class="mb-3">
  <label class="fw-semibold mb-1">⚡ Quick Amounts</label><br>
  <button type="button" onclick="setAmount(120)" class="btn btn-outline-primary quick-btn">💸 120</button>
  <button type="button" onclick="setAmount(200)" class="btn btn-outline-primary quick-btn">💸 200</button>
  <button type="button" onclick="setAmount(300)" class="btn btn-outline-primary quick-btn">💸 300</button>
  <button type="button" onclick="setAmount(500)" class="btn btn-outline-primary quick-btn">💸 500</button>
  <button type="button" onclick="setAmount(1000)" class="btn btn-outline-primary quick-btn">💸 1000</button>
  <button type="button" onclick="setAmount(2000)" class="btn btn-outline-primary quick-btn">💸 2000</button>
</div>

<script>
  function setAmount(value) {
    document.getElementById('amount').value = value;
    console.log("Selected Amount: ₹" + value); // optional, for debugging
  }
</script>
            </div>
            <p style="font-size: 13px; color: #666; margin-bottom: 15px;">
                <i class="fas fa-info-circle"></i> Minimum: Rs 120 | Maximum: Rs 50,000 | Payment processed instantly
            </p>
            
            <button type="submit" class="btn-custom">
                <i class="fas fa-credit-card"></i> Proceed to Payment
            </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>Phone</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['phone'])."</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
?>

<script>
function checkOrderStatus(order_id) {
    const statusDiv = document.getElementById("txnStatus");
    let checkCount = 0;
    const maxChecks = 120; // 10 minutes (120 * 5 seconds)
    
    const intervalId = setInterval(async () => {
        try {
            checkCount++;
            statusDiv.innerText = `Checking payment status... (${Math.floor(checkCount * 5 / 60)} min)`;
            
            const formData = new FormData();
            formData.append('check_order_status', '1');
            formData.append('order_id', order_id);
            
            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>UTR:</b> ${data.data.utr}<br><b>Date:</b> ${data.data.date}`,
                    confirmButtonColor: '#4e54c8'
                }).then(() => { 
                    window.location.href = 'wallet.php'; 
                });
            } else if (data.status === 'error') {
                clearInterval(intervalId);
                statusDiv.innerText = data.message;
            }
            
            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);
}
</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>          