<?php
// get_bed_details.php - Fetches details for a single bed by ID

// 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

if (isset($_GET['id']) && !empty($_GET['id'])) {
    $bedId = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);

    if ($bedId === false) {
        echo json_encode(['success' => false, 'message' => 'Invalid bed ID.']);
        exit;
    }

    // Join with rooms, floors, and hostels to get related names for display in modal
    $sql = "SELECT b.bed_id, b.room_id, b.bed_number, b.is_occupied,
                   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
            WHERE b.bed_id = :bed_id";

    try {
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':bed_id', $bedId, PDO::PARAM_INT);
        $stmt->execute();
        $bed = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($bed) {
            echo json_encode(['success' => true, 'bed' => $bed]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Bed not found.']);
        }
    } catch (PDOException $e) {
        error_log("Database error fetching bed details: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'A database error occurred while fetching details.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Bed ID not provided.']);
}

