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

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

$data = json_decode(file_get_contents("php://input"));

// Fixed the syntax error on this line
if (empty($data->hotelId) || empty($data->roomCategory) || empty($data->checkin) || empty($data->checkout) || empty($data->rooms)) {
    sendResponse(400, 'error', 'Missing required availability parameters');
}

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

try {
    $stmt = $db->prepare("SELECT room_types FROM hotel_registrations WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $data->hotelId]);
    $hotel = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$hotel) sendResponse(404, 'error', 'Hotel not found');

    $roomTypes = json_decode($hotel['room_types'], true) ?: [];
    $totalInventory = 0;

    foreach ($roomTypes as $rt) {
        if ($rt['name'] === $data->roomCategory) {
            $totalInventory = (int)$rt['count'];
            break;
        }
    }

    if ($totalInventory <= 0) sendResponse(400, 'error', 'This room category is not available at this hotel.');

    // Overlap logic
    $query = "
        SELECT SUM(rooms_booked) as total_booked 
        FROM hotel_bookings 
        WHERE hotel_id = :hotel_id 
          AND room_category = :category 
          AND booking_status IN ('confirmed', 'checked_in') 
          AND checkin_date < :checkout 
          AND checkout_date > :checkin
    ";

    $stmtBookings = $db->prepare($query);
    $stmtBookings->execute([
        ':hotel_id' => $data->hotelId,
        ':category' => $data->roomCategory,
        ':checkout' => $data->checkout,
        ':checkin'  => $data->checkin
    ]);

    $result = $stmtBookings->fetch(PDO::FETCH_ASSOC);
    $bookedCount = (int)$result['total_booked'];
    $availableRooms = $totalInventory - $bookedCount;

    if ($availableRooms >= (int)$data->rooms) {
        sendResponse(200, 'success', 'Rooms are available');
    } else {
        sendResponse(400, 'error', "Only {$availableRooms} room(s) available for these dates in this category.");
    }
} catch (PDOException $e) {
    sendResponse(500, 'error', 'Database error: ' . $e->getMessage());
}
?>