<?php
require_auth();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();
$sub = trim($_GET['r'] ?? '', '/');

if ($sub === 'ota/process' && $method === 'POST') {
    require_permission('ota.manage');
    if (!function_exists('hv4_process_sync_queue')) json_error('V4 not loaded', 503);
    json_ok(hv4_process_sync_queue(20), 'Queue processed');
}

if ($method === 'GET') {
    require_permission('ota.view');
    if (!hv4_table_exists('ota_connections')) {
        json_ok(['connections' => [], 'queue' => [], 'logs' => [], 'migration_required' => true]);
    }
    $connections = db()->query('SELECT id, property_id, provider, name, external_listing_id, sync_enabled, last_sync_at, status FROM ota_connections ORDER BY provider')->fetchAll();
    $queue = db()->query("SELECT q.*, c.name AS connection_name FROM ota_sync_queue q JOIN ota_connections c ON c.id=q.ota_connection_id ORDER BY q.id DESC LIMIT 30")->fetchAll();
    $logs = db()->query('SELECT * FROM ota_sync_log ORDER BY id DESC LIMIT 40')->fetchAll();
    json_ok(compact('connections', 'queue', 'logs'));
}

csrf_check();
require_permission('ota.manage');

if ($method === 'POST') {
    if (!hv4_table_exists('ota_connections')) json_error('Run V4 migration', 503);
    $err = v_required($d, ['provider', 'name']);
    if ($err) json_error('Validation failed', 422, $err);
    $secret = bin2hex(random_bytes(16));
    db()->prepare('INSERT INTO ota_connections (property_id, provider, name, external_listing_id, sync_enabled, status, webhook_secret, settings) VALUES (?,?,?,?,?,?,?,?)')
        ->execute([
            !empty($d['property_id']) ? (int)$d['property_id'] : null,
            v_enum($d['provider'], ['airbnb', 'booking_com', 'vrbo', 'expedia', 'agoda', 'hospitable', 'guesty', 'other'], 'provider'),
            v_str($d, 'name', 120),
            v_str($d, 'external_listing_id', 120) ?: null,
            !empty($d['sync_enabled']) ? 1 : 0,
            'pending',
            $secret,
            json_encode(['oauth_status' => 'awaiting_credentials']),
        ]);
    $id = (int)db()->lastInsertId();
    json_ok(['id' => $id, 'webhook_url' => hv4_webhook_url($secret), 'oauth_note' => 'Add API credentials in settings for live sync'], 'Connection created');
}

if ($method === 'PUT') {
    $id = (int)($d['id'] ?? 0);
    if (!$id) json_error('id required', 422);
    $fields = [];
    $vals = [];
    foreach (['name', 'external_listing_id', 'sync_enabled', 'status'] as $f) {
        if (array_key_exists($f, $d)) {
            if ($f === 'sync_enabled') $d[$f] = !empty($d[$f]) ? 1 : 0;
            $fields[] = "$f=?";
            $vals[] = $d[$f];
        }
    }
    if ($fields) {
        $vals[] = $id;
        db()->prepare('UPDATE ota_connections SET ' . implode(',', $fields) . ' WHERE id=?')->execute($vals);
    }
    json_ok([], 'Updated');
}

json_error('Method not allowed', 405);

function hv4_webhook_url(string $secret): string {
    global $CONFIG;
    $base = rtrim($CONFIG['app']['url'] ?? '', '/');
    return $base . '/api/?r=ota/webhook&token=' . $secret;
}
