<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// ================= FETCH ROOMS NEEDING CLEANING =================
$cleaning = $conn->query("
    SELECT r.id, r.room_number, r.room_type,
           h.housekeeper, h.last_cleaned, h.housekeeping_status, h.schedule_date
    FROM rooms r
    LEFT JOIN housekeeping_status h ON r.id=h.room_id
    WHERE h.housekeeping_status='Needs Cleaning'
    ORDER BY h.last_cleaned ASC
");

// ================= FETCH STAFF =================
$staff_result = $conn->query("SELECT id, fullname FROM staff ORDER BY fullname ASC");
$staff_list = [];
while($s = $staff_result->fetch_assoc()) {
    $staff_list[] = $s;
}

// ================= SUMMARY COUNTS =================
$statsQuery = $conn->query("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN last_cleaned IS NULL OR last_cleaned < DATE_SUB(NOW(), INTERVAL 1 DAY) THEN 1 ELSE 0 END) as overdue,
        SUM(CASE WHEN housekeeper IS NULL OR housekeeper='' THEN 1 ELSE 0 END) as unassigned
    FROM housekeeping_status
    WHERE housekeeping_status='Needs Cleaning'
");
$stats = $statsQuery->fetch_assoc();
?>

<style>
.priority-badge {
    padding: 5px 10px;
    border-radius: 20px;
    font-size: 12px;
}
.stat-card {
    border-radius: 12px;
    color: #fff;
    padding: 15px;
    text-align: center;
    font-weight: 600;
}
.table tbody tr:hover {
    background: #f8f9fa;
}
.search-box {
    max-width: 300px;
}
</style>

<div class="container-fluid mt-4">

    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i>
        Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>

    <div class="mb-3">
        <button class="btn btn-secondary btn-custom" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>
        <button class="btn btn-success mb-3" onclick="window.location.href='create_schedule.php'">
    <i class="fa fa-plus"></i> Create New Schedule
</button>
    </div>

    <h3><i class="fa fa-broom text-success"></i> Cleaning Schedule</h3>

    <!-- ================= SUMMARY CARDS ================= -->
    <div class="row mt-3 mb-3">
        <div class="col-md-4 mb-2">
            <div class="stat-card bg-primary">
                Total Pending<br><h4><?= $stats['total'] ?? 0 ?></h4>
            </div>
        </div>
        <div class="col-md-4 mb-2">
            <div class="stat-card bg-danger">
                Overdue<br><h4><?= $stats['overdue'] ?? 0 ?></h4>
            </div>
        </div>
        <div class="col-md-4 mb-2">
            <div class="stat-card bg-warning text-dark">
                Unassigned<br><h4><?= $stats['unassigned'] ?? 0 ?></h4>
            </div>
        </div>
    </div>

    <!-- ================= SEARCH ================= -->
    <div class="mb-3">
        <input type="text" id="searchRoom" class="form-control search-box"
               placeholder="🔍 Search room...">
    </div>

    <!-- ================= TABLE ================= -->
    <div class="table-responsive">
        <form id="assignForm" action="set_schedule.php" method="post">
        <table class="table table-bordered table-striped">
            <thead class="bg-dark text-white">
                <tr>
                    <th>Room</th>
                    <th>Type</th>
                    <th>Housekeeper</th>
                    <th>Schedule Date</th>
                    <th>Assign</th>
                </tr>
            </thead>
            <tbody id="cleaningTable">
            <?php while($c=$cleaning->fetch_assoc()): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($c['room_number']) ?></strong></td>
                    <td><?= htmlspecialchars($c['room_type']) ?></td>

                    <!-- Staff dropdown -->
                    <td>
                        <select name="housekeeper[<?= $c['id'] ?>]" class="form-control" required>
                            <option value="">-- Select Staff --</option>
                            <?php foreach($staff_list as $s): ?>
                                <option value="<?= $s['fullname'] ?>" <?= ($c['housekeeper']==$s['fullname'])?'selected':'' ?>>
                                    <?= htmlspecialchars($s['fullname']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>

                    <!-- Schedule Date -->
                    <td>
                        <input type="date" name="schedule_date[<?= $c['id'] ?>]" 
                               value="<?= htmlspecialchars($c['schedule_date'] ?? date('Y-m-d')) ?>"
                               class="form-control" required>
                    </td>

                    <!-- Assign Yes/No -->
                    <td class="text-center">
                        <input type="checkbox" name="assigned[<?= $c['id'] ?>]" value="Yes" 
                            <?= (!empty($c['housekeeper'])) ? 'checked' : '' ?>>
                    </td>
                </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
        </form>
    </div>

    <?php if($cleaning->num_rows == 0): ?>
        <div class="alert alert-success mt-3">
            🎉 All rooms are clean!
        </div>
    <?php endif; ?>

</div>

<script>
document.getElementById("searchRoom").addEventListener("keyup", function () {
    let value = this.value.toLowerCase();
    let rows = document.querySelectorAll("#cleaningTable tr");

    rows.forEach(row => {
        row.style.display =
            row.innerText.toLowerCase().includes(value) ? "" : "none";
    });
});
</script>

<?php include 'includes/footer.php'; ?>