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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_status']) && !empty($_POST['record_id'])) {
    $recordId = intval($_POST['record_id']);
    $user = $udata['phone'];
    
   
    $query = mysqli_query($tng_conn, "SELECT * FROM aadhar_pan_history WHERE id=$recordId AND user_phone='$user' AND status='Pending'");
    if (mysqli_num_rows($query) == 0) {
        echo "<script>Swal.fire('Error','Record not found or already processed','error').then(()=>window.location='aadhar_pan_history.php');</script>";
        exit;
    }
    $record = mysqli_fetch_assoc($query);
    $aadhar = $record['aadhar_number'];
    

    $resdata = pan_find_apply_status_verificationapi_run([
        'aadhar' => $aadhar,
    ]);
    $sampleCode = $resdata['sampleCode'] ?? '';
    $panName = $resdata['pan'] ?? '';
    $apiStatus = $resdata['status'] ?? 'Pending';
    
    $newStatus = ($apiStatus == 'Success' && $sampleCode == '200') ? 'Success' : 'Pending';
    
    mysqli_query($tng_conn, "UPDATE aadhar_pan_history SET 
        status='$newStatus',
        pan_name='".mysqli_real_escape_string($tng_conn, $panName)."',
        response_data='".mysqli_real_escape_string($tng_conn, json_encode($resdata))."'
        WHERE id=$recordId");
    
    if ($newStatus == 'Success') {
        echo "<script>Swal.fire({icon:'success',title:'Status Updated',text:'PAN Found: $panName',timer:2500,showConfirmButton:false}).then(()=>window.location='aadhar_pan_history.php');</script>";
    } else {
        echo "<script>Swal.fire({icon:'info',title:'Still Processing',text:'{$resdata['error']}.',timer:2500}).then(()=>window.location='aadhar_pan_history.php');</script>";
    }
    exit;
}

$historyQuery = mysqli_query($tng_conn, "SELECT * FROM aadhar_pan_history 
    WHERE user_phone = '".$udata['phone']."' 
    ORDER BY created_at DESC");
?>

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">

<div class="page-wrapper">
<div class="page-content">
<div class="card luxury-card shadow-lg border-0">
<div class="card-body">

<div class="d-flex justify-content-between align-items-center mb-4">
  <a href="aadhar_to_pan.php" class="btn btn-primary rounded-pill px-4">
    <i class="fa fa-plus me-2"></i> New Request
  </a>
  <h4 class="fw-bold text-primary mb-0">ðŸ“œ Aadhar â†’ PAN History</h4>
</div>

<div class="table-responsive">
<table id="historyTable" class="table table-hover align-middle text-center w-100">
<thead class="luxury-thead">
<tr>
  <th>#</th>
  <th>Date & Time</th>
  <th>Aadhaar Number</th>
  <th>PAN</th>
  <th>Status</th>
  <th>Action</th>
</tr>
</thead>
<tbody>
<?php 
$count = 0;
while($row = mysqli_fetch_assoc($historyQuery)): 
$count++;
$statusText = $row['status'];
$badgeClass = $statusText == 'Pending' ? 'badge bg-warning text-dark' : ($statusText == 'Success' ? 'badge bg-success' : 'badge bg-danger');
?>
<tr>
  <td><?= $count ?></td>
  <td><?= date('d-m-Y h:i A', strtotime($row['created_at'])) ?></td>
  <td><?= htmlspecialchars($row['aadhar_number']) ?></td>
  <td><?= htmlspecialchars($row['pan_name'] ?? '-') ?></td>
  <td><span class="<?= $badgeClass ?> px-3 py-2 rounded-pill"><?= $statusText ?></span></td>
  <td>
    <?php if($statusText == 'Pending'): ?>
    <form method="post" style="display:inline;">
      <input type="hidden" name="record_id" value="<?= $row['id'] ?>">
      <button type="submit" name="check_status" class="btn btn-sm btn-warning rounded-pill px-3">
        ðŸ”„ Check Status
      </button>
    </form>
    <?php else: ?>
    <span class="text-muted">â€”</span>
    <?php endif; ?>
  </td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>

</div>
</div>
</div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

<script>
$(document).ready(function(){
  const table = $('#historyTable').DataTable({
    responsive: true,
    pageLength: 10,
    order: [[1, 'desc']],
    dom: "<'row mb-3'<'col-md-6'l><'col-md-6 text-end'B>>" +
         "<'row'<'col-12'tr>>" +
         "<'row mt-3'<'col-md-5'i><'col-md-7'p>>",
    buttons: [
      { extend: 'excel', className: 'btn btn-success btn-sm rounded-pill px-3' },
      { extend: 'pdf', className: 'btn btn-danger btn-sm rounded-pill px-3' },
      { extend: 'print', className: 'btn btn-primary btn-sm rounded-pill px-3' }
    ],
    columnDefs: [{ orderable: false, targets: 0 }]
  });
  table.on('order.dt search.dt', function(){
    table.column(0, {search:'applied', order:'applied'}).nodes().each((cell,i)=>cell.innerHTML=i+1);
  }).draw();
});
</script>

<style>
.luxury-card{
  border-radius:20px;
  background:linear-gradient(145deg,#fff,#eef2ff);
}
.luxury-thead th{
  background:linear-gradient(135deg,#1e1e2f,#2f3350);
  color:#fff;
}
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<?php include('../template/tngweb/footer.php'); ?>