<?php
include "dbconnect.php";

// Pagination setup
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Search logic
$searchQuery = "";
if (!empty($_GET['search'])) {
    $search = $con->real_escape_string($_GET['search']);
    $searchQuery = "AND (ja.name LIKE '%$search%' OR ja.passport_no LIKE '%$search%' OR mr.medical_date LIKE '%$search%')";
}

// Fetch paginated records
$sql = "SELECT ja.name, ja.passport_no, ja.id AS applicant_id,
               mr.medical_date, mr.medical_exp_date, mr.medical_upload, mr.sleep
        FROM job_applicants ja
        LEFT JOIN medical_records mr ON ja.id = mr.applicant_id
        WHERE 1 $searchQuery
        ORDER BY mr.medical_date DESC
        LIMIT $limit OFFSET $offset";
$result = $con->query($sql);

// Total record count for pagination
$countQuery = "SELECT COUNT(*) AS total
               FROM job_applicants ja
               LEFT JOIN medical_records mr ON ja.id = mr.applicant_id
               WHERE 1 $searchQuery";
$totalRows = $con->query($countQuery)->fetch_assoc()['total'];
$totalPages = ceil($totalRows / $limit);

// ✅ Medical expiry notification data (within 45 days)
$today = date('Y-m-d');
$notifySql = "SELECT ja.name, ja.passport_no, mr.medical_exp_date
              FROM job_applicants ja
              LEFT JOIN medical_records mr ON ja.id = mr.applicant_id
              WHERE mr.medical_exp_date IS NOT NULL 
              AND DATEDIFF(mr.medical_exp_date, '$today') BETWEEN 0 AND 45
              ORDER BY mr.medical_exp_date ASC";
$notifyResult = $con->query($notifySql);
$notificationMsg = '';
while ($row = $notifyResult->fetch_assoc()) {
    $notificationMsg .= "{$row['name']} (Passport: {$row['passport_no']}) expiring on {$row['medical_exp_date']} | ";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Medical Records List</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap + Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

    <style>
        body {
            background: linear-gradient(to right, #667eea, #764ba2);
            font-family: 'Segoe UI', sans-serif;
            color: #333;
        }

        .container {
            margin-top: 50px;
            margin-bottom: 50px;
        }

        .table th {
            background-color: #343a40;
            color: #fff;
            text-align: center;
        }

        .table td {
            vertical-align: middle;
        }

        .logout-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: #dc3545;
            color: white;
            padding: 10px 20px;
            border-radius: 30px;
            font-size: 14px;
            text-decoration: none;
            z-index: 1000;
        }

        .logout-btn:hover {
            background-color: #c82333;
        }

        .search-bar {
            margin-bottom: 20px;
        }

        .page-link {
            color: #007bff;
        }

        .page-item.active .page-link {
            background-color: #007bff;
            border-color: #007bff;
        }

        .table-responsive {
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
            padding: 20px;
        }

        h3 i {
            margin-right: 10px;
        }

        @media (max-width: 768px) {
            .logout-btn {
                top: 10px;
                right: 10px;
                padding: 8px 14px;
                font-size: 12px;
            }

            h3 {
                font-size: 22px;
            }

            .table th, .table td {
                font-size: 12px;
            }
        }
    </style>
</head>
<body>
<marquee behavior="scroll" direction="left" style="background: #ffc107; color: #000; padding: 10px; font-weight: bold; font-size: 14px;">
    <?= !empty($notificationMsg) ? $notificationMsg : "No medical records expiring in the next 45 days." ?>
</marquee>

<a href="logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a>

<div class="container">
    <h3 class="text-center text-white"><i class="fas fa-notes-medical"></i> Medical Records List</h3>

    <!-- Search -->
    <form method="GET" class="row g-2 search-bar justify-content-center">
        <div class="col-sm-6 col-md-4">
            <input type="text" name="search" class="form-control" placeholder="Search Name / Passport / Date" value="<?= isset($_GET['search']) ? htmlspecialchars($_GET['search']) : '' ?>">
        </div>
        <div class="col-sm-4 col-md-2">
            <button type="submit" class="btn btn-light w-100"><i class="fas fa-search"></i> Search</button>
        </div>
    </form>

    <div class="table-responsive">
        <table class="table table-bordered align-middle text-center">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Applicant</th>
                    <th>Passport No</th>
                    <th>Medical Date</th>
                    <th>Expiry Date</th>
                    <th>Document</th>
                    <th>Sleep</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $sr = $offset + 1;
            if ($result->num_rows > 0):
                while ($row = $result->fetch_assoc()):
                    $upload = $row['medical_upload'] ?? '';
                    $uploadPath = (strpos($upload, 'uploads/') === false) ? "uploads/$upload" : $upload;
            ?>
                <tr>
                    <td><?= $sr++ ?></td>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td><?= htmlspecialchars($row['passport_no']) ?></td>
                    <td><?= $row['medical_date'] ?? '<span class="text-muted">N/A</span>' ?></td>
                    <td><?= $row['medical_exp_date'] ?? '<span class="text-muted">N/A</span>' ?></td>
                    <td>
                        <?php if (!empty($upload) && file_exists($uploadPath)): ?>
                            <a href="<?= $uploadPath ?>" class="btn btn-sm btn-success" download><i class="fas fa-download"></i> Download</a>
                        <?php else: ?>
                            <span class="text-danger">No File</span>
                        <?php endif; ?>
                    </td>
                    <td><?= !empty($row['sleep']) ? htmlspecialchars($row['sleep']) : 'No' ?></td>
                    <td>
                        <a href="medicaledit.php?id=<?= $row['applicant_id'] ?>" class="btn btn-sm btn-primary me-1" title="Edit Record">
                            <i class="fas fa-edit"></i> Edit
                        </a>
                        <a href="medicaldelete.php?id=<?= $row['applicant_id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this record?')" title="Delete Record">
                            <i class="fas fa-trash-alt"></i> Delete
                        </a>
                    </td>
                </tr>
            <?php endwhile; else: ?>
                <tr>
                    <td colspan="8" class="text-center text-muted">No records found.</td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <nav class="mt-4">
        <ul class="pagination justify-content-center">
            <?php
            $searchParam = isset($_GET['search']) ? "&search=" . urlencode($_GET['search']) : '';
            for ($i = 1; $i <= $totalPages; $i++):
                $active = ($i == $page) ? 'active' : '';
                echo "<li class='page-item $active'><a class='page-link' href='?page=$i$searchParam'>$i</a></li>";
            endfor;
            ?>
        </ul>
    </nav>
    <?php endif; ?>
</div>

</body>
</html>
