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

echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';

// ✅ Check Status POST
if (isset($_POST['check_status'], $_POST['application_no'])) {
    $application_no = mysqli_real_escape_string($tng_conn, $_POST['application_no']);

    $request = ['application_no' => $application_no];
    $resdata = lerning_exam_checkexam_api_run($request);

    $swal_icon = 'info';
    $swal_title = 'Status Check';
    $swal_text = 'Something went wrong. Please try again.';

    if (!empty($resdata)) {
        if ($resdata['Message'] === "Success" && $resdata['sampleCode'] == 200) {
            mysqli_query($tng_conn, "UPDATE llexam_requests 
                SET status='Success', pdf='" . mysqli_real_escape_string($tng_conn, $resdata['pdf']) . "' 
                WHERE application_no='" . $application_no . "'");

            $swal_icon = 'success';
            $swal_title = '✅ Exam PDF Ready!';
            $swal_text = 'Learning Licence Exam PDF generated successfully!';
        } elseif ($resdata['Message'] === "Refunded" && $resdata['sampleCode'] == 402) {
            $q = mysqli_query($tng_conn, "SELECT * FROM llexam_requests WHERE application_no='$application_no'");
            $row = mysqli_fetch_assoc($q);
            if ($row && $row['status'] !== 'Refunded') {
                mysqli_query($tng_conn, "UPDATE users SET balance=balance+" . intval($row['amount']) . " WHERE phone='" . $row['phone'] . "'");
                mysqli_query($tng_conn, "UPDATE llexam_requests SET status='Refunded' WHERE application_no='$application_no'");
            }
            $swal_icon = 'warning';
            $swal_title = '💸 Refunded';
            $swal_text = 'Amount refunded to user wallet successfully.';
        } else {
            mysqli_query($tng_conn, "UPDATE llexam_requests SET status='Pending', request_time=NOW() WHERE application_no='$application_no'");
            $swal_icon = 'info';
            $swal_title = '⏳ Still Processing';
            $swal_text = 'Exam result is still pending. Please check again after a few minutes.';
        }
    }

    echo "
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        Swal.fire({
          icon: '$swal_icon',
          title: '$swal_title',
          text: '$swal_text',
          confirmButtonColor: '#3085d6',
          confirmButtonText: 'OK',
          showClass: { popup: 'animate__animated animate__fadeInDown' },
          hideClass: { popup: 'animate__animated animate__fadeOutUp' }
        }).then(() => {
          window.location.href = window.location.href;
        });
      });
    </script>";
}
?>

<!--start page wrapper -->
<div class="page-wrapper">
  <div class="page-content">
    <div class="card radius-15 shadow-lg border-0">
      <div class="card-body">
        <!-- Back Button -->
        <div class="d-flex align-items-center justify-content-between mb-3">
          <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>
          <h5 class="mb-0 fw-bold text-primary">💰 All LL Exam History</h5>
        </div>
        <hr>

        <div class="table-responsive">
          <table id="walletTable" class="table table-hover table-striped align-middle text-center">
            <thead class="table-dark">
              <tr>
                <th>SL.</th>
                <th>User Appl No</th>
                <th>Application No</th>
                <th>Status</th>
                <th>Download</th>
                <th>Request Time</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <?php
              if ($udata['type'] == 'admin') {
                  $res = mysqli_query($tng_conn, "SELECT * FROM llexam_requests ORDER BY id DESC");
              } else {
                  $res = mysqli_query($tng_conn, "SELECT * FROM llexam_requests WHERE phone='" . $udata['phone'] . "' ORDER BY id DESC");
              }

              $sr = 1; // Serial number
              while ($row = mysqli_fetch_assoc($res)) {
                  $request_time = strtotime($row['request_time']);
                  $current_time = time();
                  $elapsed = $current_time - $request_time;
                  $remainingCountdown = 300 - $elapsed; // 5 min countdown
                  ?>
                  <tr>
                      <td><?= $sr++; ?></td>
                      <td><?= htmlspecialchars($row['user_applno']) ?></td>
                      <td><?= htmlspecialchars($row['application_no']) ?></td>
                      <td><?= htmlspecialchars($row['status']) ?></td>
                      <td>
                          <?php if ($row['status'] === 'Success' && !empty($row['pdf'])): ?>
                              <form method="POST" action="download.php" class="d-inline">
                                <input type="hidden" name="user_applno" value="Llexam_<?= $row['user_applno'] ?>">
                                <textarea name="file" hidden><?= $row['pdf'] ?></textarea>
                                <button type="submit" class="btn btn-success btn-sm px-3 py-2 rounded-pill shadow-sm">
                                  <i class="fa fa-download me-1"></i> Download
                                </button>
                              </form>
                          <?php else: ?>
                              ---
                          <?php endif; ?>
                      </td>
                      <td><?= $row['date']; ?></td>
                      <td>
                          <?php if ($row['status'] === 'Pending' && $remainingCountdown > 0): ?>
                              <span class="countdown badge bg-warning text-dark"
                                  data-remaining="<?= $remainingCountdown ?>"
                                  data-orderid="<?= htmlspecialchars($row['application_no']) ?>">
                              </span>
                          <?php elseif ($row['status'] !== 'Success' && $row['status'] !== 'Refunded'): ?>
                              <form method="post">
                                  <input type="hidden" name="application_no" value="<?= htmlspecialchars($row['application_no']) ?>">
                                  <button type="submit" name="check_status" class="btn btn-primary btn-sm rounded-pill px-3 py-1 shadow-sm">
                                    <i class="bi bi-check-circle me-1"></i> Check Now
                                  </button>
                              </form>
                          <?php endif; ?>
                      </td>
                  </tr>
              <?php } ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
<!--end page wrapper -->

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

<!-- DataTables & 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 src="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.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.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

<script>
  $(document).ready(function() {
    $('#walletTable').DataTable({
      lengthChange: false,
      pageLength: 10,
      order: [[0, "asc"]],
      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>'
    });
  });
</script>

<style>
  .table thead th { vertical-align: middle; font-weight: 600; letter-spacing: 0.3px; }
  .table tbody tr:hover { background: #f5f8ff; transition: 0.2s ease; }
  .card { background: #fff; border-radius: 15px; }
  .btn-outline-primary { border-color: #0055ff; color: #0055ff; }
  .btn-outline-primary:hover { background-color: #0055ff; color: #fff; }
  .dataTables_wrapper .dataTables_filter input { border-radius: 8px; padding: 5px 10px; }
  .dataTables_wrapper .dataTables_paginate .paginate_button { border-radius: 5px; }
  .dataTables_wrapper .dt-buttons .btn { border-radius: 20px !important; font-size: 0.85rem; margin-right: 6px; }
  .badge { font-size: 0.8rem; padding: 6px 10px; }
</style>
