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

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

$result = $conn->query("SELECT * FROM transit_visas ORDER BY created_at DESC");
?>

<?php include 'header.php'; ?>
<div class="main-content p-4" style="flex:1;">
    <h2><?= $lang['transit_visas_followup'] ?></h2>
    <a href="add_transit_visa.php" class="btn btn-primary mb-3"><?= $lang['add_new'] ?></a>

    <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['actions'] ?></th>
            </tr>
        </thead>
        <tbody>
            <?php while ($row = $result->fetch_assoc()): ?>
                <?php
                $rowClass = '';
                if ($row['status'] == 'done') {
                    $rowClass = 'table-success';
                } elseif ($row['status'] == 'ticket') {
                    $rowClass = 'table-danger';
                }
                ?>
                <tr id="row-<?= $row['id'] ?>" class="<?= $rowClass ?>">
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['passenger_name']) ?></td>

                    <!-- ✅ Checkbox للتأشيرة -->
                    <td>
                        <?php if ($row['issued']): ?>
                            <?= $lang['yes'] ?>
                        <?php else: ?>
                            <input type="checkbox" class="markIssued" data-id="<?= $row['id'] ?>">
                        <?php endif; ?>
                    </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>
                        <button class="btn btn-sm btn-success markDone <?= ($row['status'] == 'done') ? 'd-none' : '' ?>" data-id="<?= $row['id'] ?>">
                            <?= $lang['mark_done'] ?>
                        </button>
                        <button class="btn btn-sm btn-warning undoDone <?= ($row['status'] != 'done') ? 'd-none' : '' ?>" data-id="<?= $row['id'] ?>">
                            <?= $lang['undo_done'] ?>
                        </button>
                        <button class="btn btn-sm btn-danger markTicket" data-id="<?= $row['id'] ?>">
                            <?= $lang['mark_ticket'] ?>
                        </button>
                        <button class="btn btn-sm btn-secondary deleteVisa" data-id="<?= $row['id'] ?>">
                            <?= $lang['delete'] ?>
                        </button>
                        <button class="btn btn-sm btn-primary completeVisa <?= ($row['status'] != 'done') ? 'd-none' : '' ?>" data-id="<?= $row['id'] ?>">
                            <?= $lang['complete_booking'] ?>
                        </button>
                    </td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>
<?php include 'includes/footer.php'; ?>

<script>
// 🔄 تحديث الحالة في قاعدة البيانات
function updateVisaStatus(id, status, extra = "", callback) {
    fetch("update_transit_visa.php", {
        method: "POST",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        body: "id=" + id + "&status=" + status + extra
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) callback();
        else alert("Error: " + (data.error || "Unknown"));
    });
}

// ✅ تأشير Visa Issued مع اختيار تاريخ
document.querySelectorAll(".markIssued").forEach(cb => {
    cb.addEventListener("change", function() {
        if (this.checked) {
            let id = this.dataset.id;
            let issueDate = prompt("Enter Issue Date (YYYY-MM-DD):", new Date().toISOString().slice(0,10));
            if (issueDate) {
                updateVisaStatus(id, "issued", "&issue_date=" + issueDate, () => {
                    let row = document.getElementById("row-" + id);
                    row.cells[2].innerText = "<?= $lang['yes'] ?>"; 
                    row.cells[3].innerText = issueDate; 
                });
            } else {
                this.checked = false; 
            }
        }
    });
});

// ✅ تم الإجراء
document.querySelectorAll(".markDone").forEach(btn => {
    btn.addEventListener("click", function() {
        let id = this.dataset.id;
        updateVisaStatus(id, "done", "", () => {
            let row = document.getElementById("row-" + id);
            row.classList.remove("table-danger");
            row.classList.add("table-success");

            this.classList.add("d-none");
            row.querySelector(".undoDone").classList.remove("d-none");
            row.querySelector(".completeVisa").classList.remove("d-none");
        });
    });
});

// ✅ إلغاء الإجراء
document.querySelectorAll(".undoDone").forEach(btn => {
    btn.addEventListener("click", function() {
        let id = this.dataset.id;
        updateVisaStatus(id, "pending", "", () => {
            let row = document.getElementById("row-" + id);
            row.classList.remove("table-success", "table-danger");

            this.classList.add("d-none");
            row.querySelector(".markDone").classList.remove("d-none");
            row.querySelector(".completeVisa").classList.add("d-none");
        });
    });
});

// ✅ تم إصدار التذكرة
document.querySelectorAll(".markTicket").forEach(btn => {
    btn.addEventListener("click", function() {
        let id = this.dataset.id;
        updateVisaStatus(id, "ticket", "", () => {
            let row = document.getElementById("row-" + id);
            row.classList.remove("table-success");
            row.classList.add("table-danger");
        });
    });
});

// ✅ إنهاء الحجز بالكامل
document.querySelectorAll(".completeVisa").forEach(btn => {
    btn.addEventListener("click", function() {
        let id = this.dataset.id;
        fetch("complete_transit_visa.php?id=" + id)
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    document.getElementById("row-" + id).remove();
                }
            });
    });
});

// ✅ حذف التأشيرة
document.querySelectorAll(".deleteVisa").forEach(btn => {
    btn.addEventListener("click", function() {
        if (!confirm("<?= $lang['confirm_delete'] ?>")) return;
        let id = this.dataset.id;
        fetch("delete_transit_visa.php?id=" + id)
            .then(() => {
                document.getElementById("row-" + id).remove();
            });
    });
});
</script>
