<?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');
}

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

try {
    // Fetch hotels that have been approved
    $query = "SELECT * FROM hotel_registrations WHERE status = 'approved' ORDER BY created_at DESC";
    $stmt =$db->prepare($query);$stmt->execute();
    
    $hotels =$stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted_hotels = array_map(function($h) {
        // Decode JSON arrays safely
        $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) ?: [];
        $roomTypes = json_decode($h['room_types'], true) ?: [];
        $amenities = json_decode($h['amenities'], true) ?: [];
        
        // Calculate the lowest starting price from their room inventory
        $startingPrice = 0;
        if (!empty($roomTypes)) {
            $prices = array_column($roomTypes, 'pricePerNight');
            if (!empty($prices)) {
                $startingPrice = min($prices);
            }
        }

        return [
            'id' => $h['id'],
            'name' => $h['hotel_name'],
            'ownerName' => $h['owner_name'],
            'email' => $h['email'],
            'phone' => $h['owner_contact'],
            'city' => $h['city'],
            'state' => $h['state'],
            'location' => $h['hotel_address'],
            'starRating' => (int)$h['star_rating'],
            'startingPrice' => $startingPrice,
            'overview' => $h['description'],
            'amenities' => $amenities,
            'roomTypes' => $roomTypes,
            // Images
            'image' => !empty($roomPics) ?$roomPics[0] : null,
            'roomPics' => $roomPics,
            'receptionPics' => $receptionPics,
            'bathroomPics' => $bathroomPics,
            'interiorExteriorPics' => $interiorExteriorPics,
            'createdAt' => $h['created_at']
        ];
    }, $hotels);

    sendResponse(200, 'success', 'Approved hotels fetched successfully', $formatted_hotels);

} catch (PDOException $e) {
    sendResponse(500, 'error', 'Database error: ' . $e->getMessage());
}
?>