<?php
/**
 * Public OTA webhook — token in query string (no session).
 */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_error('POST only', 405);
}

$token = (string)($_GET['token'] ?? '');
$raw = file_get_contents('php://input');
$payload = json_decode($raw, true) ?: [];

if (!$token || !function_exists('hv4_table_exists') || !hv4_table_exists('ota_connections')) {
    json_error('Invalid', 400);
}

$stmt = db()->prepare('SELECT * FROM ota_connections WHERE webhook_secret=? LIMIT 1');
$stmt->execute([$token]);
$conn = $stmt->fetch();
if (!$conn) json_error('Unauthorized', 401);

$sig = $_SERVER['HTTP_X_OTA_SIGNATURE'] ?? $_SERVER['HTTP_X_HUB_SIGNATURE'] ?? null;
if (function_exists('hv5_verify_webhook_signature')) {
    $secret = (string)($conn['webhook_secret'] ?? '');
    if ($sig && !hv5_verify_webhook_signature($token, $secret, $payload, $sig)) {
        json_error('Invalid signature', 403);
    }
}

$event = $payload['event'] ?? $payload['type'] ?? 'reservation.created';
if (in_array($event, ['reservation.created', 'booking.created', 'reservation_created'], true)) {
    if (function_exists('hv5_process_inbound_reservation')) {
        $bid = hv5_process_inbound_reservation($conn, $payload);
        if ($bid === null) {
            json_ok(['received' => true, 'booking_id' => null, 'status' => 'conflict_prevented'], 'Conflict handled');
        }
        json_ok(['received' => true, 'booking_id' => $bid], 'Reservation imported');
    }
}

if (function_exists('hv4_handle_inbound_webhook')) {
    hv4_handle_inbound_webhook($conn['provider'], array_merge($payload, ['connection_id' => $conn['id']]));
}

db()->prepare('UPDATE ota_connections SET last_sync_at=NOW() WHERE id=?')->execute([$conn['id']]);
json_ok(['received' => true], 'Webhook accepted');
