<?php
declare(strict_types=1);

/**
 * Centralized availability — prevents double bookings across direct + OTA blocks.
 */
function hv4_availability_is_free(PDO $pdo, int $propertyId, string $checkIn, string $checkOut, ?int $excludeBookingId = null): bool {
    // FIXED: Parameter order must be $checkIn then $checkOut to match the query logic: NOT (check_out <= $checkIn OR check_in >= $checkOut)
    $params = [$propertyId, $checkIn, $checkOut];
    $exclude = '';
    if ($excludeBookingId) {
        $exclude = ' AND id <> ?';
        $params[] = $excludeBookingId;
    }
    $sql = "SELECT id FROM bookings WHERE property_id=? AND status NOT IN ('cancelled','no_show')
            AND NOT (check_out <= ? OR check_in >= ?)" . $exclude . ' LIMIT 1 FOR UPDATE';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    if ($stmt->fetch()) return false;

    if (function_exists('hv4_table_exists') && hv4_table_exists('calendar_blocks')) {
        // FIXED: Added FOR UPDATE to prevent race conditions on calendar blocks
        $stmt = $pdo->prepare("SELECT id FROM calendar_blocks WHERE property_id=?
            AND block_type IN ('owner_block','ota_block','maintenance')
            AND NOT (end_date <= ? OR start_date >= ?) LIMIT 1 FOR UPDATE");
        $stmt->execute([$propertyId, $checkIn, $checkOut]);
        if ($stmt->fetch()) return false;
    }
    return true;
}

function hv4_sync_calendar_block(PDO $pdo, int $bookingId): void {
    if (!hv4_table_exists('calendar_blocks')) return;
    $b = $pdo->prepare('SELECT property_id, guest_name, check_in, check_out, status FROM bookings WHERE id=?');
    $b->execute([$bookingId]);
    $row = $b->fetch();
    if (!$row || in_array($row['status'], ['cancelled', 'no_show'], true)) {
        $pdo->prepare('DELETE FROM calendar_blocks WHERE block_type="booking" AND ref_id=?')->execute([$bookingId]);
        return;
    }
    $pdo->prepare('DELETE FROM calendar_blocks WHERE block_type="booking" AND ref_id=?')->execute([$bookingId]);
    $pdo->prepare('INSERT INTO calendar_blocks (property_id, block_type, ref_id, title, start_date, end_date, color)
        VALUES (?,?,?,?,?,?,?)')->execute([
        $row['property_id'], 'booking', $bookingId,
        'Booking: ' . $row['guest_name'],
        $row['check_in'], $row['check_out'], '#7c5cff',
    ]);
}
