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

// ================= FETCH ROOMS =================
$rooms_result = $conn->query("SELECT id, room_number FROM rooms ORDER BY room_number ASC");
$rooms = [];
while($r = $rooms_result->fetch_assoc()){
    $rooms[] = $r;
}

// ================= HANDLE FORM SUBMISSION =================
if(isset($_POST['add_request'])){

    $room_id = intval($_POST['room_id'] ?? 0);
    $issue_description = htmlspecialchars(trim($_POST['issue_description'] ?? ''));

    // ================= VALIDATE INPUT =================
    if($room_id <= 0 || $issue_description === ''){
        echo "<script>alert('Please select a room and provide details.');window.history.back();</script>";
        exit;
    }

    // ================= CHECK FOR EXISTING PENDING REQUEST =================
    $check_existing = $conn->prepare("
        SELECT id FROM maintenance_requests 
        WHERE room_id = ? AND status = 'Pending' 
        LIMIT 1
    ");
    $check_existing->bind_param("i", $room_id);
    $check_existing->execute();
    $check_existing->store_result();

    if($check_existing->num_rows > 0){
        echo "<script>alert('A pending maintenance request already exists for this room.');window.history.back();</script>";
        exit;
    }
    $check_existing->close();

    // ================= INSERT NEW REQUEST =================
// ================= INSERT NEW REQUEST =================
$stmt = $conn->prepare("
    INSERT INTO maintenance_requests (room_id, issue_description, status, created_at) 
    VALUES (?, ?, 'Pending', NOW())
");
$stmt->bind_param("is", $room_id, $issue_description);
$stmt->execute();
$stmt->close();

// ================= ALERT + REDIRECT =================
echo "<script>
    alert('Maintenance request added successfully!');
    window.location.href='maintenance_requests.php';
</script>";
exit;
}
?>

<div class="container mt-4">
     <button class="btn btn-secondary" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>
    <h3>Add Maintenance Request</h3>
    <form method="post">
        <div class="mb-3">
            <label>Room</label>
            <select name="room_id" class="form-control" required>
                <option value="">-- Select Room --</option>
                <?php foreach($rooms as $r): ?>
                    <option value="<?= $r['id'] ?>"><?= htmlspecialchars($r['room_number']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mb-3">
            <label>Request Details</label>
            <textarea name="issue_description" class="form-control" placeholder="Describe the issue" required></textarea>
        </div>
        <button type="submit" name="add_request" class="btn btn-primary">Add Request</button>
        <a href="maintenance_requests.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>

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