<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

// ================= FETCH REQUESTS =================
$requests = $conn->query("
    SELECT mr.*, r.room_number 
    FROM maintenance_requests mr
    LEFT JOIN rooms r ON mr.room_id = r.id
    ORDER BY mr.created_at DESC
");

// ================= 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;
}

// ================= FETCH STATUS COUNTS =================
$statsQuery = $conn->query("
    SELECT 
        SUM(CASE WHEN status='Pending' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status='Approved' THEN 1 ELSE 0 END) as approved,
        SUM(CASE WHEN status='Completed' THEN 1 ELSE 0 END) as completed
    FROM maintenance_requests
");
$stats = $statsQuery->fetch_assoc();
?>

<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" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>
        <button class="btn btn-primary" onclick="window.location.href='add_maintenance_request.php'">
            <i class="fa fa-plus"></i> Add Request
        </button>
    </div>

    <!-- SUMMARY CARDS -->
    <div class="row mb-3">
        <div class="col-md-4 mb-2">
            <div class="stat-card bg-warning text-center p-3">
                Pending<br><h4><?= $stats['pending'] ?? 0 ?></h4>
            </div>
        </div>
        <div class="col-md-4 mb-2">
            <div class="stat-card bg-info text-center p-3">
                Approved<br><h4><?= $stats['approved'] ?? 0 ?></h4>
            </div>
        </div>
        <div class="col-md-4 mb-2">
            <div class="stat-card bg-success text-center p-3">
                Completed<br><h4><?= $stats['completed'] ?? 0 ?></h4>
            </div>
        </div>
    </div>

    <!-- SEARCH BOX -->
    <div class="mb-3">
        <input type="text" id="searchRequest" class="form-control" placeholder="Search by room, request or staff...">
    </div>

    <!-- MAINTENANCE TABLE -->
    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead class="bg-dark text-white">
                <tr>
                    <th>#</th>
                    <th>Room</th>
                    <th>Request</th>
                    <th>Status</th>
                    <th>Assigned Staff</th>
                    <th>Created At</th>
                  
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="maintenanceTable">
            <?php $i=1; while($r=$requests->fetch_assoc()): 
                $status_class = 'secondary';
                if($r['status']=='Pending') $status_class='warning';
                elseif($r['status']=='Approved') $status_class='info';
                elseif($r['status']=='Completed') $status_class='success';
            ?>
                <tr>
                    <td><?= $i ?></td>
                    <td><?= $r['room_number'] ?? '-' ?></td>
                    <td><?= $r['issue_description'] ?></td>
                    <td>
                        <span class="badge badge-status bg-<?= $status_class ?>">
                            <?= $r['status'] ?>
                        </span>
                    </td>
                    <td>
                        <?php if($r['staff_id']): ?>
                            <?= htmlspecialchars($r['staff_id']) ?>
                        <?php else: ?>
                            <form action="assign_maintenance_staff.php" method="post" class="d-flex">
                                <input type="hidden" name="request_id" value="<?= $r['id'] ?>">
                                <select name="staff_id" class="form-control form-control-sm me-1" required>
                                    <option value="">Select Staff</option>
                                    <?php foreach($staff_list as $s): ?>
                                        <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['fullname']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="submit" class="btn btn-sm btn-success">Assign</button>
                            </form>
                        <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($r['created_at']) ?></td>
                 
                    <td>
                   <!-- Approve, Complete, Edit -->
<?php if($r['status'] == 'Pending'): ?>
    <a href="#" class="btn btn-sm btn-success">
        Pending
    </a>
    
    <a href="edit_request.php?id=<?= $r['id'] ?>" class="btn btn-sm btn-warning">
        <i class="fa fa-edit"></i> Edit
    </a>
<?php elseif($r['status'] == 'Approved'): ?>
    <a class="btn btn-sm btn-primary">
        <i class="fa fa-check-double"></i>Approved
    
<?php else: ?>
    <span class="text-success"><b>Approved</b></span>
<?php endif; ?>
                      
                    </td>
                </tr>
            <?php $i++; endwhile; ?>
            </tbody>
        </table>
    </div>

    <?php if($requests->num_rows == 0): ?>
        <div class="alert alert-success mt-3">
            🎉 No maintenance requests found.
        </div>
    <?php endif; ?>
</div>

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

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

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