<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');
checkGatewayStatus();

/* ===== USER ===== */
$phone = $udata['phone'];
$balance = number_format($udata['balance'] ?? 0, 2);
$minAmount = intval(XyZ_val('balance_add_minumum_amount')) + 1;

/* ===== HISTORY ===== */
$res = mysqli_query(
 $tng_conn,
 "SELECT * FROM wallet 
  WHERE phone='".mysqli_real_escape_string($tng_conn,$phone)."'
  ORDER BY id DESC LIMIT 20"
);
?>

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<style>
.wallet-card{border-radius:16px}
.wallet-balance{
 background:linear-gradient(135deg,#4e54c8,#8f94fb);
 color:#fff
}
.wallet-balance h2{font-weight:700}
.badge-success{background:#28a745}
.badge-failed{background:#dc3545}
.timer{font-size:14px;color:#555;margin-top:6px}
.table td{vertical-align:middle}
</style>

<div class="page-wrapper">
<div class="page-content">

<!-- ===== BALANCE + ADD ===== -->
<div class="row mb-4">
 <div class="col-md-6">
  <div class="card wallet-card wallet-balance shadow">
   <div class="card-body">
    <h6>Wallet Balance</h6>
    <h2>₹<?= $balance ?></h2>
    <small>Mobile: <?= htmlspecialchars($phone) ?></small>
   </div>
  </div>
 </div>

 <div class="col-md-6">
  <div class="card wallet-card shadow">
   <div class="card-body">
    <h6>Add Money</h6>
    <form id="addMoneyForm">
     <div class="input-group input-group-lg">
      <span class="input-group-text">₹</span>
      <input type="number"
       name="amount"
       class="form-control"
       min="<?= $minAmount ?>"
       placeholder="Enter amount (Minimum ₹<?= $minAmount ?>)"
       required>
      <button class="btn btn-primary">
        <i class="fa fa-plus"></i> Add
      </button>
     </div>
     <small class="text-muted">
       Minimum recharge amount ₹<?= $minAmount ?>
     </small>
    </form>
   </div>
  </div>
 </div>
</div>

<!-- ===== HISTORY ===== -->
<div class="card wallet-card shadow">
<div class="card-header bg-white">
 <h6 class="mb-0">
  <i class="fa fa-clock me-1"></i> Wallet Transaction History
 </h6>
</div>

<div class="card-body">
<table id="walletTable" class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Mobile</th>
<th>UTR</th>
<th>Amount</th>
<th>Status</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php $i=1; while($row=mysqli_fetch_assoc($res)): ?>
<tr>
<td><?= $i++ ?></td>
<td><span class="badge bg-secondary"><?= htmlspecialchars($row['phone']) ?></span></td>
<td><code><?= htmlspecialchars($row['BANKTXNID']) ?></code></td>
<td class="fw-semibold text-success">₹<?= number_format($row['amount'],2) ?></td>
<td>
 <span class="badge <?= $row['status']=='success'?'badge-success':'badge-failed' ?>">
  <?= ucfirst($row['status']) ?>
 </span>
</td>
<td><?= date('d M Y h:i A',strtotime($row['txn_date'])) ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</div>

</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<script>
$('#walletTable').DataTable({
 ordering:false,
 pageLength:10,
 language:{search:"Search transactions"}
});

/* ===== ADD MONEY ===== */
document.getElementById('addMoneyForm').onsubmit = async e=>{
 e.preventDefault();

 const r = await fetch('qr_generate.php',{
  method:'POST',
  body:new FormData(e.target)
 });
 const d = await r.json();

 if(d.status==='success'){
  location.href='wallet.php?show_qr=1';
 }else{
  Swal.fire('Error',d.message,'error');
 }
};
</script>

<?php if(isset($_GET['show_qr'],$_SESSION['qr_data'])):
$d=$_SESSION['qr_data']; ?>

<script>
Swal.fire({
 title:"<?= $d['type']==='paytm'?'Scan QR to Pay':'Scan QR & Enter UTR' ?>",
 html:`
 <img src="<?= $d['qr'] ?>" width="220"><br>

 <?php if($d['type']==='paytm'): ?>
 <div id="txnStatus">
  ⏳ Waiting for payment...
  <div class="timer">
   Time left: <span id="timeLeft">05:00</span>
  </div>
 </div>
 <?php else: ?>
 <input id="utrInput" class="swal2-input" placeholder="Enter UTR Number">
 <?php endif; ?>
 `,
 showConfirmButton: <?= $d['type']==='bharatpay'?'true':'false' ?>,
 allowOutsideClick:false,
 didOpen:()=>{
  <?php if($d['type']==='paytm'): ?>
  setTimeout(()=>{
    startPaytmTimer("<?= $d['application_no'] ?>");
  },300);
  <?php endif; ?>
 }
}).then(r=>{
 if(r.isConfirmed && "<?= $d['type'] ?>"==="bharatpay"){
  submitBharatPay();
 }
});
</script>
<?php endif; ?>

<script>
/* ===== PAYTM TIMER (FINAL FIX) ===== */
function startPaytmTimer(app){

 let time = 300;

 const popup = Swal.getPopup();
 if(!popup) return;

 const tEl = popup.querySelector('#timeLeft');
 const sEl = popup.querySelector('#txnStatus');
 if(!tEl || !sEl) return;

 const timer = setInterval(async ()=>{
  time--;

  const m = String(Math.floor(time/60)).padStart(2,'0');
  const s = String(time%60).padStart(2,'0');
  tEl.innerText = m+':'+s;

  if(time % 5 === 0){
   const fd=new FormData();
   fd.append('application_no',app);

   try{
    const r=await fetch('payment_status.php',{method:'POST',body:fd});
    const d=await r.json();

    if(d.status==='success'){
     clearInterval(timer);
     Swal.fire('Payment Successful','₹'+d.data.amount,'success')
      .then(()=>location.href='wallet.php');
    }
    if(d.status==='error'){
     clearInterval(timer);
     Swal.fire('Error',d.message,'error');
    }
   }catch(e){}
  }

  if(time<=0){
   clearInterval(timer);
   sEl.innerHTML='⌛ Payment timeout';
  }
 },1000);
}

/* ===== BHARATPAY ===== */
function submitBharatPay(){
 const utr=document.getElementById('utrInput').value.trim();
 if(!utr){Swal.showValidationMessage('Enter UTR');return;}

 const fd=new FormData();
 fd.append('type','bharatpay');
 fd.append('application_no',"<?= $d['application_no'] ?? '' ?>");
 fd.append('utr',utr);

 fetch('payment_status.php',{method:'POST',body:fd})
 .then(r=>r.json())
 .then(d=>{
  if(d.status==='success'){
   Swal.fire('Payment Successful','₹'+d.data.amount,'success')
    .then(()=>location.href='wallet.php');
  }else{
   Swal.fire('Error',d.message ?? 'Payment failed','error');
  }
 });
}
</script>

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