<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Channel Manager Settings';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}

if (!function_exists('cm_table_exists')) {
    function cm_table_exists(PDO $pdo, string $tableName): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :table_name");
        $stmt->execute([':table_name' => $tableName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('cm_column_exists')) {
    function cm_column_exists(PDO $pdo, string $tableName, string $columnName): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = :table_name AND column_name = :column_name");
        $stmt->execute([':table_name' => $tableName, ':column_name' => $columnName]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('cm_flash')) {
    function cm_flash(string $type, string $message): void {
        $_SESSION['channel_settings_flash'][] = ['type' => $type, 'message' => $message];
    }
}

if (!function_exists('cm_get_flash')) {
    function cm_get_flash(): array {
        $items = $_SESSION['channel_settings_flash'] ?? [];
        unset($_SESSION['channel_settings_flash']);
        return $items;
    }
}

if (!function_exists('cm_mask_secret')) {
    function cm_mask_secret(?string $value): string {
        $value = (string)$value;
        if ($value === '') return '';
        $length = strlen($value);
        if ($length <= 6) return str_repeat('•', $length);
        return substr($value, 0, 3) . str_repeat('•', max(4, $length - 6)) . substr($value, -3);
    }
}

if (!function_exists('cm_encrypt_secret')) {
    function cm_encrypt_secret(?string $value): ?string {
        $value = trim((string)$value);
        return $value === '' ? null : base64_encode($value);
    }
}

if (!function_exists('cm_decrypt_secret')) {
    function cm_decrypt_secret(?string $value): string {
        $value = (string)$value;
        if ($value === '') return '';
        $decoded = base64_decode($value, true);
        return $decoded === false ? $value : $decoded;
    }
}

if (!function_exists('cm_bool')) {
    function cm_bool($value): int {
        return in_array((string)$value, ['1','yes','true','on'], true) ? 1 : 0;
    }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS channel_connections (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        provider ENUM('nightsbridge','booking_com','expedia','airbnb','custom') NOT NULL DEFAULT 'nightsbridge',
        connection_name VARCHAR(150) NOT NULL,
        property_id INT UNSIGNED NULL,
        external_property_id VARCHAR(120) NULL,
        api_base_url VARCHAR(255) NULL,
        api_username VARCHAR(150) NULL,
        api_password_enc TEXT NULL,
        api_token_enc TEXT NULL,
        webhook_secret_enc TEXT NULL,
        sync_mode ENUM('manual','scheduled','webhook') NOT NULL DEFAULT 'manual',
        sync_direction ENUM('pull_only','push_only','two_way') NOT NULL DEFAULT 'two_way',
        push_rates TINYINT(1) NOT NULL DEFAULT 1,
        push_availability TINYINT(1) NOT NULL DEFAULT 1,
        pull_bookings TINYINT(1) NOT NULL DEFAULT 1,
        auto_confirm_imported TINYINT(1) NOT NULL DEFAULT 0,
        prevent_overbooking TINYINT(1) NOT NULL DEFAULT 1,
        last_sync_at DATETIME NULL,
        last_sync_status VARCHAR(30) NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_channel_provider (provider),
        INDEX idx_channel_property (property_id),
        INDEX idx_channel_active (is_active)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS channel_sync_log (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        connection_id INT UNSIGNED NULL,
        provider VARCHAR(50) NOT NULL,
        sync_type VARCHAR(80) NOT NULL,
        sync_direction VARCHAR(30) NOT NULL,
        status VARCHAR(30) NOT NULL,
        request_payload MEDIUMTEXT NULL,
        response_payload MEDIUMTEXT NULL,
        message TEXT NULL,
        started_at DATETIME NOT NULL,
        completed_at DATETIME NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_channel_log_connection (connection_id),
        INDEX idx_channel_log_provider (provider),
        INDEX idx_channel_log_status (status),
        INDEX idx_channel_log_started (started_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS channel_room_mapping (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        connection_id INT UNSIGNED NOT NULL,
        property_id INT UNSIGNED NULL,
        room_type_id INT UNSIGNED NOT NULL,
        external_room_id VARCHAR(120) NOT NULL,
        external_room_name VARCHAR(180) NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_channel_room_map (connection_id, room_type_id, external_room_id),
        INDEX idx_channel_room_connection (connection_id),
        INDEX idx_channel_room_type (room_type_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS channel_rate_mapping (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        connection_id INT UNSIGNED NOT NULL,
        room_type_id INT UNSIGNED NOT NULL,
        rate_plan_id INT UNSIGNED NULL,
        external_rate_id VARCHAR(120) NOT NULL,
        external_rate_name VARCHAR(180) NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_channel_rate_map (connection_id, room_type_id, external_rate_id),
        INDEX idx_channel_rate_connection (connection_id),
        INDEX idx_channel_rate_room_type (room_type_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS channel_booking_imports (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        connection_id INT UNSIGNED NOT NULL,
        provider VARCHAR(50) NOT NULL,
        external_booking_id VARCHAR(150) NOT NULL,
        order_id INT UNSIGNED NULL,
        guest_name VARCHAR(180) NULL,
        check_in DATE NULL,
        check_out DATE NULL,
        total_amount DECIMAL(12,2) NOT NULL DEFAULT 0.00,
        currency VARCHAR(10) NULL,
        import_status VARCHAR(40) NOT NULL DEFAULT 'pending',
        raw_payload MEDIUMTEXT NULL,
        imported_at DATETIME NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY uq_channel_booking (provider, external_booking_id),
        INDEX idx_channel_booking_connection (connection_id),
        INDEX idx_channel_booking_order (order_id),
        INDEX idx_channel_booking_status (import_status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare channel manager tables: ' . $e->getMessage();
}

$properties = [];
try {
    if (cm_table_exists($pdo, 'properties')) {
        $properties = $pdo->query("SELECT id, name, code FROM properties WHERE is_active = 1 ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $properties = [];
}

$providers = [
    'nightsbridge' => 'NightsBridge',
    'booking_com' => 'Booking.com',
    'expedia' => 'Expedia',
    'airbnb' => 'Airbnb',
    'custom' => 'Custom API / Webhook',
];

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();

        $action = (string)($_POST['action'] ?? '');

        if ($action === 'save_connection') {
            $id = (int)($_POST['id'] ?? 0);
            $provider = (string)($_POST['provider'] ?? 'nightsbridge');
            $connectionName = trim((string)($_POST['connection_name'] ?? ''));
            $propertyId = (int)($_POST['property_id'] ?? 0);
            $externalPropertyId = trim((string)($_POST['external_property_id'] ?? ''));
            $apiBaseUrl = trim((string)($_POST['api_base_url'] ?? ''));
            $apiUsername = trim((string)($_POST['api_username'] ?? ''));
            $apiPassword = trim((string)($_POST['api_password'] ?? ''));
            $apiToken = trim((string)($_POST['api_token'] ?? ''));
            $webhookSecret = trim((string)($_POST['webhook_secret'] ?? ''));
            $syncMode = (string)($_POST['sync_mode'] ?? 'manual');
            $syncDirection = (string)($_POST['sync_direction'] ?? 'two_way');
            $pushRates = cm_bool($_POST['push_rates'] ?? 0);
            $pushAvailability = cm_bool($_POST['push_availability'] ?? 0);
            $pullBookings = cm_bool($_POST['pull_bookings'] ?? 0);
            $autoConfirmImported = cm_bool($_POST['auto_confirm_imported'] ?? 0);
            $preventOverbooking = cm_bool($_POST['prevent_overbooking'] ?? 0);
            $isActive = cm_bool($_POST['is_active'] ?? 0);
            $notes = trim((string)($_POST['notes'] ?? ''));

            if (!isset($providers[$provider])) throw new RuntimeException('Invalid provider selected.');
            if (!in_array($syncMode, ['manual','scheduled','webhook'], true)) throw new RuntimeException('Invalid sync mode.');
            if (!in_array($syncDirection, ['pull_only','push_only','two_way'], true)) throw new RuntimeException('Invalid sync direction.');
            if ($connectionName === '') throw new RuntimeException('Connection name is required.');
            if ($propertyId <= 0) throw new RuntimeException('Please select a property.');
            if ($externalPropertyId === '') throw new RuntimeException('External property ID is required.');

            if ($provider !== 'custom' && $apiBaseUrl === '') {
                $apiBaseUrl = [
                    'nightsbridge' => 'https://api.nightsbridge.com/',
                    'booking_com' => 'https://distribution-xml.booking.com/',
                    'expedia' => 'https://api.expediagroup.com/',
                    'airbnb' => 'https://api.airbnb.com/',
                ][$provider] ?? null;
            }

            $existing = null;
            if ($id > 0) {
                $stmt = $pdo->prepare("SELECT * FROM channel_connections WHERE id = :id LIMIT 1");
                $stmt->execute([':id' => $id]);
                $existing = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
            }

            $apiPasswordEnc = $apiPassword !== '' ? cm_encrypt_secret($apiPassword) : ($existing['api_password_enc'] ?? null);
            $apiTokenEnc = $apiToken !== '' ? cm_encrypt_secret($apiToken) : ($existing['api_token_enc'] ?? null);
            $webhookSecretEnc = $webhookSecret !== '' ? cm_encrypt_secret($webhookSecret) : ($existing['webhook_secret_enc'] ?? null);

            $payload = [
                ':provider' => $provider,
                ':connection_name' => $connectionName,
                ':property_id' => $propertyId,
                ':external_property_id' => $externalPropertyId,
                ':api_base_url' => $apiBaseUrl !== '' ? $apiBaseUrl : null,
                ':api_username' => $apiUsername !== '' ? $apiUsername : null,
                ':api_password_enc' => $apiPasswordEnc,
                ':api_token_enc' => $apiTokenEnc,
                ':webhook_secret_enc' => $webhookSecretEnc,
                ':sync_mode' => $syncMode,
                ':sync_direction' => $syncDirection,
                ':push_rates' => $pushRates,
                ':push_availability' => $pushAvailability,
                ':pull_bookings' => $pullBookings,
                ':auto_confirm_imported' => $autoConfirmImported,
                ':prevent_overbooking' => $preventOverbooking,
                ':is_active' => $isActive,
                ':notes' => $notes !== '' ? $notes : null,
            ];

            if ($id > 0) {
                $payload[':id'] = $id;
                $stmt = $pdo->prepare("UPDATE channel_connections SET
                    provider=:provider, connection_name=:connection_name, property_id=:property_id,
                    external_property_id=:external_property_id, api_base_url=:api_base_url,
                    api_username=:api_username, api_password_enc=:api_password_enc,
                    api_token_enc=:api_token_enc, webhook_secret_enc=:webhook_secret_enc,
                    sync_mode=:sync_mode, sync_direction=:sync_direction,
                    push_rates=:push_rates, push_availability=:push_availability, pull_bookings=:pull_bookings,
                    auto_confirm_imported=:auto_confirm_imported, prevent_overbooking=:prevent_overbooking,
                    is_active=:is_active, notes=:notes
                    WHERE id=:id");
                $stmt->execute($payload);
                cm_flash('success', 'Channel connection updated successfully.');
            } else {
                $stmt = $pdo->prepare("INSERT INTO channel_connections
                    (provider, connection_name, property_id, external_property_id, api_base_url, api_username,
                     api_password_enc, api_token_enc, webhook_secret_enc, sync_mode, sync_direction,
                     push_rates, push_availability, pull_bookings, auto_confirm_imported, prevent_overbooking,
                     is_active, notes)
                    VALUES
                    (:provider, :connection_name, :property_id, :external_property_id, :api_base_url, :api_username,
                     :api_password_enc, :api_token_enc, :webhook_secret_enc, :sync_mode, :sync_direction,
                     :push_rates, :push_availability, :pull_bookings, :auto_confirm_imported, :prevent_overbooking,
                     :is_active, :notes)");
                $stmt->execute($payload);
                cm_flash('success', 'Channel connection created successfully.');
            }

            header('Location: channel_settings.php');
            exit;
        }

        if ($action === 'toggle_connection') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid connection selected.');
            $stmt = $pdo->prepare("UPDATE channel_connections SET is_active = CASE WHEN is_active=1 THEN 0 ELSE 1 END WHERE id=:id");
            $stmt->execute([':id' => $id]);
            cm_flash('success', 'Connection status updated.');
            header('Location: channel_settings.php');
            exit;
        }

        if ($action === 'delete_connection') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid connection selected.');
            $pdo->beginTransaction();
            $pdo->prepare("DELETE FROM channel_room_mapping WHERE connection_id=:id")->execute([':id' => $id]);
            $pdo->prepare("DELETE FROM channel_rate_mapping WHERE connection_id=:id")->execute([':id' => $id]);
            $pdo->prepare("DELETE FROM channel_connections WHERE id=:id")->execute([':id' => $id]);
            $pdo->commit();
            cm_flash('success', 'Connection deleted.');
            header('Location: channel_settings.php');
            exit;
        }

        if ($action === 'test_connection') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid connection selected.');
            $stmt = $pdo->prepare("SELECT * FROM channel_connections WHERE id=:id LIMIT 1");
            $stmt->execute([':id' => $id]);
            $connection = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$connection) throw new RuntimeException('Connection not found.');

            $status = 'pending';
            $message = 'Connection saved. API handshake connector not yet configured for ' . $connection['provider'] . '.';
            if (!empty($connection['api_base_url']) && (!empty($connection['api_token_enc']) || !empty($connection['api_username']))) {
                $status = 'ready';
                $message = 'Connection has base URL and credentials. Ready for provider connector testing.';
            }

            $stmt = $pdo->prepare("INSERT INTO channel_sync_log
                (connection_id, provider, sync_type, sync_direction, status, request_payload, response_payload, message, started_at, completed_at)
                VALUES (:connection_id, :provider, 'connection_test', 'manual', :status, NULL, NULL, :message, NOW(), NOW())");
            $stmt->execute([
                ':connection_id' => $id,
                ':provider' => $connection['provider'],
                ':status' => $status,
                ':message' => $message,
            ]);

            $pdo->prepare("UPDATE channel_connections SET last_sync_at=NOW(), last_sync_status=:status WHERE id=:id")
                ->execute([':status' => $status, ':id' => $id]);

            cm_flash($status === 'ready' ? 'success' : 'warning', $message);
            header('Location: channel_settings.php');
            exit;
        }
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        cm_flash('danger', $e->getMessage());
        header('Location: channel_settings.php');
        exit;
    }
}

$editId = (int)($_GET['edit_id'] ?? 0);
$editConnection = null;
if ($editId > 0) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM channel_connections WHERE id=:id LIMIT 1");
        $stmt->execute([':id' => $editId]);
        $editConnection = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    } catch (Throwable $e) {}
}

$filterProvider = trim((string)($_GET['provider'] ?? ''));
$filterStatus = trim((string)($_GET['status'] ?? ''));
$where = '1=1';
$params = [];

if ($filterProvider !== '') {
    $where .= ' AND cc.provider = :provider ';
    $params[':provider'] = $filterProvider;
}
if ($filterStatus !== '') {
    $where .= ' AND cc.is_active = :is_active ';
    $params[':is_active'] = (int)$filterStatus;
}

$connections = [];
$summary = ['total'=>0,'active'=>0,'inactive'=>0,'ready'=>0,'pending'=>0];

try {
    $stmt = $pdo->prepare("SELECT cc.*, p.name AS property_name, p.code AS property_code,
        (SELECT COUNT(*) FROM channel_room_mapping crm WHERE crm.connection_id=cc.id) AS mapped_rooms,
        (SELECT COUNT(*) FROM channel_rate_mapping crm2 WHERE crm2.connection_id=cc.id) AS mapped_rates
        FROM channel_connections cc
        LEFT JOIN properties p ON p.id=cc.property_id
        WHERE $where
        ORDER BY cc.is_active DESC, cc.provider ASC, cc.connection_name ASC");
    $stmt->execute($params);
    $connections = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($connections as $connection) {
        $summary['total']++;
        if ((int)$connection['is_active'] === 1) $summary['active']++;
        else $summary['inactive']++;
        if (($connection['last_sync_status'] ?? '') === 'ready') $summary['ready']++;
        else $summary['pending']++;
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load channel connections: ' . $e->getMessage();
}

$recentLogs = [];
try {
    $recentLogs = $pdo->query("SELECT csl.*, cc.connection_name
        FROM channel_sync_log csl
        LEFT JOIN channel_connections cc ON cc.id=csl.connection_id
        ORDER BY csl.started_at DESC
        LIMIT 12")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {}

$flashes = cm_get_flash();

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-cloud-arrow-up"></i> Channel Manager</div>
            <div class="hero-title mt-2">Channel Manager Settings</div>
            <div class="hero-subtitle mt-2">Configure NightsBridge, Booking.com, Expedia, Airbnb and future OTA connections safely from one place.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="channel_mapping.php" class="btn btn-light me-2"><i class="bi bi-diagram-3 me-2"></i>Mappings</a>
            <a href="channel_sync_log.php" class="btn btn-outline-light"><i class="bi bi-clock-history me-2"></i>Sync Log</a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $flash): ?>
    <div class="alert alert-<?php echo h($flash['type']); ?>"><?php echo h($flash['message']); ?></div>
<?php endforeach; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<div class="alert alert-warning">
    <strong>Important:</strong> Direct OTA APIs often require provider approval/certification. This page stores and manages your connection settings. Actual API push/pull connectors are built in the next files.
</div>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-plug"></i></div><div><div class="metric-label">Connections</div><div class="metric-value"><?php echo (int)$summary['total']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-success-subtle text-success"><i class="bi bi-toggle-on"></i></div><div><div class="metric-label">Active</div><div class="metric-value"><?php echo (int)$summary['active']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-hourglass-split"></i></div><div><div class="metric-label">Pending Setup</div><div class="metric-value"><?php echo (int)$summary['pending']; ?></div></div></div></div>
    <div class="col-md-6 col-xl-3"><div class="metric-card"><div class="metric-icon bg-info-subtle text-info"><i class="bi bi-check2-circle"></i></div><div><div class="metric-label">Ready</div><div class="metric-value"><?php echo (int)$summary['ready']; ?></div></div></div></div>
</div>

<div class="row g-4">
    <div class="col-xl-4">
        <div class="card panel-card sticky-xl-top" style="top:20px;">
            <div class="card-header"><h5 class="mb-0"><?php echo $editConnection ? 'Edit Channel Connection' : 'Add Channel Connection'; ?></h5></div>
            <div class="card-body">
                <form method="post" autocomplete="off">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_connection">
                    <input type="hidden" name="id" value="<?php echo (int)($editConnection['id'] ?? 0); ?>">

                    <div class="mb-3">
                        <label class="form-label">Provider</label>
                        <select name="provider" class="form-select" required>
                            <?php foreach ($providers as $value => $label): ?>
                                <option value="<?php echo h($value); ?>" <?php echo (($editConnection['provider'] ?? 'nightsbridge') === $value) ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Connection Name</label>
                        <input type="text" name="connection_name" class="form-control" required value="<?php echo h($editConnection['connection_name'] ?? ''); ?>" placeholder="NightsBridge - Main Lodge">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Property</label>
                        <select name="property_id" class="form-select" required>
                            <option value="">Select property</option>
                            <?php foreach ($properties as $property): ?>
                                <option value="<?php echo (int)$property['id']; ?>" <?php echo (int)($editConnection['property_id'] ?? 0) === (int)$property['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($property['name']); ?> - <?php echo h($property['code']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">External Property ID</label>
                        <input type="text" name="external_property_id" class="form-control" required value="<?php echo h($editConnection['external_property_id'] ?? ''); ?>" placeholder="Provider property / hotel ID">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">API Base URL</label>
                        <input type="url" name="api_base_url" class="form-control" value="<?php echo h($editConnection['api_base_url'] ?? ''); ?>" placeholder="https://api.provider.com/">
                        <div class="small text-muted mt-1">Leave blank to use provider default where available.</div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">API Username</label>
                        <input type="text" name="api_username" class="form-control" value="<?php echo h($editConnection['api_username'] ?? ''); ?>" placeholder="Optional">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">API Password</label>
                        <input type="password" name="api_password" class="form-control" value="" placeholder="<?php echo !empty($editConnection['api_password_enc']) ? 'Saved: ' . cm_mask_secret(cm_decrypt_secret($editConnection['api_password_enc'])) : 'Optional'; ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">API Token / Key</label>
                        <input type="password" name="api_token" class="form-control" value="" placeholder="<?php echo !empty($editConnection['api_token_enc']) ? 'Saved: ' . cm_mask_secret(cm_decrypt_secret($editConnection['api_token_enc'])) : 'Optional'; ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Webhook Secret</label>
                        <input type="password" name="webhook_secret" class="form-control" value="" placeholder="<?php echo !empty($editConnection['webhook_secret_enc']) ? 'Saved: ' . cm_mask_secret(cm_decrypt_secret($editConnection['webhook_secret_enc'])) : 'Optional'; ?>">
                    </div>

                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Sync Mode</label>
                            <select name="sync_mode" class="form-select">
                                <?php foreach (['manual'=>'Manual','scheduled'=>'Scheduled','webhook'=>'Webhook'] as $value => $label): ?>
                                    <option value="<?php echo h($value); ?>" <?php echo (($editConnection['sync_mode'] ?? 'manual') === $value) ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Direction</label>
                            <select name="sync_direction" class="form-select">
                                <?php foreach (['pull_only'=>'Pull Only','push_only'=>'Push Only','two_way'=>'Two Way'] as $value => $label): ?>
                                    <option value="<?php echo h($value); ?>" <?php echo (($editConnection['sync_direction'] ?? 'two_way') === $value) ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="settings-check-grid mt-3">
                        <?php
                        $checks = [
                            'push_rates'=>'Push Rates','push_availability'=>'Push Availability','pull_bookings'=>'Pull Bookings',
                            'auto_confirm_imported'=>'Auto-confirm Imported','prevent_overbooking'=>'Prevent Overbooking','is_active'=>'Active'
                        ];
                        ?>
                        <?php foreach ($checks as $field => $label): ?>
                            <?php $default = in_array($field, ['push_rates','push_availability','pull_bookings','prevent_overbooking','is_active'], true) ? 1 : 0; ?>
                            <label class="setting-check">
                                <input type="checkbox" name="<?php echo h($field); ?>" value="1" <?php echo (int)($editConnection[$field] ?? $default) === 1 ? 'checked' : ''; ?>>
                                <span><?php echo h($label); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>

                    <div class="mt-3">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-control" rows="3" placeholder="Internal notes, certification status, provider contacts"><?php echo h($editConnection['notes'] ?? ''); ?></textarea>
                    </div>

                    <div class="d-grid gap-2 mt-4">
                        <button class="btn btn-primary"><i class="bi bi-save me-2"></i><?php echo $editConnection ? 'Update Connection' : 'Create Connection'; ?></button>
                        <?php if ($editConnection): ?><a href="channel_settings.php" class="btn btn-outline-secondary">Cancel Edit</a><?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card panel-card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3 align-items-end">
                    <div class="col-md-5">
                        <label class="form-label">Provider</label>
                        <select name="provider" class="form-select">
                            <option value="">All providers</option>
                            <?php foreach ($providers as $value => $label): ?>
                                <option value="<?php echo h($value); ?>" <?php echo $filterProvider === $value ? 'selected' : ''; ?>><?php echo h($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All</option>
                            <option value="1" <?php echo $filterStatus === '1' ? 'selected' : ''; ?>>Active</option>
                            <option value="0" <?php echo $filterStatus === '0' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    <div class="col-md-3 d-grid"><button class="btn btn-primary"><i class="bi bi-funnel me-2"></i>Filter</button></div>
                </form>
            </div>
        </div>

        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Channel Connections</h5></div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr><th>Connection</th><th>Property</th><th>Sync</th><th>Mappings</th><th>Last Status</th><th>Status</th><th class="text-end">Actions</th></tr>
                        </thead>
                        <tbody>
                        <?php if (!$connections): ?>
                            <tr><td colspan="7" class="text-center text-muted py-4">No channel connections configured yet.</td></tr>
                        <?php else: ?>
                            <?php foreach ($connections as $connection): ?>
                                <?php
                                $providerLabel = $providers[$connection['provider']] ?? ucwords(str_replace('_', ' ', $connection['provider']));
                                $lastStatus = $connection['last_sync_status'] ?: 'pending';
                                $statusBadge = 'text-bg-secondary';
                                if ($lastStatus === 'ready' || $lastStatus === 'success') $statusBadge = 'text-bg-success';
                                elseif ($lastStatus === 'failed') $statusBadge = 'text-bg-danger';
                                elseif ($lastStatus === 'pending') $statusBadge = 'text-bg-warning';
                                ?>
                                <tr>
                                    <td>
                                        <strong><?php echo h($connection['connection_name']); ?></strong>
                                        <div class="small text-muted"><?php echo h($providerLabel); ?> • External ID: <?php echo h($connection['external_property_id']); ?></div>
                                    </td>
                                    <td><?php echo h($connection['property_name'] ?: 'Property'); ?><div class="small text-muted"><?php echo h($connection['property_code'] ?: ''); ?></div></td>
                                    <td><span class="badge text-bg-light border"><?php echo h(ucwords($connection['sync_mode'])); ?></span><div class="small text-muted"><?php echo h(ucwords(str_replace('_', ' ', $connection['sync_direction']))); ?></div></td>
                                    <td><div class="small">Rooms: <strong><?php echo (int)$connection['mapped_rooms']; ?></strong></div><div class="small">Rates: <strong><?php echo (int)$connection['mapped_rates']; ?></strong></div></td>
                                    <td><span class="badge <?php echo h($statusBadge); ?>"><?php echo h(ucwords($lastStatus)); ?></span><div class="small text-muted"><?php echo h($connection['last_sync_at'] ?: 'Never synced'); ?></div></td>
                                    <td><span class="badge <?php echo (int)$connection['is_active'] === 1 ? 'text-bg-success' : 'text-bg-secondary'; ?>"><?php echo (int)$connection['is_active'] === 1 ? 'Active' : 'Inactive'; ?></span></td>
                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm">
                                            <a href="channel_settings.php?edit_id=<?php echo (int)$connection['id']; ?>" class="btn btn-outline-primary" title="Edit"><i class="bi bi-pencil"></i></a>
                                            <a href="channel_mapping.php?connection_id=<?php echo (int)$connection['id']; ?>" class="btn btn-outline-info" title="Mappings"><i class="bi bi-diagram-3"></i></a>
                                            <form method="post" class="d-inline">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="test_connection"><input type="hidden" name="id" value="<?php echo (int)$connection['id']; ?>">
                                                <button type="submit" class="btn btn-outline-success" title="Test"><i class="bi bi-plug"></i></button>
                                            </form>
                                            <form method="post" class="d-inline">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="toggle_connection"><input type="hidden" name="id" value="<?php echo (int)$connection['id']; ?>">
                                                <button type="submit" class="btn btn-outline-secondary" title="Toggle"><i class="bi bi-toggle-on"></i></button>
                                            </form>
                                            <form method="post" class="d-inline" onsubmit="return confirm('Delete this connection and its mappings?');">
                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                <input type="hidden" name="action" value="delete_connection"><input type="hidden" name="id" value="<?php echo (int)$connection['id']; ?>">
                                                <button type="submit" class="btn btn-outline-danger" title="Delete"><i class="bi bi-trash"></i></button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Recent Channel Activity</h5></div>
            <div class="card-body p-0">
                <table class="table table-modern align-middle mb-0">
                    <thead><tr><th>Time</th><th>Connection</th><th>Type</th><th>Direction</th><th>Status</th><th>Message</th></tr></thead>
                    <tbody>
                    <?php if (!$recentLogs): ?>
                        <tr><td colspan="6" class="text-center text-muted py-4">No channel activity yet.</td></tr>
                    <?php else: ?>
                        <?php foreach ($recentLogs as $log): ?>
                            <?php
                            $logBadge = 'text-bg-secondary';
                            if ($log['status'] === 'success' || $log['status'] === 'ready') $logBadge = 'text-bg-success';
                            elseif ($log['status'] === 'failed') $logBadge = 'text-bg-danger';
                            elseif ($log['status'] === 'pending') $logBadge = 'text-bg-warning';
                            ?>
                            <tr>
                                <td><?php echo h($log['started_at']); ?></td>
                                <td><?php echo h($log['connection_name'] ?: $log['provider']); ?></td>
                                <td><?php echo h(ucwords(str_replace('_', ' ', $log['sync_type']))); ?></td>
                                <td><?php echo h(ucwords(str_replace('_', ' ', $log['sync_direction']))); ?></td>
                                <td><span class="badge <?php echo h($logBadge); ?>"><?php echo h(ucwords($log['status'])); ?></span></td>
                                <td class="small text-muted"><?php echo h($log['message']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<style>
.settings-check-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}
.setting-check{display:flex;align-items:center;gap:8px;border:1px solid rgba(15,23,42,.10);background:#fff;border-radius:14px;padding:10px 12px;font-weight:800;font-size:13px;color:#475569;cursor:pointer}
.setting-check input{width:16px;height:16px}
@media (max-width:575.98px){.settings-check-grid{grid-template-columns:1fr}}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
