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

$pageTitle = 'Channel Manager Dashboard';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($amount): string { return number_format((float)$amount, 2); }
}
if (!function_exists('cmd_table_exists')) {
    function cmd_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('cmd_column_exists')) {
    function cmd_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('cmd_base_url')) {
    function cmd_base_url(string $path = ''): string {
        if (function_exists('base_url')) {
            return base_url($path);
        }

        $base = '/rooms/';
        return rtrim($base, '/') . '/' . ltrim($path, '/');
    }
}
if (!function_exists('cmd_absolute_url')) {
    function cmd_absolute_url(string $path): string {
        $host = $_SERVER['HTTP_HOST'] ?? '';
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';

        if ($host !== '') {
            return $scheme . '://' . $host . cmd_base_url($path);
        }

        return cmd_base_url($path);
    }
}

$errors = [];

/*
 * Ensure base tables exist so the dashboard does not crash on first open.
 */
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();
}

$summary = [
    'connections' => 0,
    'active_connections' => 0,
    'inactive_connections' => 0,
    'room_mappings' => 0,
    'rate_mappings' => 0,
    'failed_syncs' => 0,
    'pending_imports' => 0,
    'created_imports' => 0,
    'unmapped_room_types' => 0,
];

try {
    $summary['connections'] = (int)$pdo->query("SELECT COUNT(*) FROM channel_connections")->fetchColumn();
    $summary['active_connections'] = (int)$pdo->query("SELECT COUNT(*) FROM channel_connections WHERE is_active = 1")->fetchColumn();
    $summary['inactive_connections'] = (int)$pdo->query("SELECT COUNT(*) FROM channel_connections WHERE is_active = 0")->fetchColumn();
    $summary['room_mappings'] = (int)$pdo->query("SELECT COUNT(*) FROM channel_room_mapping WHERE is_active = 1")->fetchColumn();
    $summary['rate_mappings'] = (int)$pdo->query("SELECT COUNT(*) FROM channel_rate_mapping WHERE is_active = 1")->fetchColumn();
    $summary['failed_syncs'] = (int)$pdo->query("SELECT COUNT(*) FROM channel_sync_log WHERE status IN ('failed','error','rejected') AND started_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetchColumn();
    $summary['pending_imports'] = (int)$pdo->query("SELECT COUNT(*) FROM channel_booking_imports WHERE order_id IS NULL AND import_status IN ('pending','ready_for_reservation')")->fetchColumn();
    $summary['created_imports'] = (int)$pdo->query("SELECT COUNT(*) FROM channel_booking_imports WHERE order_id IS NOT NULL OR import_status = 'imported'")->fetchColumn();

    if (cmd_table_exists($pdo, 'room_types')) {
        $summary['unmapped_room_types'] = (int)$pdo->query("
            SELECT COUNT(*)
            FROM room_types rt
            WHERE NOT EXISTS (
                SELECT 1
                FROM channel_room_mapping crm
                WHERE crm.room_type_id = rt.id
                  AND crm.is_active = 1
            )
        ")->fetchColumn();
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load dashboard summary: ' . $e->getMessage();
}

$connections = [];
try {
    $connections = $pdo->query("
        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 AND crm.is_active = 1) AS room_map_count,
            (SELECT COUNT(*) FROM channel_rate_mapping crm2 WHERE crm2.connection_id = cc.id AND crm2.is_active = 1) AS rate_map_count,
            (SELECT COUNT(*) FROM channel_sync_log csl WHERE csl.connection_id = cc.id AND csl.status IN ('failed','error','rejected') AND csl.started_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)) AS failed_count,
            (SELECT COUNT(*) FROM channel_booking_imports cbi WHERE cbi.connection_id = cc.id AND cbi.order_id IS NULL AND cbi.import_status IN ('pending','ready_for_reservation')) AS pending_import_count
        FROM channel_connections cc
        LEFT JOIN properties p ON p.id = cc.property_id
        ORDER BY cc.is_active DESC, cc.provider ASC, cc.connection_name ASC
        LIMIT 20
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $connections = [];
}

$failedLogs = [];
try {
    $failedLogs = $pdo->query("
        SELECT
            csl.*,
            cc.connection_name
        FROM channel_sync_log csl
        LEFT JOIN channel_connections cc ON cc.id = csl.connection_id
        WHERE csl.status IN ('failed','error','rejected')
        ORDER BY csl.started_at DESC
        LIMIT 8
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $failedLogs = [];
}

$recentImports = [];
try {
    $recentImports = $pdo->query("
        SELECT
            cbi.*,
            cc.connection_name,
            cc.provider AS connection_provider,
            p.name AS property_name
        FROM channel_booking_imports cbi
        LEFT JOIN channel_connections cc ON cc.id = cbi.connection_id
        LEFT JOIN properties p ON p.id = cc.property_id
        ORDER BY cbi.created_at DESC
        LIMIT 10
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $recentImports = [];
}

$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 10
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $recentLogs = [];
}

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

function cmd_badge_class(string $status): string {
    $status = strtolower($status);
    if (in_array($status, ['success','ready','sent','imported'], true)) return 'text-bg-success';
    if (in_array($status, ['failed','error','rejected'], true)) return 'text-bg-danger';
    if (in_array($status, ['pending','queued','warning','preview'], true)) return 'text-bg-warning';
    if ($status === 'reviewed') return 'text-bg-info';
    return 'text-bg-secondary';
}

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-broadcast"></i> Channel Manager</div>
            <div class="hero-title mt-2">Channel Manager Dashboard</div>
            <div class="hero-subtitle mt-2">
                Control OTA connections, mappings, availability/rate pushes, booking imports, webhooks and failed syncs.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="channel_settings.php" class="btn btn-light me-2">
                <i class="bi bi-gear me-2"></i>Settings
            </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 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="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['active_connections']; ?>/<?php echo (int)$summary['connections']; ?></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-diagram-3"></i></div>
            <div>
                <div class="metric-label">Room / Rate Maps</div>
                <div class="metric-value"><?php echo (int)$summary['room_mappings']; ?>/<?php echo (int)$summary['rate_mappings']; ?></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-inbox"></i></div>
            <div>
                <div class="metric-label">Pending OTA Imports</div>
                <div class="metric-value"><?php echo (int)$summary['pending_imports']; ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-exclamation-triangle"></i></div>
            <div>
                <div class="metric-label">Failed Syncs 7 Days</div>
                <div class="metric-value"><?php echo (int)$summary['failed_syncs']; ?></div>
            </div>
        </div>
    </div>
</div>

<?php if ($summary['failed_syncs'] > 0): ?>
    <div class="alert alert-danger d-flex justify-content-between align-items-center">
        <div>
            <strong>Action required:</strong> <?php echo (int)$summary['failed_syncs']; ?> failed channel sync(s) found in the last 7 days.
        </div>
        <a href="channel_sync_log.php?status=failed" class="btn btn-sm btn-danger">Review Failed Syncs</a>
    </div>
<?php endif; ?>

<?php if ($summary['unmapped_room_types'] > 0): ?>
    <div class="alert alert-warning d-flex justify-content-between align-items-center">
        <div>
            <strong>Mapping incomplete:</strong> <?php echo (int)$summary['unmapped_room_types']; ?> PMS room type(s) are not mapped to any channel.
        </div>
        <a href="channel_mapping.php" class="btn btn-sm btn-warning">Fix Mapping</a>
    </div>
<?php endif; ?>

<div class="row g-4 mb-4">
    <div class="col-xl-8">
        <div class="card panel-card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Channel Connections</h5>
                <a href="channel_settings.php" class="btn btn-sm btn-outline-primary">
                    <i class="bi bi-plus-circle me-1"></i>Add / Edit
                </a>
            </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>Health</th>
                            <th class="text-end">Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$connections): ?>
                            <tr><td colspan="6" class="text-center text-muted py-4">No channel connections configured yet.</td></tr>
                        <?php else: ?>
                            <?php foreach ($connections as $connection): ?>
                                <?php
                                $provider = $providerLabels[$connection['provider']] ?? ucwords(str_replace('_', ' ', $connection['provider']));
                                $healthBadge = 'text-bg-success';
                                $healthText = 'Healthy';
                                if ((int)$connection['is_active'] !== 1) {
                                    $healthBadge = 'text-bg-secondary';
                                    $healthText = 'Inactive';
                                } elseif ((int)$connection['failed_count'] > 0) {
                                    $healthBadge = 'text-bg-danger';
                                    $healthText = 'Failed Syncs';
                                } elseif ((int)$connection['room_map_count'] === 0) {
                                    $healthBadge = 'text-bg-warning';
                                    $healthText = 'Needs Mapping';
                                }
                                ?>
                                <tr>
                                    <td>
                                        <strong><?php echo h($connection['connection_name']); ?></strong>
                                        <div class="small text-muted"><?php echo h($provider); ?> • 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['room_map_count']; ?></strong></div>
                                        <div class="small">Rates: <strong><?php echo (int)$connection['rate_map_count']; ?></strong></div>
                                    </td>
                                    <td>
                                        <span class="badge <?php echo h($healthBadge); ?>"><?php echo h($healthText); ?></span>
                                        <div class="small text-muted">
                                            Pending imports: <?php echo (int)$connection['pending_import_count']; ?>
                                        </div>
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm">
                                            <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>
                                            <a href="channel_push_availability.php?connection_id=<?php echo (int)$connection['id']; ?>" class="btn btn-outline-success" title="Push Availability">
                                                <i class="bi bi-calendar-check"></i>
                                            </a>
                                            <a href="channel_push_rates.php?connection_id=<?php echo (int)$connection['id']; ?>" class="btn btn-outline-warning" title="Push Rates">
                                                <i class="bi bi-tags"></i>
                                            </a>
                                            <a href="channel_pull_bookings.php?connection_id=<?php echo (int)$connection['id']; ?>" class="btn btn-outline-primary" title="Pull Bookings">
                                                <i class="bi bi-cloud-download"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-4">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Quick Actions</h5></div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <a href="channel_settings.php" class="btn btn-outline-primary text-start">
                        <i class="bi bi-gear me-2"></i> Manage Connections
                    </a>
                    <a href="channel_mapping.php" class="btn btn-outline-info text-start">
                        <i class="bi bi-diagram-3 me-2"></i> Room & Rate Mapping
                    </a>
                    <a href="channel_push_availability.php" class="btn btn-outline-success text-start">
                        <i class="bi bi-calendar-check me-2"></i> Push Availability
                    </a>
                    <a href="channel_push_rates.php" class="btn btn-outline-warning text-start">
                        <i class="bi bi-tags me-2"></i> Push Rates
                    </a>
                    <a href="channel_pull_bookings.php" class="btn btn-outline-primary text-start">
                        <i class="bi bi-cloud-download me-2"></i> Pull Bookings
                    </a>
                    <a href="channel_sync_log.php" class="btn btn-outline-secondary text-start">
                        <i class="bi bi-clock-history me-2"></i> View Sync Logs
                    </a>
                </div>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Webhook Endpoints</h5></div>
            <div class="card-body">
                <?php if (!$connections): ?>
                    <div class="text-muted small">Create a channel connection first to generate webhook URLs.</div>
                <?php else: ?>
                    <?php foreach (array_slice($connections, 0, 5) as $connection): ?>
                        <div class="webhook-box mb-3">
                            <div class="fw-bold small"><?php echo h($connection['connection_name']); ?></div>
                            <input class="form-control form-control-sm mt-1" readonly onclick="this.select()" value="<?php echo h(cmd_absolute_url('modules/channel_manager/channel_webhook.php?connection_id=' . (int)$connection['id'])); ?>">
                            <div class="small text-muted mt-1">Use with provider webhook configuration.</div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-6">
        <div class="card panel-card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Recent OTA Booking Imports</h5>
                <a href="channel_pull_bookings.php" class="btn btn-sm btn-outline-primary">View Queue</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Booking</th>
                            <th>Guest</th>
                            <th>Stay</th>
                            <th>Status</th>
                            <th class="text-end">Action</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$recentImports): ?>
                            <tr><td colspan="5" class="text-center text-muted py-4">No OTA imports yet.</td></tr>
                        <?php else: ?>
                            <?php foreach ($recentImports as $row): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo h($row['external_booking_id']); ?></strong>
                                        <div class="small text-muted"><?php echo h($row['connection_name'] ?: $row['provider']); ?></div>
                                    </td>
                                    <td><?php echo h($row['guest_name'] ?: 'OTA Guest'); ?></td>
                                    <td><?php echo h($row['check_in']); ?> → <?php echo h($row['check_out']); ?></td>
                                    <td>
                                        <span class="badge <?php echo h(cmd_badge_class($row['import_status'])); ?>">
                                            <?php echo h(ucwords(str_replace('_', ' ', $row['import_status']))); ?>
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <?php if (empty($row['order_id'])): ?>
                                            <a href="channel_create_reservation.php?import_id=<?php echo (int)$row['id']; ?>" class="btn btn-sm btn-outline-success">
                                                Create
                                            </a>
                                        <?php else: ?>
                                            <a href="/rooms/modules/reservations/reservation_view.php?order_id=<?php echo (int)$row['order_id']; ?>" class="btn btn-sm btn-outline-primary">
                                                View
                                            </a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-6">
        <div class="card panel-card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Recent Sync Activity</h5>
                <a href="channel_sync_log.php" class="btn btn-sm btn-outline-secondary">All Logs</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Time</th>
                            <th>Connection</th>
                            <th>Type</th>
                            <th>Status</th>
                            <th class="text-end">Retry</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$recentLogs): ?>
                            <tr><td colspan="5" class="text-center text-muted py-4">No sync activity yet.</td></tr>
                        <?php else: ?>
                            <?php foreach ($recentLogs as $row): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo h($row['started_at']); ?></strong>
                                        <div class="small text-muted"><?php echo h($row['provider']); ?></div>
                                    </td>
                                    <td><?php echo h($row['connection_name'] ?: 'No connection'); ?></td>
                                    <td><?php echo h(ucwords(str_replace('_', ' ', $row['sync_type']))); ?></td>
                                    <td>
                                        <span class="badge <?php echo h(cmd_badge_class($row['status'])); ?>">
                                            <?php echo h(ucwords($row['status'])); ?>
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <?php if (in_array(strtolower((string)$row['status']), ['failed','error','rejected'], true)): ?>
                                            <a href="channel_retry.php?log_id=<?php echo (int)$row['id']; ?>" class="btn btn-sm btn-outline-warning">
                                                Retry
                                            </a>
                                        <?php else: ?>
                                            <a href="channel_sync_log.php?view_id=<?php echo (int)$row['id']; ?>" class="btn btn-sm btn-outline-secondary">
                                                View
                                            </a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.webhook-box{
    border:1px solid rgba(15,23,42,.10);
    border-radius:16px;
    padding:12px;
    background:#f8fafc;
}
</style>

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