<?php
// Set the content type to JSON
header('Content-Type: application/json');

// Include necessary files
require_once '../includes/db.php';
require_once '../includes/helpers.php';

// Get the POST data sent from JavaScript
$input = json_decode(file_get_contents('php://input'), true);

// Validate input
$hotel_id = filter_var($input['hotel_id'] ?? 0, FILTER_VALIDATE_INT);
$check_in = $input['check_in'] ?? '';
$check_out = $input['check_out'] ?? '';
$guests = filter_var($input['guests'] ?? 1, FILTER_VALIDATE_INT);

if (!$hotel_id || empty($check_in) || empty($check_out)) {
    echo json_encode(['error' => 'Missing required parameters.']);
    exit;
}

try {
    // Find all room IDs for this hotel that have conflicting bookings
    $stmt_booked = $conn->prepare("
        SELECT DISTINCT room_id 
        FROM hotel_bookings 
        WHERE hotel_id = ? 
        AND status IN ('Confirmed', 'Pending Confirmation')
        AND (check_in_date < ? AND check_out_date > ?)
    ");
    $stmt_booked->bind_param("iss", $hotel_id, $check_out, $check_in);
    $stmt_booked->execute();
    $booked_rooms_result = $stmt_booked->get_result();
    $unavailable_room_ids = array_column($booked_rooms_result->fetch_all(MYSQLI_ASSOC), 'room_id');
    $stmt_booked->close();
    
    // Fetch all rooms and their rates for this hotel
    $stmt_rooms = $conn->prepare("
        SELECT hr.id, hr.room_type_name, hr.max_occupancy, hrr.id as rate_id, hrr.rate_name, hrr.price_per_night 
        FROM hotel_rooms hr
        JOIN hotel_room_rates hrr ON hr.id = hrr.room_id
        WHERE hr.hotel_id = ? AND hrr.is_active = 1
    ");
    $stmt_rooms->bind_param("i", $hotel_id);
    $stmt_rooms->execute();
    $all_rooms_result = $stmt_rooms->get_result();
    $all_rooms = $all_rooms_result->fetch_all(MYSQLI_ASSOC);
    $stmt_rooms->close();

    // Calculate number of nights
    $start_date = new DateTime($check_in);
    $end_date = new DateTime($check_out);
    $num_nights = $start_date->diff($end_date)->days;
    
    $response_data = [];
    foreach($all_rooms as $room) {
        $is_available = !in_array($room['id'], $unavailable_room_ids) && ($guests <= $room['max_occupancy']);
        
        $response_data[] = [
            'room_id' => $room['id'],
            'rate_id' => $room['rate_id'],
            'is_available' => $is_available,
            'total_price' => $room['price_per_night'] * $num_nights,
            'num_nights' => $num_nights,
            'price_per_night' => $room['price_per_night']
        ];
    }

    echo json_encode(['success' => true, 'rooms' => $response_data]);

} catch (Exception $e) {
    echo json_encode(['error' => 'An error occurred: ' . $e->getMessage()]);
}
?>
