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

error_reporting(0); // Remove warning/notice

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


/* =======================================================
   ðŸ”¥ MASTER API FUNCTION
========================================================= */
if (!function_exists("lerning_exam_checkexam_api_run")) {

    function lerning_exam_checkexam_api_run($request) {

        $apiUrl = "https://a1.allrto.shop/api/llexam_status.php";
        $api_key = "TESTAPIKEY123456789";

        $postData = [
            'api_key'        => $api_key,
            'application_no' => $request['application_no']
        ];

        $ch = curl_init($apiUrl);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $postData,
            CURLOPT_TIMEOUT => 30
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        return json_decode($response, true);
    }
}


/* =======================================================
   ðŸ”¥ CLIENT CLICKS "CHECK NOW"
========================================================= */
if (isset($_POST['check_status'], $_POST['application_no'])) {

    $application_no = mysqli_real_escape_string($master_conn, $_POST['application_no']);
    $request = ['application_no' => $application_no];

    $resdata = lerning_exam_checkexam_api_run($request);

    $icon = "info";
    $title = "Status Check";
    $msg = "Try again shortly.";

    if (!empty($resdata)) {

        /* SUCCESS */
        if ($resdata['sampleCode'] == 200) {

            mysqli_query($master_conn,
                "UPDATE llexam_requests 
                 SET status='Success',
                     pdf='".mysqli_real_escape_string($master_conn, $resdata['pdf'])."',
                     remark='PDF Generated Successfully'
                 WHERE application_no='$application_no'"
            );

            $icon = "success";
            $title = "PDF Ready";
            $msg = "Your LL Exam PDF Generated Successfully!";
        }

        /* REFUND */
        elseif ($resdata['sampleCode'] == 402) {

            mysqli_query($master_conn,
                "UPDATE llexam_requests 
                 SET status='Refunded',
                     remark='Amount Refunded'
                 WHERE application_no='$application_no'"
            );

            $icon = "warning";
            $title = "Refunded";
            $msg = "Amount refunded to wallet";
        }

        /* PENDING */
        else {

            mysqli_query($master_conn,
                "UPDATE llexam_requests 
                 SET status='Pending',
                     remark='Still Pending',
                     request_time=NOW()
                 WHERE application_no='$application_no'"
            );

            $icon = "info";
            $title = "Pending";
            $msg = "Check again after few minutes.";
        }
    }

    echo "
    <script>
    Swal.fire({ icon:'$icon', title:'$title', text:'$msg' })
    .then(()=>{ window.location.href = window.location.href; });
    </script>";
}

?>

<!-- ======================= PREMIUM UI CSS ======================= -->

<style>

.card-custom {
    background: #ffffff;
    border-radius: 18px;
    padding: 25px;
    box-shadow: 0 8px 18px rgba(0,0,0,0.12);
}
.table-custom thead {
    background: linear-gradient(90deg, #004bff, #007bff);
    color: white;
}
.table-custom tbody tr:hover {
    background: #eef5ff;
}
.btn-premium {
    background: linear-gradient(90deg,#005cff,#00a2ff);
    border: none;
    color: white;
    padding: 6px 18px;
    border-radius: 50px;
    font-weight: 600;
}
.badge-soft { padding: 6px 12px; border-radius: 50px; font-size: 12px; }
.badge-success-soft { background:#d6ffe0; color:#048f36; }
.badge-warning-soft { background:#fff1cc; color:#d17b00; }
.badge-danger-soft { background:#ffd6d6; color:#c30000; }

</style>


<!-- ======================= PAGE BODY ======================= -->

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

    <div class="card card-custom">

      <div class="d-flex justify-content-between align-items-center mb-3">
        <a onclick="history.back();" class="btn btn-outline-primary rounded-pill px-4 fw-bold">
            <i class="bi bi-arrow-left-circle"></i> Back
        </a>

        <h4 class="fw-bold text-primary m-0">ðŸ“„ LL Exam â€“ Request History</h4>
      </div>

      <hr>

      <div class="table-responsive">
        <table id="walletTable" class="table table-hover table-custom text-center align-middle">

            <thead>
              <tr>
                <th>SL</th>
                <th>User Appl No</th>
                <th>Application No</th>
                <th>Status</th>
                <th>Remark</th>
                <th>PDF</th>
                <th>Request Time</th>
                <th>Action</th>
              </tr>
            </thead>

            <tbody>

<?php
$res = mysqli_query($master_conn,
    "SELECT * FROM llexam_requests WHERE phone='".$udata['phone']."' ORDER BY id DESC"
);

$sr = 1;
while ($row = mysqli_fetch_assoc($res)) {

$reqTime = $row['request_time'] ?? "---";

?>

<tr>

    <td><strong><?= $sr++; ?></strong></td>

    <td><?= htmlspecialchars($row['user_applno']); ?></td>

    <td><?= htmlspecialchars($row['application_no']); ?></td>

    <td>
        <?php if ($row['status']=="Success"): ?>
            <span class="badge badge-success-soft">Success</span>
        <?php elseif ($row['status']=="Refunded"): ?>
            <span class="badge badge-danger-soft">Refunded</span>
        <?php else: ?>
            <span class="badge badge-warning-soft">Pending</span>
        <?php endif; ?>
    </td>

    <td><?= $row['remark'] ?: "---"; ?></td>

    <td>
        <?php if ($row['status']=="Success" && !empty($row['pdf'])): ?>
            <form method="POST" action="download1.php">
                <input type="hidden" name="user_applno" value="LL_<?= $row['user_applno']; ?>">
                <textarea name="file" hidden><?= $row['pdf']; ?></textarea>
                <button class="btn btn-success btn-sm rounded-pill px-3">Download</button>
            </form>
        <?php else: ?>
            <span class="text-muted">---</span>
        <?php endif; ?>
    </td>

    <td><?= $reqTime ?></td>

    <td>
        <?php if ($row['status']!="Success" && $row['status']!="Refunded"): ?>
            <form method="POST">
                <input type="hidden" name="application_no" value="<?= $row['application_no']; ?>">
                <button class="btn btn-premium btn-sm" name="check_status">Check Now</button>
            </form>
        <?php else: ?>
            <span class="text-muted">---</span>
        <?php endif; ?>
    </td>

</tr>

<?php } ?>

            </tbody>

        </table>
      </div>

    </div>

  </div>
</div>


<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<script>
$(document).ready(function(){
    $('#walletTable').DataTable({
        pageLength: 10,
        order: [[0, "desc"]]
    });
});
</script>

</html>
