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


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 <= XyZ_val('balance_add_minumum_amount')) {
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Please enter a valid amount greater than $amount',
                confirmButtonColor: '#4e54c8'
            });
        </script>";
    } else {
        $url = "https://".JkL_get('paymentapi','gateway_Url')."/qr_verification?amount=" . urlencode($amount) . "&apikey=" . urlencode(JkL_get('paymentapi','gateway_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 = "https://".JkL_get('paymentapi','gateway_Url')."/bharatpaygateway_verification?type=" . urlencode($type) . "&application_no=" . urlencode($application_no) . "&utr=" . urlencode($utr) . "&apikey=" . urlencode(JkL_get('paymentapi','gateway_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($tng_conn, $utr, $mobileno)) {
                $stmt = mysqli_prepare($tng_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($tng_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 = "https://".JkL_get('paymentapi','gateway_Url')."/bharatpaygateway_verification?type=paytm&application_no=" . urlencode($application_no) . "&apikey=" . urlencode(JkL_get('paymentapi','gateway_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($tng_conn, $utr, $mobileno)) {
            $stmt = mysqli_prepare($tng_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($tng_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 = "https://".JkL_get('paymentapi','gateway_Url')."/bharatpaygateway_verification?type=paytm&application_no=" . urlencode($application_no) . "&apikey=" . urlencode(JkL_get('paymentapi','gateway_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($tng_conn, $utr, $mobileno)) {
            $stmt = mysqli_prepare($tng_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($tng_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;
    }
}
?>
<?php 
$minAmount = intval(XyZ_val('balance_add_minumum_amount')) + 1; 
?>
<div class="page-wrapper">
  <div class="page-content">
    <div class="card radius-15 shadow-lg border-0">
      <div class="card-body">

        
        <div class="d-flex align-items-center justify-content-between mb-4">
          <div>
            <h4 class="mb-1 fw-bold text-primary">💰 Wallet Management</h4>
            <p class="mb-0 text-muted">Add money to your wallet and track payment history</p>
          </div>
          <a href="javascript:void(0);" onclick="window.history.back();" class="btn btn-outline-primary rounded-pill px-4 py-2 fw-semibold">
            <i class="bi bi-arrow-left-circle me-2"></i> Go Back
          </a>
        </div>

        
        <div class="row mb-4">
          <div class="col-md-6">
            <div class="card bg-gradient-primary border-0 text-white shadow-sm">
              <div class="card-body py-4">
                <div class="d-flex align-items-center">
                  <div class="flex-grow-1">
                    <h6 class="mb-2">Current Balance</h6>
                    <h3 class="mb-0 fw-bold">₹<?php echo number_format($udata['balance'] ?? 0, 2); ?></h3>
                    <small class="opacity-75">Available for transactions</small>
                  </div>
                  <div class="flex-shrink-0">
                    <i class="fas fa-wallet fa-2x opacity-75"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col-md-6">
            <div class="card bg-light border-0 shadow-sm">
              <div class="card-body py-4">
                <h6 class="mb-2 text-primary">Quick Actions</h6>
                <div class="d-flex gap-2">
                  <button class="btn btn-sm btn-outline-primary rounded-pill" onclick="setAmount(100)">₹100</button>
                  <button class="btn btn-sm btn-outline-primary rounded-pill" onclick="setAmount(500)">₹500</button>
                  <button class="btn btn-sm btn-outline-primary rounded-pill" onclick="setAmount(1000)">₹1000</button>
                  <button class="btn btn-sm btn-outline-primary rounded-pill" onclick="setAmount(2000)">₹2000</button>
                </div>
              </div>
            </div>
          </div>
        </div>

       
<div class="card border-0 shadow-sm mb-4">
  <div class="card-header bg-transparent border-bottom">
    <h6 class="mb-0 fw-bold">💳 Add Money to Wallet</h6>
  </div>
  <div class="card-body">
    <!-- Updated Form -->
    <form method="POST" action="AXEN/index.php" class="mb-0" autocomplete="off" style="max-width: 100%; margin: 0 auto;">
      <!-- Hidden Inputs -->
      <input type="hidden" name="mode" value="index">
      <input type="hidden" name="order_id" value="<?php echo $ORDER_ID; ?>">
      <input type="hidden" name="email" value="<?php echo $emailid; ?>">
      <input type="hidden" name="phone" value="<?php echo $phone; ?>">

      <div class="row g-3 align-items-end">
        <div class="col-md-8">
          <label class="form-label fw-semibold">Enter Amount</label>
          <div class="input-group input-group-lg">
            <span class="input-group-text bg-light border-end-0">
              <i class="fas fa-indian-rupee-sign text-muted"></i>
            </span>
            <input type="number" id="amount" name="amount" required step="1"
                   placeholder="Enter amount (Minimum ₹<?php echo $minAmount; ?>)"
                   min="<?php echo $minAmount; ?>"
                   value="<?php echo isset($_POST['amount']) ? htmlspecialchars($_POST['amount']) : ''; ?>"
                   class="form-control border-start-0 ps-0">
          </div>
        </div>

        <div class="col-md-4">
          <button type="submit" class="btn btn-primary btn-lg w-100 d-flex align-items-center justify-content-center gap-2">
            <i class="fas fa-plus-circle"></i> Add Money
          </button>
        </div>
      </div>
    </form>
  </div>
</div>

        
        <div class="card border-0 shadow-sm">
          <div class="card-header bg-transparent border-bottom d-flex justify-content-between align-items-center">
            <h6 class="mb-0 fw-bold">📋 Payment History</h6>
            <span class="badge bg-primary">Last 10 Transactions</span>
          </div>
          <div class="card-body p-0">
            <div class="table-responsive">
              <table id="walletTable" class="table table-hover align-middle mb-0">
                <thead class="table-light">
                  <tr>
                    <th class="text-center">#</th>
                    <th>UTR/Transaction ID</th>
                    <th class="text-end">Amount</th>
                    <th>Payer</th>
                    <th>Method</th>
                    <th class="text-center">Status</th>
                    <th>Date</th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                  $res = null;
                  if ($udata['type'] === 'admin') {
                      $res = mysqli_query($tng_conn, "SELECT * FROM wallet ORDER BY id DESC LIMIT 10"); 
                  } else {
                      $phone = mysqli_real_escape_string($tng_conn, $udata['phone']);
                      $res = mysqli_query($tng_conn, "SELECT * FROM wallet WHERE phone='$phone' ORDER BY id DESC LIMIT 10");
                  }

                  if ($res && mysqli_num_rows($res) > 0) {
                      $srNo = 1;
                      while ($row = mysqli_fetch_assoc($res)) {
                          $statusClass = ($row['status'] ?? '') == 'success' ? 'success' : 'danger';
                          $statusIcon = ($row['status'] ?? '') == 'success' ? 'fa-check-circle' : 'fa-times-circle';
                          
                          echo "<tr>
                              <td class='text-center'><span class='badge bg-light text-dark'>$srNo</span></td>
                              <td><code class='text-truncate' style='max-width: 120px;'>".htmlspecialchars($row['BANKTXNID'] ?? '')."</code></td>
                              <td class='text-end fw-bold text-success'>₹".number_format($row['amount'] ?? '0', 2)."</td>
                              <td>".htmlspecialchars($row['RESPMSG'] ?? '')."</td>
                              <td><span class='badge bg-light text-dark'>".htmlspecialchars($row['PAYMENTMODE'] ?? '')."</span></td>
                              <td class='text-center'><span class='badge bg-$statusClass'><i class='fas $statusIcon me-1'></i>".htmlspecialchars(ucfirst($row['status'] ?? ''))."</span></td>
                              <td><small class='text-muted'>".htmlspecialchars($row['txn_date'] ?? '')."</small></td>
                          </tr>";
                          $srNo++; 
                      }
                  } else {
                      echo "<tr><td colspan='7' class='text-center py-4 text-muted'><i class='fas fa-inbox me-2'></i>No transactions found</td></tr>";
                  }
                  ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<?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 class="text-center mb-3">
            <div class="qr-container mb-3">
                <img src="' . $data['qr'] . '" class="qr-image">
            </div>
            <div id="txnStatus" class="status-indicator">
                <i class="fas fa-sync-alt fa-spin me-2"></i> Waiting for payment...
            </div>
        </div>';
    
   
    if ($data['type'] === "bharatpay") {
        $html .= '
        <div class="utr-section mt-3 p-3 bg-warning bg-opacity-10 border-start border-warning border-3">
            <h6 class="mb-2 text-warning"><i class="fas fa-exclamation-triangle me-2"></i>UTR Number Required</h6>
            <p class="small text-muted mb-2">After payment, enter the <strong>UTR number</strong> from your bank transaction.</p>
            <div class="input-group">
                <span class="input-group-text bg-white"><i class="fas fa-receipt text-warning"></i></span>
                <input id="utrInput" type="text" class="form-control" placeholder="Enter UTR Number">
            </div>
        </div>';
    }
    
    echo '<script>
    Swal.fire({
        title: "' . ($data['type'] === "bharatpay" ? "Scan QR & Enter UTR" : "Scan QR to Pay") . '",
        html: `' . $html . '`,
        showConfirmButton: ' . ($data['type'] === "bharatpay" ? 'true' : 'false') . ',
        confirmButtonText: "✅ Verify Payment",
        confirmButtonColor: "#28a745",
        showCancelButton: true,
        cancelButtonText: "⬅ Back",
        cancelButtonColor: "#6c757d",
        allowOutsideClick: false,
        width: "420px",
        customClass: {
            popup: "qr-popup",
            header: "qr-header",
            content: "qr-content"
        },
        didOpen: () => {
            if("' . $data['type'] . '" === "paytm"){
                checkPaytmStatus("' . $data['application_no'] . '");
            } else if("' . $data['type'] . '" === "bharatpay") {
                setTimeout(() => {
                    const utrInput = document.getElementById("utrInput");
                    if(utrInput) utrInput.focus();
                }, 300);
            }
        }
    }).then(result => {
        if(result.dismiss === Swal.DismissReason.cancel){
            window.location.href = "wallet.php";
        }
        else if(result.isConfirmed && "' . $data['type'] . '" === "bharatpay"){
            let utr = document.getElementById("utrInput").value.trim();
            if(!utr) {
                Swal.showValidationMessage("Please enter UTR number");
                return false;
            }
            
            if(utr.length < 8) {
                Swal.showValidationMessage("UTR number seems too short");
                return false;
            }
            
            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>';

}
?>

<!-- Modern and professional styling -->
<style>
/* QR Popup Styling */
.swal2-popup.qr-popup {
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.15);
    overflow: hidden;
}

.swal2-title.qr-header {
    color: #2c3e50;
    font-weight: 600;
    padding: 20px 20px 10px;
    font-size: 20px;
    border-bottom: 1px solid #f1f3f4;
    margin-bottom: 0;
}

.swal2-content.qr-content {
    padding: 20px;
}

.qr-container {
    background: white;
    padding: 15px;
    border-radius: 12px;
    display: inline-block;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    border: 1px solid #e9ecef;
}

.qr-image {
    width: 200px;
    height: 200px;
    border-radius: 8px;
}

.payment-info {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
    color: white;
    border: none;
}

.payment-info h5 {
    font-weight: 700;
    margin-bottom: 5px;
}

.status-indicator {
    padding: 12px;
    background: #e8f4fd;
    border-radius: 8px;
    border-left: 4px solid #2196F3;
    color: #2c3e50;
    font-weight: 500;
    font-size: 14px;
}

.utr-section {
    border-radius: 8px;
}

/* Animation for status updates */
@keyframes pulse {
    0% { opacity: 1; }
    50% { opacity: 0.7; }
    100% { opacity: 1; }
}

.pulse {
    animation: pulse 2s infinite;
}

/* Enhanced form styling */
.card {
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.1) !important;
}

.bg-gradient-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    font-weight: 600;
    transition: all 0.3s ease;
}

.btn-primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

/* Table enhancements */
.table > thead {
    border-bottom: 2px solid #667eea;
}

.table > thead th {
    font-weight: 600;
    font-size: 0.85rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: #495057;
    padding: 12px 8px;
}

.table tbody tr {
    transition: background-color 0.2s ease;
}

.table tbody tr:hover {
    background-color: #f8f9ff !important;
}

/* Quick action buttons */
.btn-outline-primary.rounded-pill {
    border-width: 1.5px;
    font-weight: 500;
    transition: all 0.2s ease;
}

.btn-outline-primary.rounded-pill:hover {
    transform: translateY(-1px);
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .card-body {
        padding: 1rem;
    }
    
    .qr-image {
        width: 160px;
        height: 160px;
    }
    
    .swal2-popup.qr-popup {
        width: 90% !important;
        margin: 5% auto;
    }
}
</style>

<script>
function setAmount(amount) {
    document.getElementById('amount').value = amount;
    document.getElementById('amount').focus();
}

function checkPaytmStatus(application_no) {
    const statusDiv = document.getElementById("txnStatus");
    let checkCount = 0;
    const maxChecks = 60; 
    
    statusDiv.classList.add('pulse');
    
    const intervalId = setInterval(async () => {
        try {
            checkCount++;
            statusDiv.innerHTML = `<i class="fas fa-sync-alt fa-spin me-2"></i> Checking payment status... (${checkCount}/${maxChecks})`;
            
            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);
                statusDiv.classList.remove('pulse');
                statusDiv.innerHTML = `<i class="fas fa-check-circle text-success me-2"></i> Payment Successful!`;
                
                setTimeout(() => {
                    Swal.close();
                    Swal.fire({
                        icon: 'success',
                        title: 'Payment Successful 🎉',
                        html: `<div class="text-start p-2" style="font-size:14px;">
                                 <p><b>Amount:</b> ₹${data.data.amount}</p>
                                 <p><b>Payer:</b> ${data.data.payer}</p>
                                 <p><b>Date:</b> ${data.data.date}</p>
                               </div>`,
                        confirmButtonColor: '#4e54c8',
                        showCancelButton: false
                    }).then(() => { 
                        window.location.href = 'wallet.php'; 
                    });
                }, 1000);
            } else if (data.status === 'error') {
                statusDiv.innerHTML = `<i class="fas fa-exclamation-triangle text-danger me-2"></i> ${data.message}`;
                
                if (data.message.includes('not successful') || data.message.includes('failed')) {
                    clearInterval(intervalId);
                    statusDiv.classList.remove('pulse');
                    statusDiv.innerHTML = `<i class="fas fa-times-circle text-danger me-2"></i> Payment failed`;
                }
            }
            
            if (checkCount >= maxChecks) {
                clearInterval(intervalId);
                statusDiv.classList.remove('pulse');
                statusDiv.innerHTML = `<i class="fas fa-clock text-muted me-2"></i> Timeout - Contact support`;
            }
        } catch (error) {
            console.error('Error checking payment status:', error);
            statusDiv.innerHTML = `<i class="fas fa-exclamation-circle text-warning me-2"></i> Error - 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 -->

          
<!--end page wrapper -->

<?php include('../template/tngweb/footer.php'); ?>

<!-- ✅ DataTables CDN & Scripts -->
<script src="../template/tngweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/tngweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/tngweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>


<script>
  $(document).ready(function() {
    $('#walletTable').DataTable({
      lengthChange: false,
      pageLength: 10,
      order: [], // disables initial sorting
      columnDefs: [
        { orderable: false, targets: 0 } // prevent sorting on SR column
      ],
      buttons: ['copy', 'excel', 'pdf', 'print'],
      dom: '<"d-flex justify-content-between align-items-center mb-3"Bf>rt<"d-flex justify-content-between align-items-center"ip>',
      language: {
        search: "Search transactions:",
        paginate: {
          previous: "<i class='fas fa-chevron-left'></i>",
          next: "<i class='fas fa-chevron-right'></i>"
        }
      }
    });
  });
</script>