<?php
// get_beds_paginated.php - Fetches filtered and paginated bed data

// Enable full error reporting for debugging. REMOVE IN PRODUCTION!
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'config.php'; // Include database configuration
header('Content-Type: application/json'); // Set header to return JSON response

try {
    // Get pagination parameters
    $page = filter_var($_GET['page'] ?? 1, FILTER_VALIDATE_INT);
    $limit = filter_var($_GET['limit'] ?? 10, FILTER_VALIDATE_INT);

    // Ensure page and limit are valid
    $page = ($page < 1) ? 1 : $page;
    $limit = ($limit < 1) ? 10 : $limit; // Default to 10 if invalid

    $offset = ($page - 1) * $limit;

    // Get filter parameters
    $filterHostelId = filter_var($_GET['hostel_id'] ?? '', FILTER_SANITIZE_NUMBER_INT);
    $filterFloorId = filter_var($_GET['floor_id'] ?? '', FILTER_SANITIZE_NUMBER_INT);
    $filterRoomId = filter_var($_GET['room_id'] ?? '', FILTER_SANITIZE_NUMBER_INT);
    $filterBedNumber = filter_var($data['bed_number'] ?? '', FILTER_SANITIZE_STRING); // Use $data if POST, but this is GET. Should be $_GET.
    $filterIsOccupied = filter_var($_GET['is_occupied'] ?? '', FILTER_SANITIZE_NUMBER_INT); // Can be 0, 1, or empty

    // FIX: Changed $data['bed_number'] to $_GET['bed_number'] as this is a GET request
    $filterBedNumber = filter_var($_GET['bed_number'] ?? '', FILTER_SANITIZE_STRING);


    // Start building the WHERE clause
    $whereClauses = [];
    $params = [];

    if (!empty($filterHostelId)) {
        $whereClauses[] = "h.hostel_id = :filter_hostel_id";
        $params[':filter_hostel_id'] = $filterHostelId;
    }
    if (!empty($filterFloorId)) {
        $whereClauses[] = "f.floor_id = :filter_floor_id";
        $params[':filter_floor_id'] = $filterFloorId;
    }
    if (!empty($filterRoomId)) {
        $whereClauses[] = "r.room_id = :filter_room_id";
        $params[':filter_room_id'] = $filterRoomId;
    }
    if (!empty($filterBedNumber)) {
        $whereClauses[] = "b.bed_number LIKE :filter_bed_number";
        $params[':filter_bed_number'] = '%' . $filterBedNumber . '%';
    }
    // Only apply is_occupied filter if it's explicitly 0 or 1
    if ($filterIsOccupied !== '' && ($filterIsOccupied == 0 || $filterIsOccupied == 1)) {
        $whereClauses[] = "b.is_occupied = :filter_is_occupied";
        $params[':filter_is_occupied'] = $filterIsOccupied;
    }

    $whereSql = '';
    if (!empty($whereClauses)) {
        $whereSql = ' WHERE ' . implode(' AND ', $whereClauses);
    }

    // --- 1. Get Total Count (for pagination metadata) ---
    $countSql = "SELECT COUNT(b.bed_id)
                 FROM beds b
                 JOIN rooms r ON b.room_id = r.room_id
                 JOIN floors f ON r.floor_id = f.floor_id
                 JOIN hostels h ON f.hostel_id = h.hostel_id"
                 . $whereSql;

    $stmtCount = $pdo->prepare($countSql);
    $stmtCount->execute($params);
    $totalBeds = $stmtCount->fetchColumn();

    // --- 2. Get Paginated and Filtered Data ---
    $dataSql = "SELECT b.bed_id, b.bed_number, b.is_occupied,
                       r.room_id, r.room_number, r.room_type, r.capacity, r.current_occupancy,
                       f.floor_id, f.floor_number,
                       h.hostel_id, h.name AS hostel_name
                FROM beds b
                JOIN rooms r ON b.room_id = r.room_id
                JOIN floors f ON r.floor_id = f.floor_id
                JOIN hostels h ON f.hostel_id = h.hostel_id"
                . $whereSql .
                " ORDER BY h.name, f.floor_number, r.room_number, b.bed_number ASC
                LIMIT :limit OFFSET :offset";

    $stmtData = $pdo->prepare($dataSql);
    // Bind parameters for data query
    foreach ($params as $key => $value) {
        $stmtData->bindValue($key, $value);
    }
    $stmtData->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmtData->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmtData->execute();
    $beds = $stmtData->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'beds' => $beds,
        'total' => $totalBeds,
        'page' => $page,
        'limit' => $limit
    ]);

} catch (PDOException $e) {
    error_log("Database error in get_beds_paginated.php: " . $e->getMessage());
    // IMPORTANT: Return the full PDO error message for debugging
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    error_log("General error in get_beds_paginated.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'An unexpected error occurred: ' . $e->getMessage()]);
}
// NO CLOSING PHP TAG `?>
