<?php
require_once 'includes/db.php';
header('Content-Type: application/json');

// Get required parameters from the calendar's AJAX request
$tour_id = intval($_GET['tour_id'] ?? 0);
$month = intval($_GET['month'] ?? date('m'));
$year = intval($_GET['year'] ?? date('Y'));

if ($tour_id <= 0) {
    echo json_encode([]); // Return empty if no tour is specified
    exit;
}

// Ensure month is between 1 and 12
$month = max(1, min(12, $month));

// Calculate the first and last day of the requested month
$start_date = date('Y-m-d', strtotime("$year-$month-01"));
$end_date = date('Y-m-t', strtotime($start_date));

// Fetch all availability records for the given tour within the specified month
$stmt = $conn->prepare("
    SELECT available_date, slots_available 
    FROM tour_availability 
    WHERE tour_id = ? AND available_date BETWEEN ? AND ?
");
$stmt->bind_param("iss", $tour_id, $start_date, $end_date);
$stmt->execute();
$result = $stmt->get_result();

$availability_data = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $status = ($row['slots_available'] > 0) ? 'available' : 'full';
        // The key is the date string, the value is the status
        $availability_data[$row['available_date']] = $status;
    }
}

// Output the data as a JSON object for the JavaScript calendar to read
echo json_encode($availability_data);
?>
