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

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


function checkExamStatus($application_no, $tng_apiurl, $tng_apikey) {
    $status_url = $tng_apiurl . "/api/llexam/v1/checkexam-status?application_no=" . rawurlencode($application_no) . "&apikey=" . rawurlencode($tng_apikey);
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $status_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET'
    ]);
    $response = curl_exec($curl);
    curl_close($curl);
    return json_decode($response, true);
}


if (isset($_POST['check_status'], $_POST['application_no'])) {
    $application_no = mysqli_real_escape_string($ahk_conn, $_POST['application_no']);

   
    $resdata = checkExamStatus($application_no, $tng_apiurl, $tng_apikey);

    if (!empty($resdata)) {
        if ($resdata['Message'] === "Success" && $resdata['sampleCode'] == 200) {
           
            mysqli_query($ahk_conn, "UPDATE llexam_requests 
                SET status='Success', pdf='" . mysqli_real_escape_string($ahk_conn, $resdata['pdf']) . "' 
                WHERE application_no='" . $application_no . "'");
        } elseif ($resdata['Message'] === "Refunded" && $resdata['sampleCode'] == 402) {
           
            $q = mysqli_query($ahk_conn, "SELECT * FROM llexam_requests WHERE application_no='$application_no'");
            $row = mysqli_fetch_assoc($q);
            if ($row && $row['status'] !== 'Refunded') {
                mysqli_query($ahk_conn, "UPDATE users SET balance=balance+" . intval($row['amount']) . " WHERE phone='" . $row['phone'] . "'");
                mysqli_query($ahk_conn, "UPDATE llexam_requests SET status='Refunded' WHERE application_no='$application_no'");
            }
        } else {
           
            mysqli_query($ahk_conn, "UPDATE llexam_requests SET status='Pending', request_time=NOW() WHERE application_no='$application_no'");
        }
    }
}
?>


<div class="page-wrapper">
<div class="page-content">
    <div class="card radius-10">
        <div class="card-body">
            <h5 class="mb-0">LL Exam Requests</h5>
            <hr>
            <div class="table-responsive">
                <table id="example2" class="table align-middle mb-0">
                    <thead class="table-light">
                        <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($ahk_conn, "SELECT * FROM llexam_requests ORDER BY date DESC");
                        } else {
                            $res = mysqli_query($ahk_conn, "SELECT * FROM llexam_requests WHERE phone='" . $udata['phone'] . "' ORDER BY date DESC");
                        }

                        $x = 0;
                        while ($row = mysqli_fetch_assoc($res)) {
                            $x++;
                            $request_time = strtotime($row['request_time']);
                            $current_time = time();
                            $elapsed = $current_time - $request_time;
                            $remainingCountdown = 300 - $elapsed; 
                            ?>
                            <tr>
                                <td><?= $x ?></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'])): ?>
                                        <a href="<?= $row['pdf'] ?>" download="Llexam_<?= $row['user_applno'] ?>.pdf" class="btn btn-success btn-sm">Download</a>
                                    <?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">Check Now</button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php } ?>
                     </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</div>
<!--end page wrapper -->

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

<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/js/jquery.min.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/jquery.dataTables.min.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/dataTables.bootstrap5.min.js"></script>

<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>
<script>
$(document).ready(function() {
    $('#example2').DataTable();

    function startCountdown() {
        $(".countdown").each(function () {
            var el = $(this);
            var remaining = parseInt(el.data("remaining"));
            if (remaining > 0) {
                var timer = setInterval(function () {
                    if (remaining <= 0) {
                        clearInterval(timer);
                        // Auto-submit to check API
                        var form = $('<form method="post">' +
                            '<input type="hidden" name="application_no" value="' + el.data("orderid") + '">' +
                            '<input type="hidden" name="check_status" value="1">' +
                            '</form>');
                        $('body').append(form);
                        form.submit();
                    } else {
                        var minutes = Math.floor(remaining / 60);
                        var seconds = remaining % 60;
                        el.text('Wait ' + minutes + ':' + (seconds < 10 ? '0' : '') + seconds);
                        remaining--;
                    }
                }, 1000);
            }
        });
    }
    startCountdown();
});
</script>
