<?php
require_once __DIR__ . '/db.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: ' . SITE_URL);
header('Cache-Control: no-store, no-cache, must-revalidate');

$month = (int)($_GET['month'] ?? date('n'));
$year  = (int)($_GET['year']  ?? date('Y'));
$month = max(1, min(12, $month));
$year  = max(date('Y'), min(date('Y') + 2, $year));

$start = sprintf('%04d-%02d-01', $year, $month);
$end   = date('Y-m-t', strtotime($start));

// Bookings that overlap this month — including those that start last month and end this month
$booked = db()->prepare(
    "SELECT rental_date, end_date FROM bookings
     WHERE status IN ('pending','confirmed')
     AND rental_date <= ? AND end_date >= ?"
);
$booked->execute([$end, $start]);

$bookedDays = [];
foreach ($booked->fetchAll() as $row) {
    $d = new DateTime($row['rental_date']);
    $e = new DateTime($row['end_date']);
    while ($d <= $e) {
        $bookedDays[] = $d->format('Y-m-d');
        $d->modify('+1 day');
    }
}

// Admin-blocked dates for this month
$blocked = db()->prepare(
    "SELECT block_date FROM blocked_dates WHERE block_date BETWEEN ? AND ?"
);
$blocked->execute([$start, $end]);
foreach ($blocked->fetchAll() as $row) {
    $bookedDays[] = $row['block_date'];
}

echo json_encode([
    'month'        => $month,
    'year'         => $year,
    'booked_dates' => array_values(array_unique($bookedDays)),
]);
