<?php
include "dbconnect.php";

// Pagination settings
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Search & Date Filtering
$searchQuery = "";
$dateFilter = "";

if (!empty($_GET['search'])) {
    $search = $con->real_escape_string($_GET['search']);
    $searchQuery = "AND (ja.passport_no LIKE '%$search%' OR ja.mobile_no LIKE '%$search%')";
}

if (!empty($_GET['start_date']) && !empty($_GET['end_date'])) {
    $start_date = $con->real_escape_string($_GET['start_date']);
    $end_date = $con->real_escape_string($_GET['end_date']);
    $dateFilter = "AND a.appointment_date BETWEEN '$start_date' AND '$end_date'";
}

// Load Data for Appointment List
$sql = "SELECT ja.id, ja.name, ja.passport_no, ja.mobile_no, ja.position, ja.job_country, ja.reference, 
               a.appointment_date, a.status AS appointment_status
        FROM job_applicants ja
        LEFT JOIN appointments a ON ja.id = a.applicant_id
        WHERE 1 $searchQuery $dateFilter
        ORDER BY a.appointment_date ASC
        LIMIT $limit OFFSET $offset";

$result = $con->query($sql);

// Fetch Expiring Soon for Marquee
$marqueeQuery = "SELECT ja.name, ja.passport_no, a.appointment_date FROM job_applicants ja
                 LEFT JOIN appointments a ON ja.id = a.applicant_id
                 WHERE DATEDIFF(a.appointment_date, CURDATE()) BETWEEN 1 AND 15 
                 ORDER BY a.appointment_date ASC";
$marqueeResult = $con->query($marqueeQuery);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Appointment List</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    
    <!-- Bootstrap 5 CSS & Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <style>
        body {
            background: linear-gradient(135deg, #cfe8fc 0%, #eaf3ff 100%);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            padding-top: 70px;
        }

        /* Status Colors */
        .done {
            background-color: #d1e7dd !important;
            color: #0f5132 !important;
            font-weight: 600;
        }
        .pending {
            background-color: #fff3cd !important;
            color: #664d03 !important;
            font-weight: 600;
        }
        .missed {
            background-color: #f8d7da !important;
            color: #842029 !important;
            font-weight: 600;
        }

        /* Marquee */
        .marquee-wrapper {
            font-weight: 600;
            color: #b02a37;
            margin-bottom: 15px;
            background-color: #f8f9fa;
            padding: 12px 20px;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgb(0 0 0 / 0.1);
        }
        .marquee-wrapper span {
            margin-right: 25px;
        }

        /* Logout Button */
        .logout-btn {
            position: fixed;
            top: 15px;
            right: 15px;
            z-index: 1100;
            background-color: #dc3545;
            color: #fff;
            padding: 8px 16px;
            border-radius: 8px;
            font-weight: 600;
            border: none;
            box-shadow: 0 3px 8px rgb(220 53 69 / 0.5);
            transition: background-color 0.3s ease;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .logout-btn:hover {
            background-color: #bb2d3b;
            text-decoration: none;
            color: #fff;
        }
        .logout-btn i {
            font-size: 1.2rem;
        }

        /* Table Container */
        .table-container {
            overflow-x: auto;
            box-shadow: 0 4px 12px rgb(0 0 0 / 0.08);
            border-radius: 12px;
            background-color: #fff;
            padding: 15px;
        }

        /* Pagination */
        .pagination li a.page-link {
            color: #0d6efd;
            font-weight: 600;
            border-radius: 10px;
        }
        .pagination li.active a.page-link {
            background-color: #0d6efd;
            border-color: #0d6efd;
            color: #fff;
            font-weight: 700;
        }

        /* Responsive Adjustments */
        @media (max-width: 991.98px) {
            .marquee-wrapper {
                font-size: 0.9rem;
                padding: 8px 15px;
            }
            .logout-btn {
                padding: 6px 12px;
                font-size: 0.9rem;
            }
            .logout-btn i {
                font-size: 1rem;
            }
        }
        @media (max-width: 575.98px) {
            body {
                padding-top: 90px;
            }
            .marquee-wrapper {
                font-size: 0.85rem;
                padding: 6px 12px;
            }
            .table-container {
                padding: 10px;
            }
            .table th, .table td {
                font-size: 0.85rem;
                padding: 8px 10px;
            }
            .btn {
                font-size: 0.85rem;
                padding: 6px 10px;
            }
        }
    </style>
</head>
<body>

<!-- Logout Button -->
<form method="POST" action="logout.php">
    <button type="submit" class="logout-btn" title="Logout">
        <i class="bi bi-box-arrow-right"></i> Logout
    </button>
</form>

<div class="container mb-5">
    <h3 class="text-center text-primary mb-4 fw-bold">Appointment List</h3>

    <!-- Marquee for Upcoming Appointments -->
    <div class="marquee-wrapper" role="region" aria-label="Upcoming appointments">
        <marquee scrollamount="5" behavior="scroll" direction="left" onmouseover="this.stop();" onmouseout="this.start();">
            <?php while ($row = $marqueeResult->fetch_assoc()) { ?>
                <span>🗓 <strong><?= htmlspecialchars($row['name']) ?></strong> (<?= htmlspecialchars($row['passport_no']) ?>) - <?= htmlspecialchars($row['appointment_date']) ?> |</span>
            <?php } ?>
        </marquee>
    </div>

    <!-- Filter Form -->
    <form method="GET" class="row g-3 mb-4">
        <div class="col-lg-4 col-md-6 col-sm-12">
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-search"></i></span>
                <input type="text" name="search" class="form-control" placeholder="Search Passport/Mobile" value="<?= isset($_GET['search']) ? htmlspecialchars($_GET['search']) : '' ?>" aria-label="Search by Passport or Mobile Number">
            </div>
        </div>

        <div class="col-lg-3 col-md-6 col-sm-6">
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-calendar-event"></i></span>
                <input type="date" name="start_date" class="form-control" value="<?= $_GET['start_date'] ?? '' ?>" aria-label="Start Date">
            </div>
        </div>

        <div class="col-lg-3 col-md-6 col-sm-6">
            <div class="input-group">
                <span class="input-group-text"><i class="bi bi-calendar-event"></i></span>
                <input type="date" name="end_date" class="form-control" value="<?= $_GET['end_date'] ?? '' ?>" aria-label="End Date">
            </div>
        </div>

        <div class="col-lg-2 col-md-6 col-sm-12 d-grid">
            <button type="submit" class="btn btn-success" aria-label="Search appointments">
                <i class="bi bi-funnel-fill me-1"></i> Filter
            </button>
        </div>
    </form>

    <!-- Appointment Table -->
    <div class="table-container">
        <table class="table table-bordered text-center align-middle table-hover mb-0">
            <thead class="table-primary text-primary">

                <tr>
                    <th>#</th>
                    <th><i class="bi bi-person-fill"></i> Name</th>
                    <th><i class="bi bi-passport"></i> Passport No</th>
                    <th><i class="bi bi-telephone-fill"></i> Mobile No</th>
                    <th><i class="bi bi-briefcase-fill"></i> Position</th>
                    <th><i class="bi bi-globe"></i> Job Country</th>
                    <th><i class="bi bi-card-list"></i> Reference</th>
                    <th><i class="bi bi-calendar-check-fill"></i> Appointment Date</th>
                    <th><i class="bi bi-info-circle-fill"></i> Status</th>
                    <th><i class="bi bi-gear-fill"></i> Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $sr = $offset + 1;
                if ($result->num_rows > 0):
                    while ($row = $result->fetch_assoc()):
                        $status_class = 'done';
                        $status_text = ucfirst($row['appointment_status'] ?? 'N/A');

                        if ($row['appointment_status'] == "pending") $status_class = "pending";
                        if ($row['appointment_status'] == "missed") $status_class = "missed";
                ?>
                    <tr class="<?= $status_class ?>">
                        <td><?= $sr++ ?></td>
                        <td><?= htmlspecialchars($row['name']) ?></td>
                        <td><?= htmlspecialchars($row['passport_no']) ?></td>
                        <td><?= htmlspecialchars($row['mobile_no']) ?></td>
                        <td><?= htmlspecialchars($row['position']) ?></td>
                        <td><?= htmlspecialchars($row['job_country']) ?></td>
                        <td><?= htmlspecialchars($row['reference']) ?></td>
                        <td><?= htmlspecialchars($row['appointment_date'] ?? 'N/A') ?></td>
                        <td><?= $status_text ?></td>
                        <td>
                            <a href="appointment_edit.php?id=<?= $row['id'] ?>" class="btn btn-warning btn-sm" aria-label="Edit appointment for <?= htmlspecialchars($row['name']) ?>">
                                <i class="bi bi-pencil-fill"></i>
                            </a>
                            <a href="appointment_delete.php?id=<?= $row['id'] ?>" class="btn btn-danger btn-sm" aria-label="Delete appointment for <?= htmlspecialchars($row['name']) ?>" onclick="return confirm('Are you sure you want to delete this appointment?');">
                                <i class="bi bi-trash-fill"></i>
                            </a>
                        </td>
                    </tr>
                <?php
                    endwhile;
                else:
                ?>
                    <tr>
                        <td colspan="10" class="text-muted fst-italic">No appointments found matching your criteria.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Export & Print Buttons -->
    <div class="text-center mt-4">
        <a href="export.php?search=<?= urlencode($_GET['search'] ?? '') ?>&start_date=<?= urlencode($_GET['start_date'] ?? '') ?>&end_date=<?= urlencode($_GET['end_date'] ?? '') ?>" class="btn btn-primary me-2" aria-label="Export appointments to CSV">
            <i class="bi bi-file-earmark-spreadsheet-fill"></i> Export CSV
        </a>
        <button onclick="window.print()" class="btn btn-secondary" aria-label="Print appointment list">
            <i class="bi bi-printer-fill"></i> Print
        </button>
    </div>

    <!-- Pagination -->
    <nav aria-label="Page navigation" class="mt-4">
        <ul class="pagination justify-content-center flex-wrap">
            <?php
            $countQuery = "SELECT COUNT(*) AS total FROM job_applicants ja 
                           LEFT JOIN appointments a ON ja.id = a.applicant_id
                           WHERE 1 $searchQuery $dateFilter";
            $countResult = $con->query($countQuery);
            $totalRows = $countResult->fetch_assoc()['total'];
            $totalPages = ceil($totalRows / $limit);

            // Pagination with previous & next arrows
            $prevDisabled = ($page <= 1) ? "disabled" : "";
            $nextDisabled = ($page >= $totalPages) ? "disabled" : "";

            $prevPage = max(1, $page - 1);
            $nextPage = min($totalPages, $page + 1);
            ?>
            <li class="page-item <?= $prevDisabled ?>">
                <a class="page-link" href="?page=<?= $prevPage ?>&search=<?= urlencode($_GET['search'] ?? '') ?>&start_date=<?= urlencode($_GET['start_date'] ?? '') ?>&end_date=<?= urlencode($_GET['end_date'] ?? '') ?>" aria-label="Previous">
                    <i class="bi bi-chevron-left"></i>
                </a>
            </li>

            <?php
            // Show up to 5 pages for simplicity
            $startPage = max(1, $page - 2);
            $endPage = min($totalPages, $page + 2);

            for ($i = $startPage; $i <= $endPage; $i++):
                $active = ($i == $page) ? 'active' : '';
            ?>
                <li class="page-item <?= $active ?>">
                    <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($_GET['search'] ?? '') ?>&start_date=<?= urlencode($_GET['start_date'] ?? '') ?>&end_date=<?= urlencode($_GET['end_date'] ?? '') ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>

            <li class="page-item <?= $nextDisabled ?>">
                <a class="page-link" href="?page=<?= $nextPage ?>&search=<?= urlencode($_GET['search'] ?? '') ?>&start_date=<?= urlencode($_GET['start_date'] ?? '') ?>&end_date=<?= urlencode($_GET['end_date'] ?? '') ?>" aria-label="Next">
                    <i class="bi bi-chevron-right"></i>
                </a>
            </li>
        </ul>
    </nav>
</div>

<!-- Bootstrap 5 JS Bundle (Popper + Bootstrap) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>
