<?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>';
echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>';

// Handle form POST for checking status (always hit API)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_status'], $_POST['order_id'])) {
    $order_id = mysqli_real_escape_string($ahk_conn, $_POST['order_id']);
    $status_url = "$tng_apiurl/api/ration-to-uid-all/v1/ration-to-uid-all-status?apikey=$tng_apikey&order_id=$order_id";

    $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);

    $resdata = json_decode($response, true);

    $status  = $resdata['Message'] ?? 'Unknown';
    $message = $resdata['message'] ?? ($resdata['error'] ?? 'No message from API');

    // DB update only if API says Success
    if ($status === 'Success') {
        mysqli_query($ahk_conn, "UPDATE ration_to_aadhar_requests SET status='Success' WHERE order_id='$order_id'");
    }

    // Prepare member list HTML
    $member_html = '';
    if (!empty($resdata['memberDetailsList']) && is_array($resdata['memberDetailsList'])) {
        $member_html .= '<div style="max-height:300px;overflow:auto;font-size:14px">';
        $member_html .= '<table border="1" cellspacing="0" cellpadding="5" style="width:100%;border-collapse:collapse;text-align:left;font-size:14px">';
        $member_html .= '<tr style="background:#f2f2f2"><th>SL</th><th>Name</th><th>Member ID</th><th>Aadhaar</th><th>Relationship</th></tr>';
        foreach ($resdata['memberDetailsList'] as $member) {
            $member_html .= '<tr>
                <td>' . htmlspecialchars($member['sl_no']) . '</td>
                <td>' . htmlspecialchars($member['memberName']) . '</td>
                <td>' . htmlspecialchars($member['memberId']) . '</td>
                <td>' . htmlspecialchars($member['aadhaar']) . '</td>
                <td>' . htmlspecialchars($member['releationship_name']) . '</td>
            </tr>';
        }
        $member_html .= '</table></div>';
    }

    // Final HTML for Swal (with a wrapper for capture)
    $swal_html = "
    <div id='swalContent' style='padding:10px;text-align:left'>
        <h3 style='margin-top:0;color:#333;'>Status: " . htmlspecialchars($status) . "</h3>
        <p><b>Message:</b> " . htmlspecialchars($message) . "</p>
        $member_html
    </div>";

    echo "
<script>
Swal.fire({
    html: `$swal_html`,
    width: 750,
    showCloseButton: true,
    showCancelButton: true,
    cancelButtonText: 'Download PDF',
    confirmButtonText: 'OK'
}).then((result) => {
    if (result.dismiss === Swal.DismissReason.cancel) {
        let target = document.querySelector('#swalContent');
        if (target) {
            var opt = {
                margin: 0.3,
                filename: 'ration_uid_status.pdf',
                image: { type: 'jpeg', quality: 1 },
                html2canvas: { scale: 3, backgroundColor: '#fff' },
                jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' }
            };
            html2pdf().set(opt).from(target).save();
        }
    } else if (result.isConfirmed) {
        window.location.href = 'ration_2_uid_all_submit_list.php';
    }
});
</script>";
}
?>

<!-- Page Wrapper -->
<div class="page-wrapper">
<div class="page-content">
    <div class="card radius-10">
        <div class="card-body">
            <h5 class="mb-0">Ration to UID All 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>Ration No</th>
                            <th>Order ID</th>
                            <th>Status</th>
                            <th>Request Time</th>
                            <th>View</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if ($udata['type'] == 'admin') {
                            $res = mysqli_query($ahk_conn, "SELECT * FROM ration_to_aadhar_requests ORDER BY request_time DESC");
                        } else {
                            $res = mysqli_query($ahk_conn, "SELECT * FROM ration_to_aadhar_requests WHERE userid='" . $udata['phone'] . "' ORDER BY request_time DESC");
                        }

                        $x = 0;
                        $refresh_after = 999999;

                        while ($row = mysqli_fetch_assoc($res)) {
                            $x++;

                            $request_time = strtotime($row['request_time']);
                            $current_time = time();
                            $elapsed = $current_time - $request_time;

                            if ($elapsed < 180) {
                                $remaining = 180 - $elapsed;
                                if ($remaining < $refresh_after) {
                                    $refresh_after = $remaining;
                                }
                            }

                            if ($row['status'] !== 'Success' && $elapsed >= 180) {
                                mysqli_query($ahk_conn, "UPDATE ration_to_aadhar_requests SET status='Success' WHERE order_id='" . $row['order_id'] . "'");
                                $row['status'] = 'Success';
                            }
                            ?>
                            <tr>
                                <td><?php echo $x; ?></td>
                                <td><?php echo htmlspecialchars($row['ration_no']); ?></td>
                                <td><?php echo htmlspecialchars($row['order_id']); ?></td>
                                <td><?php echo htmlspecialchars($row['status']); ?></td>
                                <td><?php echo $row['request_time']; ?></td>
                                <td>
                                    <?php
                                    $remainingCountdown = 180 - $elapsed;
                                    if ($remainingCountdown > 0 && $row['status'] !== 'Success') {
                                        echo "<span class='countdown badge bg-warning text-dark' data-remaining='{$remainingCountdown}' data-orderid='" . htmlspecialchars($row['order_id']) . "'></span>";
                                    } else {
                                        ?>
                                        <form method="post">
                                            <input type="hidden" name="order_id" value="<?php echo htmlspecialchars($row['order_id']); ?>">
                                            <button type="submit" name="check_status" class="btn btn-primary btn-sm">View</button>
                                        </form>
                                        <?php
                                    }
                                    ?>
                                </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/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/index.js"></script>
<script src="../template/ahkweb/assets/js/app.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/plugins/datatable/js/dataTables.buttons.min.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/buttons.bootstrap5.min.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/jszip.min.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/pdfmake.min.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/vfs_fonts.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/buttons.html5.min.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/buttons.print.min.js"></script>
<script src="../template/ahkweb/assets/plugins/datatable/js/buttons.colVis.min.js"></script>

<script>
$(document).ready(function() {
    var table = $('#example2').DataTable({
        lengthChange: false,
        buttons: [ 'copy', 'excel', 'pdf', 'print', 'colvis' ]
    });
    table.buttons().container().appendTo('#example2_wrapper .col-md-6:eq(0)');

    var refreshAfter = <?php echo ($refresh_after < 999999) ? $refresh_after : 0; ?>;
    if (refreshAfter > 0) {
        setTimeout(function() {
            location.reload();
        }, refreshAfter * 1000);
    }

    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);
                        el.replaceWith(
                            '<form method="post">' +
                            '<input type="hidden" name="order_id" value="' + el.data("orderid") + '">' +
                            '<button type="submit" name="check_status" class="btn btn-primary btn-sm">View</button>' +
                            '</form>'
                        );
                    } else {
                        var minutes = Math.floor(remaining / 60);
                        var seconds = remaining % 60;
                        el.text('Wait ' + minutes + ':' + (seconds < 10 ? '0' : '') + seconds);
                        remaining--;
                    }
                }, 1000);
            }
        });
    }
    startCountdown();
});
</script>
