<?php
/**
 * Channel integrations — Unified to use ota_connections table to prevent duplicate sources of truth.
 */
require_auth();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();
$id = (int)($d['id'] ?? 0);
$providers = ['airbnb', 'booking_com', 'vrbo', 'hospitable', 'guesty', 'direct', 'other'];

if ($method === 'GET') {
    require_permission('channels.view');
    $where = '1=1';
    $params = [];
    if (!empty($d['property_id'])) {
        $where .= ' AND c.property_id=?';
        $params[] = (int)$d['property_id'];
    }
    // UNIFIED ARCHITECTURE: read from ota_connections instead of legacy channel_connections
    $sql = 'SELECT c.id, c.property_id, c.provider, c.name, c.external_listing_id AS external_id, c.sync_enabled, c.status, c.settings, p.name AS property_name 
            FROM ota_connections c
            LEFT JOIN properties p ON p.id=c.property_id
            WHERE ' . $where . ' ORDER BY c.provider, c.name LIMIT 200';
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll();
    foreach ($rows as &$r) {
        if (!empty($r['settings']) && is_string($r['settings'])) {
            $r['settings'] = json_decode($r['settings'], true) ?: [];
        }
    }
    json_ok($rows);
}

csrf_check();

if ($method === 'POST') {
    require_permission('channels.manage');
    $err = v_required($d, ['provider', 'name']);
    if ($err) json_error('Validation failed', 422, $err);
    $provider = v_enum($d['provider'], $providers, 'provider');
    $propertyId = !empty($d['property_id']) ? (int)$d['property_id'] : null;
    if ($propertyId) {
        $chk = db()->prepare('SELECT id FROM properties WHERE id=? AND deleted_at IS NULL');
        $chk->execute([$propertyId]);
        if (!$chk->fetch()) json_error('Property not found', 404);
    }
    $settings = isset($d['settings']) && is_array($d['settings']) ? json_encode($d['settings']) : null;
    $secret = bin2hex(random_bytes(16));
    
    // UNIFIED ARCHITECTURE: insert into ota_connections
    db()->prepare('INSERT INTO ota_connections (property_id, provider, name, external_listing_id, sync_enabled, status, settings, webhook_secret) VALUES (?,?,?,?,?,?,?,?)')
        ->execute([
            $propertyId,
            $provider,
            v_str($d, 'name', 100),
            v_str($d, 'external_id', 100) ?: null,
            !empty($d['sync_enabled']) ? 1 : 0,
            v_enum($d['status'] ?? 'inactive', ['active', 'inactive', 'pending', 'error'], 'status', 'inactive'),
            $settings,
            $secret
        ]);
    $nid = (int)db()->lastInsertId();
    audit('channel.create', 'ota_connection', $nid);
    json_ok(['id' => $nid], 'Channel connection saved');
}

if ($method === 'PUT') {
    require_permission('channels.manage');
    if (!$id) json_error('id required', 422);
    $allowed = ['property_id', 'provider', 'name', 'external_id', 'sync_enabled', 'status', 'settings'];
    $fields = [];
    $vals = [];
    foreach ($allowed as $f) {
        if (!array_key_exists($f, $d)) continue;
        if ($f === 'provider') $d[$f] = v_enum($d[$f], $providers, 'provider');
        if ($f === 'status') $d[$f] = v_enum($d[$f], ['active', 'inactive', 'pending', 'error'], 'status');
        if ($f === 'sync_enabled') $d[$f] = !empty($d[$f]) ? 1 : 0;
        if ($f === 'property_id') $d[$f] = $d[$f] !== '' && $d[$f] !== null ? (int)$d[$f] : null;
        if ($f === 'settings' && is_array($d[$f])) $d[$f] = json_encode($d[$f]);
        
        $dbField = ($f === 'external_id') ? 'external_listing_id' : $f;
        $fields[] = "$dbField=?";
        $vals[] = $d[$f];
    }
    if (!$fields) json_error('Nothing to update', 422);
    $vals[] = $id;
    // UNIFIED ARCHITECTURE: update ota_connections
    db()->prepare('UPDATE ota_connections SET ' . implode(',', $fields) . ' WHERE id=?')->execute($vals);
    audit('channel.update', 'ota_connection', $id);
    json_ok([], 'Updated');
}

if ($method === 'DELETE') {
    require_permission('channels.manage');
    if (!$id) json_error('id required', 422);
    db()->prepare('DELETE FROM ota_connections WHERE id=?')->execute([$id]);
    audit('channel.delete', 'ota_connection', $id);
    json_ok([], 'Removed');
}

json_error('Method not allowed', 405);
