<?php
/**
 * Rooms API
 * Get rooms data from database
 */

header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';

$response = ['success' => false, 'data' => [], 'message' => ''];

try {
    $filter_type = $_GET['filter_type'] ?? '';
    $min_price = $_GET['min_price'] ?? 0;
    $max_price = $_GET['max_price'] ?? 999999;
    $guests = $_GET['guests'] ?? 0;

    $sql = "SELECT * FROM rooms WHERE is_available = 1";
    $params = [];
    $types = '';

    if ($filter_type) {
        $sql .= " AND room_type = ?";
        $params[] = $filter_type;
        $types .= 's';
    }

    if ($guests > 0) {
        $sql .= " AND max_guests >= ?";
        $params[] = $guests;
        $types .= 'i';
    }

    $sql .= " AND price_per_night BETWEEN ? AND ?";
    $params[] = $min_price;
    $params[] = $maxPrice;
    $types .= 'dd';

    $stmt = $conn->prepare($sql);
    
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }

    $stmt->execute();
    $result = $stmt->get_result();
    $rooms = [];

    while ($room = $result->fetch_assoc()) {
        // Handle JSON amenities field
        if (isset($room['amenities'])) {
            $room['amenities'] = json_decode($room['amenities'], true);
        }
        $rooms[] = $room;
    }

    $response['success'] = true;
    $response['data'] = $rooms;
    $response['count'] = count($rooms);

} catch (Exception $e) {
    http_response_code(500);
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
$conn->close();
?>
