<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();
$nightsBridgeConnector = __DIR__ . '/providers/nightsbridge_connector.php';
if (file_exists($nightsBridgeConnector)) {
    require_once $nightsBridgeConnector;
}
$pageTitle = 'Pull Channel Bookings';

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('cpb_table_exists')) {
    function cpb_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('cpb_column_exists')) {
    function cpb_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('cpb_flash')) {
    function cpb_flash(string $type, string $message): void {
        $_SESSION['channel_pull_bookings_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('cpb_get_flash')) {
    function cpb_get_flash(): array {
        $items = $_SESSION['channel_pull_bookings_flash'] ?? [];
        unset($_SESSION['channel_pull_bookings_flash']);
        return $items;
    }
}
if (!function_exists('cpb_log_sync')) {
    function cpb_log_sync(PDO $pdo, ?int $connectionId, string $provider, string $status, array $requestPayload, array $responsePayload, string $message): int {
        $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, 'booking_pull', 'pull', :status, :request_payload, :response_payload, :message, NOW(), NOW())
        ");
        $stmt->execute([
            ':connection_id' => $connectionId ?: null,
            ':provider' => $provider,
            ':status' => $status,
            ':request_payload' => json_encode($requestPayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
            ':response_payload' => json_encode($responsePayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
            ':message' => $message,
        ]);

        return (int)$pdo->lastInsertId();
    }
}
if (!function_exists('cpb_provider_stub_pull')) {
    function cpb_provider_stub_pull(array $connection, string $dateFrom, string $dateTo, bool $liveMode = false): array {
        /*
         * SAFE STUB:
         * This does not call Booking.com / Expedia / Airbnb / NightsBridge yet.
         * It returns sample data only when preview mode is used.
         */
        if (!$liveMode) {
            $provider = $connection['provider'] ?? 'custom';
            $externalPropertyId = $connection['external_property_id'] ?? 'PROPERTY';

            return [
                'ok' => true,
                'mode' => 'preview_stub',
                'provider' => $provider,
                'message' => 'Preview stub returned sample bookings. No external provider was called.',
                'bookings' => [
                    [
                        'external_booking_id' => strtoupper($provider) . '-' . date('Ymd') . '-001',
                        'external_property_id' => $externalPropertyId,
                        'guest_name' => 'Sample OTA Guest',
                        'guest_email' => 'guest@example.com',
                        'guest_phone' => '+263771234567',
                        'check_in' => date('Y-m-d', strtotime('+7 days')),
                        'check_out' => date('Y-m-d', strtotime('+9 days')),
                        'room_type_external_id' => 'EXT-ROOM-001',
                        'rate_external_id' => 'EXT-RATE-001',
                        'rooms' => 1,
                        'adults' => 2,
                        'children' => 0,
                        'total_amount' => 300.00,
                        'currency' => 'USD',
                        'status' => 'confirmed',
                        'special_requests' => 'Late arrival if possible.',
                        'raw_payload' => [
                            'source' => 'preview_stub',
                            'date_from' => $dateFrom,
                            'date_to' => $dateTo,
                        ],
                    ],
                ],
            ];
        }
if (($connection['provider'] ?? '') === 'nightsbridge' && function_exists('nb_pull_bookings')) {
    return nb_pull_bookings($connection, $dateFrom, $dateTo);
}
        return [
            'ok' => false,
            'mode' => 'stub',
            'provider' => $connection['provider'] ?? 'unknown',
            'message' => 'Live booking pull is blocked because provider-specific API connector is not configured yet.',
            'bookings' => [],
        ];
    }
}
if (!function_exists('cpb_import_booking')) {
    function cpb_import_booking(PDO $pdo, array $connection, array $booking, bool $autoCreateReservation = false): array {
        $provider = (string)($connection['provider'] ?? 'custom');
        $connectionId = (int)($connection['id'] ?? 0);
        $externalBookingId = trim((string)($booking['external_booking_id'] ?? ''));

        if ($externalBookingId === '') {
            return ['ok' => false, 'status' => 'failed', 'message' => 'Missing external booking ID.'];
        }

        $stmt = $pdo->prepare("
            SELECT id, import_status, order_id
            FROM channel_booking_imports
            WHERE provider = :provider
              AND external_booking_id = :external_booking_id
            LIMIT 1
        ");
        $stmt->execute([
            ':provider' => $provider,
            ':external_booking_id' => $externalBookingId,
        ]);
        $existing = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            return [
                'ok' => true,
                'status' => 'duplicate',
                'message' => 'Booking already exists in import queue.',
                'import_id' => (int)$existing['id'],
                'order_id' => (int)($existing['order_id'] ?? 0),
            ];
        }

        $importStatus = $autoCreateReservation ? 'ready_for_reservation' : 'pending';

        $stmt = $pdo->prepare("
            INSERT INTO channel_booking_imports
            (
                connection_id, provider, external_booking_id, order_id,
                guest_name, check_in, check_out, total_amount, currency,
                import_status, raw_payload, imported_at
            )
            VALUES
            (
                :connection_id, :provider, :external_booking_id, NULL,
                :guest_name, :check_in, :check_out, :total_amount, :currency,
                :import_status, :raw_payload, NOW()
            )
        ");
        $stmt->execute([
            ':connection_id' => $connectionId,
            ':provider' => $provider,
            ':external_booking_id' => $externalBookingId,
            ':guest_name' => trim((string)($booking['guest_name'] ?? 'OTA Guest')),
            ':check_in' => !empty($booking['check_in']) ? $booking['check_in'] : null,
            ':check_out' => !empty($booking['check_out']) ? $booking['check_out'] : null,
            ':total_amount' => (float)($booking['total_amount'] ?? 0),
            ':currency' => trim((string)($booking['currency'] ?? 'USD')),
            ':import_status' => $importStatus,
            ':raw_payload' => json_encode($booking, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
        ]);

        return [
            'ok' => true,
            'status' => 'imported',
            'message' => 'Booking added to import queue.',
            'import_id' => (int)$pdo->lastInsertId(),
            'order_id' => 0,
        ];
    }
}

$errors = [];

try {
    $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
    ");

    $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
    ");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare channel booking import tables: ' . $e->getMessage();
}

foreach (['channel_connections', 'channel_booking_imports'] as $table) {
    if (!cpb_table_exists($pdo, $table)) {
        $errors[] = 'Required table missing: ' . $table;
    }
}

$connections = [];
try {
    $connections = $pdo->query("
        SELECT
            cc.*,
            p.name AS property_name,
            p.code AS property_code
        FROM channel_connections cc
        LEFT JOIN properties p ON p.id = cc.property_id
        WHERE cc.is_active = 1
          AND cc.pull_bookings = 1
        ORDER BY cc.provider ASC, cc.connection_name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $connections = [];
}

$connectionId = (int)($_GET['connection_id'] ?? $_POST['connection_id'] ?? 0);
if ($connectionId <= 0 && $connections) {
    $connectionId = (int)$connections[0]['id'];
}

$dateFrom = trim((string)($_GET['date_from'] ?? $_POST['date_from'] ?? date('Y-m-d', strtotime('-7 days'))));
$dateTo = trim((string)($_GET['date_to'] ?? $_POST['date_to'] ?? date('Y-m-d', strtotime('+30 days'))));
$autoCreateReservation = (int)($_GET['auto_create_reservation'] ?? $_POST['auto_create_reservation'] ?? 0);

if (strtotime($dateFrom) === false) $dateFrom = date('Y-m-d', strtotime('-7 days'));
if (strtotime($dateTo) === false) $dateTo = date('Y-m-d', strtotime('+30 days'));
if (strtotime($dateFrom) > strtotime($dateTo)) {
    $tmp = $dateFrom;
    $dateFrom = $dateTo;
    $dateTo = $tmp;
}

$selectedConnection = null;
foreach ($connections as $conn) {
    if ((int)$conn['id'] === $connectionId) {
        $selectedConnection = $conn;
        break;
    }
}

$previewResponse = null;
$previewBookings = [];

if (!$errors && $selectedConnection && isset($_GET['preview'])) {
    $previewResponse = cpb_provider_stub_pull($selectedConnection, $dateFrom, $dateTo, false);
    $previewBookings = $previewResponse['bookings'] ?? [];
}

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

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

        if (!$selectedConnection) {
            throw new RuntimeException('Please select a valid channel connection.');
        }

        if ($action === 'preview_pull') {
            $response = cpb_provider_stub_pull($selectedConnection, $dateFrom, $dateTo, false);

            $requestPayload = [
                'connection_id' => $connectionId,
                'provider' => $selectedConnection['provider'],
                'external_property_id' => $selectedConnection['external_property_id'],
                'date_from' => $dateFrom,
                'date_to' => $dateTo,
                'mode' => 'preview',
            ];

            $logId = cpb_log_sync(
                $pdo,
                $connectionId,
                $selectedConnection['provider'],
                !empty($response['ok']) ? 'preview' : 'failed',
                $requestPayload,
                $response,
                $response['message'] ?? 'Booking preview pull completed.'
            );

            cpb_flash('success', 'Preview pull completed and logged. Log ID: ' . $logId);
            header('Location: channel_pull_bookings.php?connection_id=' . $connectionId . '&date_from=' . urlencode($dateFrom) . '&date_to=' . urlencode($dateTo) . '&preview=1');
            exit;
        }

        if ($action === 'pull_import') {
            $response = cpb_provider_stub_pull($selectedConnection, $dateFrom, $dateTo, true);
            $bookings = $response['bookings'] ?? [];

            $imported = 0;
            $duplicates = 0;
            $failed = 0;
            $results = [];

            foreach ($bookings as $booking) {
                $result = cpb_import_booking($pdo, $selectedConnection, $booking, $autoCreateReservation === 1);
                $results[] = $result;

                if (($result['status'] ?? '') === 'imported') $imported++;
                elseif (($result['status'] ?? '') === 'duplicate') $duplicates++;
                else $failed++;
            }

            $requestPayload = [
                'connection_id' => $connectionId,
                'provider' => $selectedConnection['provider'],
                'external_property_id' => $selectedConnection['external_property_id'],
                'date_from' => $dateFrom,
                'date_to' => $dateTo,
                'mode' => 'live_stub',
                'auto_create_reservation' => $autoCreateReservation,
            ];

            $responsePayload = [
                'provider_response' => $response,
                'import_results' => $results,
                'imported' => $imported,
                'duplicates' => $duplicates,
                'failed' => $failed,
            ];

            $status = !empty($response['ok']) ? 'success' : 'failed';

            $logId = cpb_log_sync(
                $pdo,
                $connectionId,
                $selectedConnection['provider'],
                $status,
                $requestPayload,
                $responsePayload,
                $response['message'] ?? 'Booking pull/import completed.'
            );

            if (!empty($response['ok'])) {
                cpb_flash('success', "Booking pull completed. Imported: {$imported}, duplicates: {$duplicates}, failed: {$failed}. Log ID: {$logId}");
            } else {
                cpb_flash('warning', 'Live booking pull is currently blocked/stubbed. Log ID: ' . $logId . '. ' . ($response['message'] ?? ''));
            }

            header('Location: channel_pull_bookings.php?connection_id=' . $connectionId . '&date_from=' . urlencode($dateFrom) . '&date_to=' . urlencode($dateTo));
            exit;
        }

        if ($action === 'mark_import_reviewed') {
            $importId = (int)($_POST['import_id'] ?? 0);
            if ($importId <= 0) throw new RuntimeException('Invalid import selected.');

            $stmt = $pdo->prepare("
                UPDATE channel_booking_imports
                SET import_status = 'reviewed'
                WHERE id = :id
                  AND order_id IS NULL
            ");
            $stmt->execute([':id' => $importId]);

            cpb_flash('success', 'Import marked as reviewed.');
            header('Location: channel_pull_bookings.php?connection_id=' . $connectionId);
            exit;
        }

        if ($action === 'delete_import') {
            $importId = (int)($_POST['import_id'] ?? 0);
            if ($importId <= 0) throw new RuntimeException('Invalid import selected.');

            $stmt = $pdo->prepare("
                DELETE FROM channel_booking_imports
                WHERE id = :id
                  AND order_id IS NULL
            ");
            $stmt->execute([':id' => $importId]);

            cpb_flash('success', 'Import queue item deleted.');
            header('Location: channel_pull_bookings.php?connection_id=' . $connectionId);
            exit;
        }

    } catch (Throwable $e) {
        cpb_flash('danger', $e->getMessage());
        header('Location: channel_pull_bookings.php?connection_id=' . $connectionId);
        exit;
    }
}

$imports = [];
$importSummary = [
    'total' => 0,
    'pending' => 0,
    'ready_for_reservation' => 0,
    'imported' => 0,
    'reviewed' => 0,
    'duplicate' => 0,
];

try {
    $where = "1=1";
    $params = [];

    if ($connectionId > 0) {
        $where .= " AND cbi.connection_id = :connection_id";
        $params[':connection_id'] = $connectionId;
    }

    $stmt = $pdo->prepare("
        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
        WHERE $where
        ORDER BY cbi.created_at DESC, cbi.id DESC
        LIMIT 300
    ");
    $stmt->execute($params);
    $imports = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($imports as $row) {
        $importSummary['total']++;
        $status = (string)$row['import_status'];
        if (isset($importSummary[$status])) $importSummary[$status]++;
    }
} catch (Throwable $e) {
    $errors[] = 'Could not load booking import queue: ' . $e->getMessage();
}

$viewImportId = (int)($_GET['view_import_id'] ?? 0);
$viewImport = null;
if ($viewImportId > 0) {
    try {
        $stmt = $pdo->prepare("
            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
            WHERE cbi.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $viewImportId]);
        $viewImport = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    } catch (Throwable $e) {}
}

$flashes = cpb_get_flash();

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

function cpb_status_badge(string $status): string {
    if (in_array($status, ['imported','created','confirmed'], true)) return 'text-bg-success';
    if (in_array($status, ['pending','ready_for_reservation'], true)) return 'text-bg-warning';
    if (in_array($status, ['failed','cancelled','rejected'], true)) return 'text-bg-danger';
    if ($status === 'reviewed') return 'text-bg-info';
    return 'text-bg-secondary';
}

function cpb_pretty_json(?string $value): string {
    $value = (string)$value;
    if (trim($value) === '') return '';
    $decoded = json_decode($value, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        return json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }
    return $value;
}

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-download"></i> Channel Manager</div>
            <div class="hero-title mt-2">Pull Bookings</div>
            <div class="hero-subtitle mt-2">
                Safely pull OTA bookings into an import queue before creating PMS reservations.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="channel_mapping.php?connection_id=<?php echo (int)$connectionId; ?>" 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>Safe mode:</strong> Live provider booking pull is currently blocked by a stub until provider-specific API connector/certification details are configured.
</div>

<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-4">
                <label class="form-label">Channel Connection</label>
                <select name="connection_id" class="form-select">
                    <?php foreach ($connections as $connection): ?>
                        <?php $label = $providerLabels[$connection['provider']] ?? $connection['provider']; ?>
                        <option value="<?php echo (int)$connection['id']; ?>" <?php echo $connectionId === (int)$connection['id'] ? 'selected' : ''; ?>>
                            <?php echo h($connection['connection_name']); ?> — <?php echo h($label); ?> — <?php echo h($connection['property_name'] ?: 'Property'); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php if (!$connections): ?>
                    <div class="small text-muted mt-1">No active booking-pull connections found.</div>
                <?php endif; ?>
            </div>

            <div class="col-md-2">
                <label class="form-label">Date From</label>
                <input type="date" name="date_from" class="form-control" value="<?php echo h($dateFrom); ?>">
            </div>

            <div class="col-md-2">
                <label class="form-label">Date To</label>
                <input type="date" name="date_to" class="form-control" value="<?php echo h($dateTo); ?>">
            </div>

            <div class="col-md-2">
                <label class="form-label">Auto Create</label>
                <select name="auto_create_reservation" class="form-select">
                    <option value="0" <?php echo $autoCreateReservation === 0 ? 'selected' : ''; ?>>Queue only</option>
                    <option value="1" <?php echo $autoCreateReservation === 1 ? 'selected' : ''; ?>>Ready status</option>
                </select>
            </div>

            <div class="col-md-2 d-grid">
                <button class="btn btn-primary">
                    <i class="bi bi-funnel me-2"></i>Filter
                </button>
            </div>
        </form>
    </div>
</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-inbox"></i></div>
            <div><div class="metric-label">Queue Total</div><div class="metric-value"><?php echo (int)$importSummary['total']; ?></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</div><div class="metric-value"><?php echo (int)$importSummary['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-card-checklist"></i></div>
            <div><div class="metric-label">Ready</div><div class="metric-value"><?php echo (int)$importSummary['ready_for_reservation']; ?></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-check-circle"></i></div>
            <div><div class="metric-label">Created</div><div class="metric-value"><?php echo (int)$importSummary['imported']; ?></div></div>
        </div>
    </div>
</div>

<?php if ($viewImport): ?>
<div class="card panel-card mb-4 border-primary">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Import Detail #<?php echo (int)$viewImport['id']; ?></h5>
        <a href="channel_pull_bookings.php?connection_id=<?php echo (int)$connectionId; ?>" class="btn btn-sm btn-outline-secondary">Close</a>
    </div>
    <div class="card-body">
        <div class="row g-3 mb-3">
            <div class="col-md-3">
                <div class="detail-label">External Booking</div>
                <div class="detail-value"><?php echo h($viewImport['external_booking_id']); ?></div>
            </div>
            <div class="col-md-3">
                <div class="detail-label">Guest</div>
                <div class="detail-value"><?php echo h($viewImport['guest_name']); ?></div>
            </div>
            <div class="col-md-3">
                <div class="detail-label">Stay</div>
                <div class="detail-value"><?php echo h($viewImport['check_in']); ?> → <?php echo h($viewImport['check_out']); ?></div>
            </div>
            <div class="col-md-3">
                <div class="detail-label">Status</div>
                <span class="badge <?php echo h(cpb_status_badge($viewImport['import_status'])); ?>">
                    <?php echo h(ucwords(str_replace('_', ' ', $viewImport['import_status']))); ?>
                </span>
            </div>
        </div>

        <h6 class="fw-bold">Raw Payload</h6>
        <pre class="payload-box"><?php echo h(cpb_pretty_json($viewImport['raw_payload'])); ?></pre>
    </div>
</div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-xl-9">
        <div class="card panel-card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Pull / Preview Bookings</h5>
                <div>
                    <form method="post" class="d-inline">
                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                        <input type="hidden" name="action" value="preview_pull">
                        <input type="hidden" name="connection_id" value="<?php echo (int)$connectionId; ?>">
                        <input type="hidden" name="date_from" value="<?php echo h($dateFrom); ?>">
                        <input type="hidden" name="date_to" value="<?php echo h($dateTo); ?>">
                        <input type="hidden" name="auto_create_reservation" value="<?php echo (int)$autoCreateReservation; ?>">
                        <button class="btn btn-sm btn-outline-primary" <?php echo !$selectedConnection ? 'disabled' : ''; ?>>
                            <i class="bi bi-eye me-2"></i>Preview Pull
                        </button>
                    </form>

                    <form method="post" class="d-inline" onsubmit="return confirm('Attempt live booking pull? This is currently stubbed and will not call OTA until provider connector is configured.');">
                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                        <input type="hidden" name="action" value="pull_import">
                        <input type="hidden" name="connection_id" value="<?php echo (int)$connectionId; ?>">
                        <input type="hidden" name="date_from" value="<?php echo h($dateFrom); ?>">
                        <input type="hidden" name="date_to" value="<?php echo h($dateTo); ?>">
                        <input type="hidden" name="auto_create_reservation" value="<?php echo (int)$autoCreateReservation; ?>">
                        <button class="btn btn-sm btn-danger" <?php echo !$selectedConnection ? 'disabled' : ''; ?>>
                            <i class="bi bi-cloud-download me-2"></i>Pull Live
                        </button>
                    </form>
                </div>
            </div>

            <?php if ($previewBookings): ?>
                <div class="card-body p-0">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>External ID</th>
                            <th>Guest</th>
                            <th>Stay</th>
                            <th class="text-end">Rooms</th>
                            <th class="text-end">Amount</th>
                            <th>Status</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($previewBookings as $b): ?>
                            <tr>
                                <td><strong><?php echo h($b['external_booking_id'] ?? ''); ?></strong></td>
                                <td>
                                    <?php echo h($b['guest_name'] ?? 'OTA Guest'); ?>
                                    <div class="small text-muted"><?php echo h($b['guest_email'] ?? ''); ?></div>
                                </td>
                                <td><?php echo h($b['check_in'] ?? ''); ?> → <?php echo h($b['check_out'] ?? ''); ?></td>
                                <td class="text-end"><?php echo (int)($b['rooms'] ?? 1); ?></td>
                                <td class="text-end fw-bold"><?php echo h($b['currency'] ?? 'USD'); ?> <?php echo money_fmt($b['total_amount'] ?? 0); ?></td>
                                <td><span class="badge text-bg-info"><?php echo h(ucwords($b['status'] ?? 'preview')); ?></span></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="card-body">
                    <div class="text-muted">Click <strong>Preview Pull</strong> to view sample/stub incoming bookings.</div>
                </div>
            <?php endif; ?>
        </div>

        <div class="card panel-card">
            <div class="card-header">
                <h5 class="mb-0">Booking Import Queue</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Imported</th>
                            <th>External Booking</th>
                            <th>Guest</th>
                            <th>Stay</th>
                            <th class="text-end">Amount</th>
                            <th>Status</th>
                            <th>PMS Order</th>
                            <th class="text-end">Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$imports): ?>
                            <tr><td colspan="8" class="text-center text-muted py-4">No booking imports yet.</td></tr>
                        <?php else: ?>
                            <?php foreach ($imports as $row): ?>
                                <tr>
                                    <td>
                                        <strong><?php echo h($row['created_at']); ?></strong>
                                        <div class="small text-muted"><?php echo h($row['connection_name'] ?: $row['provider']); ?></div>
                                    </td>
                                    <td><strong><?php echo h($row['external_booking_id']); ?></strong></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 class="text-end fw-bold"><?php echo h($row['currency'] ?: 'USD'); ?> <?php echo money_fmt($row['total_amount']); ?></td>
                                    <td>
                                        <span class="badge <?php echo h(cpb_status_badge($row['import_status'])); ?>">
                                            <?php echo h(ucwords(str_replace('_', ' ', $row['import_status']))); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if (!empty($row['order_id'])): ?>
                                            <a href="/rooms/modules/reservations/reservation_view.php?order_id=<?php echo (int)$row['order_id']; ?>">
                                                #<?php echo (int)$row['order_id']; ?>
                                            </a>
                                        <?php else: ?>
                                            <span class="text-muted">Not created</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-group btn-group-sm">
                                            <a class="btn btn-outline-primary" href="channel_pull_bookings.php?connection_id=<?php echo (int)$connectionId; ?>&view_import_id=<?php echo (int)$row['id']; ?>">
                                                <i class="bi bi-eye"></i>
                                            </a>

                                            <?php if (empty($row['order_id'])): ?>
                                                <a class="btn btn-outline-success" href="channel_create_reservation.php?import_id=<?php echo (int)$row['id']; ?>">
                                                    <i class="bi bi-plus-circle"></i>
                                                </a>

                                                <form method="post" class="d-inline">
                                                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                    <input type="hidden" name="action" value="mark_import_reviewed">
                                                    <input type="hidden" name="import_id" value="<?php echo (int)$row['id']; ?>">
                                                    <input type="hidden" name="connection_id" value="<?php echo (int)$connectionId; ?>">
                                                    <button class="btn btn-outline-info"><i class="bi bi-check2-square"></i></button>
                                                </form>

                                                <form method="post" class="d-inline" onsubmit="return confirm('Delete this import queue item?');">
                                                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                    <input type="hidden" name="action" value="delete_import">
                                                    <input type="hidden" name="import_id" value="<?php echo (int)$row['id']; ?>">
                                                    <input type="hidden" name="connection_id" value="<?php echo (int)$connectionId; ?>">
                                                    <button class="btn btn-outline-danger"><i class="bi bi-trash"></i></button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3">
        <div class="card panel-card mb-4">
            <div class="card-header"><h5 class="mb-0">Import Rules</h5></div>
            <div class="card-body small">
                <p><strong>Duplicate prevention:</strong> provider + external booking ID is unique.</p>
                <p><strong>Safe queue:</strong> pulled bookings are stored before becoming PMS reservations.</p>
                <p class="mb-0"><strong>Next:</strong> build channel_create_reservation.php to convert queue items into reservations.</p>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Provider Status</h5></div>
            <div class="card-body small">
                <p class="text-muted">Current pull is a safe stub. Real connectors need provider API approval/certification and exact payload specs.</p>
                <ul class="mb-0">
                    <li>NightsBridge connector</li>
                    <li>Booking.com XML/API connector</li>
                    <li>Expedia connector</li>
                    <li>Airbnb approved partner connector</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<style>
.detail-label{font-size:.75rem;text-transform:uppercase;letter-spacing:.06em;color:#64748b;font-weight:800}
.detail-value{font-weight:800;color:#111827}
.payload-box{background:#0f172a;color:#e5e7eb;border-radius:16px;padding:14px;max-height:520px;overflow:auto;font-size:12px}
</style>

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