<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type");

require_once "config.php";

$hotel_id = isset($_GET['hotel_id']) ? (int) $_GET['hotel_id'] : 0;

if ($hotel_id <= 0) {
    http_response_code(422);
    echo json_encode([
        "status" => false,
        "message" => "hotel_id is required"
    ]);
    exit;
}

try {
    // Verify hotel
    $hotelCheck = $pdo->prepare("SELECT hotel_id, hotel_name FROM hotels WHERE hotel_id = ? AND status = 'active'");
    $hotelCheck->execute([$hotel_id]);
    $hotel = $hotelCheck->fetch();

    if (!$hotel) {
        http_response_code(404);
        echo json_encode([
            "status" => false,
            "message" => "Hotel not found"
        ]);
        exit;
    }

    // Fetch rooms
    $stmt = $pdo->prepare("
        SELECT 
            r.id,
            r.room_name,
            r.room_type,
            r.price_per_night,
            r.max_guests,
            r.description
        FROM hotel_rooms r
        WHERE r.hotel_id = ?
        ORDER BY r.id DESC
    ");
    $stmt->execute([$hotel_id]);
    $rooms = $stmt->fetchAll();

    // Attach images + features
    foreach ($rooms as &$room) {

        $img = $pdo->prepare("SELECT image_path FROM hotel_room_images WHERE room_id = ?");
        $img->execute([$room['id']]);
        $room['images'] = $img->fetchAll(PDO::FETCH_COLUMN);

        $feat = $pdo->prepare("SELECT feature FROM room_features WHERE room_id = ?");
        $feat->execute([$room['id']]);
        $room['features'] = $feat->fetchAll(PDO::FETCH_COLUMN);
    }

    echo json_encode([
        "status" => true,
        "hotel" => [
            "id" => $hotel['hotel_id'],
            "name" => $hotel['hotel_name']
        ],
        "rooms" => $rooms
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        "status" => false,
        "message" => "Server error"
    ]);
}
