<?php
// Availability check endpoint — used by calendar checker and booking form
require_auth();
require_permission('bookings.view');
$d = input();

$propId = (int)($d['property_id'] ?? 0);
$ci     = v_date($d['check_in']  ?? '', 'check_in');
$co     = v_date($d['check_out'] ?? '', 'check_out');

if (!$propId || !$ci || !$co) json_error('property_id, check_in, check_out required', 422);
if ($co <= $ci) json_error('check_out must be after check_in', 422);

$db = db();

// Check bookings
$stmt = $db->prepare("
    SELECT id, reference, guest_name, check_in, check_out, source
    FROM bookings
    WHERE property_id = ?
      AND status NOT IN ('cancelled','no_show')
      AND NOT (check_out <= ? OR check_in >= ?)
    LIMIT 1
");
$stmt->execute([$propId, $ci, $co]);
$conflict = $stmt->fetch();

if ($conflict) {
    json_ok(['available' => false, 'conflict' => $conflict]);
}

// Check calendar blocks
if (hv4_table_exists('calendar_blocks')) {
    $stmt = $db->prepare("
        SELECT id, title, block_type, start_date, end_date
        FROM calendar_blocks
        WHERE property_id = ?
          AND block_type IN ('owner_block','ota_block','maintenance')
          AND NOT (end_date <= ? OR start_date >= ?)
        LIMIT 1
    ");
    $stmt->execute([$propId, $ci, $co]);
    $block = $stmt->fetch();
    if ($block) {
        json_ok(['available' => false, 'conflict' => array_merge($block, ['reference' => $block['title'], 'guest_name' => $block['block_type'], 'source' => 'block'])]);
    }
}

json_ok(['available' => true, 'conflict' => null]);
