<?php
declare(strict_types=1);

function hv4_queue_outbound_sync(string $action, array $payload, ?int $otaConnectionId = null): void {
    if (!hv4_table_exists('ota_sync_queue')) return;
    if (!$otaConnectionId) {
        $rows = db()->query("SELECT id FROM ota_connections WHERE sync_enabled=1 AND status='active' LIMIT 20")->fetchAll(PDO::FETCH_COLUMN);
        foreach ($rows as $oid) {
            db()->prepare('INSERT INTO ota_sync_queue (ota_connection_id, direction, action, payload, status) VALUES (?,?,?,?,?)')
                ->execute([$oid, 'outbound', $action, json_encode($payload), 'pending']);
        }
        return;
    }
    db()->prepare('INSERT INTO ota_sync_queue (ota_connection_id, direction, action, payload, status) VALUES (?,?,?,?,?)')
        ->execute([$otaConnectionId, 'outbound', $action, json_encode($payload), 'pending']);
}

function hv4_process_sync_queue(int $limit = 10): array {
    if (!hv4_table_exists('ota_sync_queue')) return ['processed' => 0];
    $pdo = db();
    $items = $pdo->query("SELECT * FROM ota_sync_queue WHERE status='pending' AND (next_retry_at IS NULL OR next_retry_at <= NOW()) ORDER BY id LIMIT " . (int)$limit)->fetchAll();
    $done = 0;
    foreach ($items as $item) {
        $pdo->prepare("UPDATE ota_sync_queue SET status='processing' WHERE id=?")->execute([$item['id']]);
        $ok = hv4_simulate_ota_sync($item);
        if ($ok) {
            $pdo->prepare("UPDATE ota_sync_queue SET status='done', processed_at=NOW() WHERE id=?")->execute([$item['id']]);
            hv4_log_sync((int)$item['ota_connection_id'], $item['action'], 'success', 'Simulated sync OK (configure API keys for live)');
            $done++;
        } else {
            $attempts = (int)$item['attempts'] + 1;
            $pdo->prepare("UPDATE ota_sync_queue SET status='pending', attempts=?, next_retry_at=DATE_ADD(NOW(), INTERVAL 5 MINUTE), last_error=? WHERE id=?")
                ->execute([$attempts, 'Retry scheduled', $item['id']]);
        }
    }
    return ['processed' => $done, 'total' => count($items)];
}

function hv4_simulate_ota_sync(array $item): bool {
    global $CONFIG;
    $mode = $CONFIG['v4']['ota_mode'] ?? 'simulation';
    if ($mode === 'live') {
        // Production: call provider APIs using stored tokens
        return false;
    }
    return true;
}

function hv4_log_sync(?int $connId, string $action, string $status, string $message, ?int $bookingId = null, $payload = null): void {
    if (!hv4_table_exists('ota_sync_log')) return;
    db()->prepare('INSERT INTO ota_sync_log (ota_connection_id, booking_id, action, status, message, payload) VALUES (?,?,?,?,?,?)')
        ->execute([$connId, $bookingId, $action, $status, $message, $payload ? json_encode($payload) : null]);
}

function hv4_handle_inbound_webhook(string $provider, array $payload): void {
    hv4_log_sync(null, 'webhook.' . $provider, 'success', 'Webhook received', null, $payload);
    if (($payload['event'] ?? '') === 'reservation.created' && !empty($payload['property_id'])) {
        hv4_emit_event('ota.reservation.inbound', $payload, 'booking', null);
    }
}
