<?php
require_once '../config/headers.php';
require_once '../config/database.php';
require_once '../utils/response.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendResponse(405, 'error', 'Method not allowed');
}

$id = isset($_GET['id']) ? $_GET['id'] : '';

if (empty($id)) {
    sendResponse(400, 'error', 'Hotel ID is required');
}

$database = new Database();
$db = $database->getConnection();

try {
    // Fetch only if the hotel is approved
    $query = "SELECT * FROM hotel_registrations WHERE id = :id AND status = 'approved' LIMIT 1";
    $stmt = $db->prepare($query);
    $stmt->execute([':id' => $id]);
    
    if ($stmt->rowCount() > 0) {
        $h = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Safely decode JSON arrays
        $roomPics = json_decode($h['room_pics'], true) ?: [];
        $receptionPics = json_decode($h['reception_pics'], true) ?: [];
        $bathroomPics = json_decode($h['bathroom_pics'], true) ?: [];
        $interiorExteriorPics = json_decode($h['interior_exterior_pics'], true) ?: [];
        
        // Combine all images for the frontend Gallery component
        $allImages = array_merge($roomPics, $receptionPics, $bathroomPics, $interiorExteriorPics);
        
        $roomTypes = json_decode($h['room_types'], true) ?: [];
        $amenities = json_decode($h['amenities'], true) ?: [];

        $hotel = [
            'id' => $h['id'],
            'name' => $h['hotel_name'],
            'city' => $h['city'],
            'state' => $h['state'],
            'location' => $h['hotel_address'],
            'starRating' => (int)$h['star_rating'],
            'overview' => $h['description'],
            'amenities' => $amenities,
            'roomTypes' => $roomTypes,
            
            // Set the first room pic as the main hero image
            'image' => !empty($roomPics) ? $roomPics[0] : null,
            'images' => $allImages, // The full gallery
            
            // Default cancellation policy (You can add this to your DB schema later if you want owners to customize it)
            'cancellationPolicy' => 'Free cancellation up to 24 hours before check-in. Standard hotel policies apply.' 
        ];

        sendResponse(200, 'success', 'Hotel fetched successfully', $hotel);
    } else {
        sendResponse(404, 'error', 'Hotel not found');
    }
} catch (PDOException $e) {
    sendResponse(500, 'error', 'Database error: ' . $e->getMessage());
}
?>