<?php
require_once 'config/config.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: auth/login.php");
    exit;
}

$result = $conn->query("SELECT * FROM completed_transit_visas ORDER BY completed_at DESC");

include 'header.php';
?>
<div class="main-content p-4" style="flex:1;">
    <h2><?= $lang['completed_bookings'] ?></h2>

    <table class="table table-bordered table-striped align-middle">
        <thead>
            <tr>
                <th><?= $lang['id'] ?></th>
                <th><?= $lang['passenger_name'] ?></th>
                <th><?= $lang['visa_issued'] ?></th>
                <th><?= $lang['issue_date'] ?></th>
                <th><?= $lang['travel_date'] ?></th>
                <th><?= $lang['booking_nas_go'] ?></th>
                <th><?= $lang['booking_nas_return'] ?></th>
                <th><?= $lang['created_at'] ?></th>
                <th><?= $lang['completed_at'] ?></th>
                <th><?= $lang['actions'] ?></th>
            </tr>
        </thead>
        <tbody>
            <?php while ($row = $result->fetch_assoc()): ?>
                <tr id="row-<?= $row['id'] ?>">
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['passenger_name']) ?></td>
                    <td><?= $row['issued'] ? $lang['yes'] : $lang['no'] ?></td>
                    <td><?= $row['issue_date'] ?: "-" ?></td>
                    <td><?= $row['travel_date'] ?: "-" ?></td>
                    <td><?= htmlspecialchars($row['booking_nas_go'] ?: "-") ?></td>
                    <td><?= htmlspecialchars($row['booking_nas_return'] ?: "-") ?></td>
                    <td><?= $row['created_at'] ?></td>
                    <td><?= $row['completed_at'] ?></td>
                    <td>
                        <button class="btn btn-sm btn-danger deleteCompleted" data-id="<?= $row['id'] ?>">
                            <?= $lang['delete'] ?>
                        </button>
                    </td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>
<?php include 'includes/footer.php'; ?>

<script>
// ✅ حذف من جدول المكتملة
document.querySelectorAll(".deleteCompleted").forEach(btn => {
    btn.addEventListener("click", function() {
        if (!confirm("<?= $lang['confirm_delete'] ?>")) return;
        let id = this.dataset.id;
        fetch("delete_completed_transit_visa.php?id=" + id)
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    document.getElementById("row-" + id).remove();
                } else {
                    alert("Error: " + (data.error || "Unknown"));
                }
            });
    });
});
</script>
