<?php
declare(strict_types=1);

function hv5_acquire_reservation_lock(PDO $pdo, int $propertyId, string $checkIn, string $checkOut, string $source = 'direct'): ?string {
    if (!hv5_table_exists('reservation_locks')) return bin2hex(random_bytes(16));
    
    // FIXED: Serialize lock requests by locking the property first. This prevents concurrent phantom inserts.
    $pdo->prepare('SELECT id FROM properties WHERE id=? FOR UPDATE')->execute([$propertyId]);

    $token = bin2hex(random_bytes(24));
    $expires = date('Y-m-d H:i:s', time() + 120);
    $pdo->prepare('DELETE FROM reservation_locks WHERE expires_at < NOW()')->execute();
    
    // FIXED: Check if there's already an active reservation_lock overlapping these dates (not just bookings)
    $lockStmt = $pdo->prepare('SELECT id FROM reservation_locks WHERE property_id=? AND NOT (check_out <= ? OR check_in >= ?) LIMIT 1 FOR UPDATE');
    $lockStmt->execute([$propertyId, $checkIn, $checkOut]);
    if ($lockStmt->fetch()) {
        return null;
    }

    if (function_exists('hv4_availability_is_free') && !hv4_availability_is_free($pdo, $propertyId, $checkIn, $checkOut)) {
        return null;
    }
    $pdo->prepare('INSERT INTO reservation_locks (property_id, check_in, check_out, lock_token, source, expires_at) VALUES (?,?,?,?,?,?)')
        ->execute([$propertyId, $checkIn, $checkOut, $token, $source, $expires]);
    return $token;
}

function hv5_commit_reservation_lock(PDO $pdo, string $token, int $bookingId): void {
    if (!hv5_table_exists('reservation_locks')) return;
    $st = $pdo->prepare('SELECT property_id FROM reservation_locks WHERE lock_token=?');
    $st->execute([$token]);
    $pid = (int)$st->fetchColumn();
    $pdo->prepare('UPDATE reservation_locks SET booking_id=?, expires_at=DATE_ADD(NOW(), INTERVAL 1 DAY) WHERE lock_token=?')->execute([$bookingId, $token]);
    if ($pid) hv5_invalidate_availability_cache($pdo, $pid);
}

function hv5_release_reservation_lock(PDO $pdo, string $token): void {
    if (!hv5_table_exists('reservation_locks')) return;
    $pdo->prepare('DELETE FROM reservation_locks WHERE lock_token=?')->execute([$token]);
}

function hv5_invalidate_availability_cache(PDO $pdo, int $propertyId): void {
    if (!hv5_table_exists('availability_cache')) return;
    $pdo->prepare('DELETE FROM availability_cache WHERE property_id=?')->execute([$propertyId]);
}
