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

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

if (!function_exists('cpa_table_exists')) {
    function cpa_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('cpa_column_exists')) {
    function cpa_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('cpa_flash')) {
    function cpa_flash(string $type, string $message): void {
        $_SESSION['channel_push_availability_flash'][] = ['type' => $type, 'message' => $message];
    }
}

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

if (!function_exists('cpa_date_range')) {
    function cpa_date_range(string $from, string $to): array {
        $dates = [];
        $start = new DateTime($from);
        $end = new DateTime($to);
        $endExclusive = (clone $end)->modify('+1 day');

        while ($start < $endExclusive) {
            $dates[] = $start->format('Y-m-d');
            $start->modify('+1 day');
        }

        return $dates;
    }
}

if (!function_exists('cpa_log_sync')) {
    function cpa_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, 'availability_push', 'push', :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('cpa_provider_stub_push')) {
    function cpa_provider_stub_push(array $connection, array $payload, bool $liveMode = false): array {
        /*
         * SAFE STUB:
         * This does not call Booking.com / Expedia / Airbnb / NightsBridge yet.
         * Real provider API connectors are added in the next phase after certification details.
         */
       
        if (!$liveMode) {
            return [
                'ok' => true,
                'mode' => 'preview',
                'provider' => $connection['provider'] ?? 'unknown',
                'message' => 'Preview only. Nothing was sent to the external channel.',
                'records_received' => count($payload['availability'] ?? []),
            ];
        }
if (($connection['provider'] ?? '') === 'booking_com' && function_exists('bc_push_availability')) {
    return bc_push_availability($connection, $payload['availability'] ?? []);
}  
if (($connection['provider'] ?? '') === 'nightsbridge' && function_exists('nb_push_availability')) {
    return nb_push_availability($connection, $payload['availability'] ?? []);
}

        return [
            'ok' => false,
            'mode' => 'stub',
            'provider' => $connection['provider'] ?? 'unknown',
            'message' => 'Live push is blocked because provider-specific API connector is not configured yet.',
            'records_received' => count($payload['availability'] ?? []),
        ];
    }
}

$errors = [];

try {
    $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 sync log table: ' . $e->getMessage();
}

$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.push_availability = 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')));
$dateTo = trim((string)($_GET['date_to'] ?? $_POST['date_to'] ?? date('Y-m-d', strtotime('+30 days'))));
$includeUnmapped = (int)($_GET['include_unmapped'] ?? $_POST['include_unmapped'] ?? 0);

if (strtotime($dateFrom) === false) $dateFrom = date('Y-m-d');
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;
    }
}

$hasOrderStatus = cpa_table_exists($pdo, 'orders') && cpa_column_exists($pdo, 'orders', 'status');
$hasOrderCancelled = cpa_table_exists($pdo, 'orders') && cpa_column_exists($pdo, 'orders', 'cancelled');
$hasRoomingCancelled = cpa_table_exists($pdo, 'order_rooming') && cpa_column_exists($pdo, 'order_rooming', 'cancelled');
$hasRoomingProperty = cpa_table_exists($pdo, 'order_rooming') && cpa_column_exists($pdo, 'order_rooming', 'property_id');
$hasRoomActive = cpa_table_exists($pdo, 'rooms') && cpa_column_exists($pdo, 'rooms', 'is_active');
$hasRoomStatus = cpa_table_exists($pdo, 'rooms') && cpa_column_exists($pdo, 'rooms', 'status');

if (!cpa_table_exists($pdo, 'rooms')) $errors[] = 'Required table missing: rooms';
if (!cpa_table_exists($pdo, 'room_types')) $errors[] = 'Required table missing: room_types';
if (!cpa_table_exists($pdo, 'order_rooming')) $errors[] = 'Required table missing: order_rooming';
if (!cpa_table_exists($pdo, 'orders')) $errors[] = 'Required table missing: orders';
if (!cpa_table_exists($pdo, 'channel_room_mapping')) $errors[] = 'Required table missing: channel_room_mapping';
if (!cpa_table_exists($pdo, 'channel_connections')) $errors[] = 'Required table missing: channel_connections';

$availabilityRows = [];
$payload = [
    'connection_id' => $connectionId,
    'provider' => $selectedConnection['provider'] ?? null,
    'external_property_id' => $selectedConnection['external_property_id'] ?? null,
    'date_from' => $dateFrom,
    'date_to' => $dateTo,
    'availability' => [],
];

if (!$errors && $selectedConnection) {
    try {
        $dates = cpa_date_range($dateFrom, $dateTo);
        $propertyId = (int)($selectedConnection['property_id'] ?? 0);

        $stmt = $pdo->prepare("
            SELECT
                crm.*,
                rt.title AS room_type,
                COALESCE(crm.property_id, :property_id) AS effective_property_id
            FROM channel_room_mapping crm
            INNER JOIN room_types rt ON rt.id = crm.room_type_id
            WHERE crm.connection_id = :connection_id
              AND crm.is_active = 1
            ORDER BY rt.title ASC, crm.external_room_name ASC
        ");
        $stmt->execute([
            ':connection_id' => $connectionId,
            ':property_id' => $propertyId,
        ]);
        $mappings = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($includeUnmapped === 1) {
            $stmt = $pdo->prepare("
                SELECT
                    0 AS id,
                    :connection_id AS connection_id,
                    :property_id AS property_id,
                    rt.id AS room_type_id,
                    '' AS external_room_id,
                    '' AS external_room_name,
                    rt.title AS room_type,
                    :property_id AS effective_property_id
                FROM room_types rt
                WHERE NOT EXISTS (
                    SELECT 1
                    FROM channel_room_mapping crm
                    WHERE crm.connection_id = :connection_id2
                      AND crm.room_type_id = rt.id
                      AND crm.is_active = 1
                )
                ORDER BY rt.title ASC
            ");
            $stmt->execute([
                ':connection_id' => $connectionId,
                ':connection_id2' => $connectionId,
                ':property_id' => $propertyId,
            ]);
            $unmapped = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $mappings = array_merge($mappings, $unmapped);
        }

        $orderActiveSql = '';
        if ($hasOrderCancelled) {
            $orderActiveSql .= " AND COALESCE(o.cancelled, 0) = 0 ";
        }
        if ($hasOrderStatus) {
            $orderActiveSql .= " AND LOWER(COALESCE(o.status, '')) NOT IN ('cancelled','canceled','void','deleted') ";
        }

        $roomingActiveSql = '';
        if ($hasRoomingCancelled) {
            $roomingActiveSql .= " AND COALESCE(orm.cancelled, 0) = 0 ";
        }

        foreach ($mappings as $mapping) {
            $roomTypeId = (int)$mapping['room_type_id'];
            $effectivePropertyId = (int)($mapping['effective_property_id'] ?: $propertyId);

            $roomWhere = "r.room_type_id = :room_type_id";
            $roomParams = [':room_type_id' => $roomTypeId];

            if ($effectivePropertyId > 0) {
                $roomWhere .= " AND COALESCE(r.property_id, rt.property_id) = :property_id";
                $roomParams[':property_id'] = $effectivePropertyId;
            }

            if ($hasRoomActive) {
                $roomWhere .= " AND COALESCE(r.is_active, 1) = 1";
            }
            if ($hasRoomStatus) {
                $roomWhere .= " AND (r.status IS NULL OR r.status NOT IN ('inactive','out_of_order','blocked'))";
            }

            $stmtCapacity = $pdo->prepare("
                SELECT COUNT(*)
                FROM rooms r
                LEFT JOIN room_types rt ON rt.id = r.room_type_id
                WHERE $roomWhere
            ");
            $stmtCapacity->execute($roomParams);
            $capacity = (int)$stmtCapacity->fetchColumn();

            foreach ($dates as $day) {
                $daySql = $pdo->quote($day);

                $occWhere = "
                    orm.room_type_id = :room_type_id
                    AND orm.check_in <= $daySql
                    AND orm.check_out > $daySql
                    $roomingActiveSql
                    $orderActiveSql
                ";

                $occParams = [':room_type_id' => $roomTypeId];

                if ($effectivePropertyId > 0) {
                    if ($hasRoomingProperty) {
                        $occWhere .= " AND COALESCE(orm.property_id, o.property_id, r.property_id, rt.property_id) = :property_id";
                    } else {
                        $occWhere .= " AND COALESCE(o.property_id, r.property_id, rt.property_id) = :property_id";
                    }
                    $occParams[':property_id'] = $effectivePropertyId;
                }

                $stmtOcc = $pdo->prepare("
                    SELECT COUNT(DISTINCT orm.id)
                    FROM order_rooming orm
                    LEFT JOIN orders o ON o.id = orm.order_id
                    LEFT JOIN rooms r ON r.id = orm.room_id
                    LEFT JOIN room_types rt ON rt.id = orm.room_type_id
                    WHERE $occWhere
                ");
                $stmtOcc->execute($occParams);
                $booked = (int)$stmtOcc->fetchColumn();

                $available = max(0, $capacity - $booked);

                $row = [
                    'date' => $day,
                    'room_type_id' => $roomTypeId,
                    'room_type' => $mapping['room_type'],
                    'external_room_id' => (string)($mapping['external_room_id'] ?? ''),
                    'external_room_name' => (string)($mapping['external_room_name'] ?? ''),
                    'capacity' => $capacity,
                    'booked' => $booked,
                    'available' => $available,
                    'mapped' => trim((string)($mapping['external_room_id'] ?? '')) !== '',
                ];

                $availabilityRows[] = $row;

                if ($row['mapped']) {
                    $payload['availability'][] = [
                        'date' => $day,
                        'external_room_id' => $row['external_room_id'],
                        'available' => $available,
                        'closed' => $available <= 0 ? 1 : 0,
                    ];
                }
            }
        }

    } catch (Throwable $e) {
        $errors[] = 'Could not calculate availability: ' . $e->getMessage();
    }
} elseif (!$selectedConnection && !$connections) {
    $errors[] = 'No active channel connection with availability push enabled. Create one in Channel Settings.';
}

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

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

        if ($action === 'preview_push') {
            $response = cpa_provider_stub_push($selectedConnection ?: [], $payload, false);
            $logId = cpa_log_sync(
                $pdo,
                $connectionId,
                $selectedConnection['provider'] ?? 'unknown',
                'preview',
                $payload,
                $response,
                'Availability preview generated. Nothing sent to channel.'
            );

            cpa_flash('success', 'Preview payload generated and logged. Log ID: ' . $logId);
            header('Location: channel_push_availability.php?connection_id=' . $connectionId . '&date_from=' . urlencode($dateFrom) . '&date_to=' . urlencode($dateTo));
            exit;
        }

        if ($action === 'push_live') {
            $response = cpa_provider_stub_push($selectedConnection ?: [], $payload, true);
            $status = !empty($response['ok']) ? 'success' : 'failed';
            $logId = cpa_log_sync(
                $pdo,
                $connectionId,
                $selectedConnection['provider'] ?? 'unknown',
                $status,
                $payload,
                $response,
                $response['message'] ?? 'Availability push attempted.'
            );

            if (!empty($response['ok'])) {
                cpa_flash('success', 'Availability pushed successfully. Log ID: ' . $logId);
            } else {
                cpa_flash('warning', 'Live push blocked/stubbed. Log ID: ' . $logId . '. ' . ($response['message'] ?? ''));
            }

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

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

$summary = [
    'rows' => count($availabilityRows),
    'mapped_payload_rows' => count($payload['availability']),
    'sold_out_days' => 0,
    'low_inventory_days' => 0,
    'unmapped_rows' => 0,
];

foreach ($availabilityRows as $row) {
    if (!$row['mapped']) $summary['unmapped_rows']++;
    if ((int)$row['available'] <= 0) $summary['sold_out_days']++;
    elseif ((int)$row['available'] < 3) $summary['low_inventory_days']++;
}

$flashes = cpa_get_flash();

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

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">Push Availability</div>
            <div class="hero-subtitle mt-2">
                Calculate PMS availability by room type and prepare channel payloads for NightsBridge, Booking.com, Expedia and Airbnb.
            </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 pushes are currently blocked by a stub until provider-specific API connector/certification details are added.
</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 availability-push 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">Unmapped</label>
                <select name="include_unmapped" class="form-select">
                    <option value="0" <?php echo $includeUnmapped === 0 ? 'selected' : ''; ?>>Hide</option>
                    <option value="1" <?php echo $includeUnmapped === 1 ? 'selected' : ''; ?>>Show</option>
                </select>
            </div>

            <div class="col-md-2 d-grid">
                <button class="btn btn-primary">
                    <i class="bi bi-calculator me-2"></i>Calculate
                </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-list-check"></i></div>
            <div><div class="metric-label">Availability Rows</div><div class="metric-value"><?php echo (int)$summary['rows']; ?></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-send-check"></i></div>
            <div><div class="metric-label">Payload Rows</div><div class="metric-value"><?php echo (int)$summary['mapped_payload_rows']; ?></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-x-octagon"></i></div>
            <div><div class="metric-label">Sold Out Days</div><div class="metric-value"><?php echo (int)$summary['sold_out_days']; ?></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-exclamation-triangle"></i></div>
            <div><div class="metric-label">Unmapped Rows</div><div class="metric-value"><?php echo (int)$summary['unmapped_rows']; ?></div></div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-9">
        <div class="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Availability Preview</h5>
                <div>
                    <form method="post" class="d-inline">
                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                        <input type="hidden" name="action" value="preview_push">
                        <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="include_unmapped" value="<?php echo (int)$includeUnmapped; ?>">
                        <button class="btn btn-sm btn-outline-primary" <?php echo !$selectedConnection ? 'disabled' : ''; ?>>
                            <i class="bi bi-eye me-2"></i>Log Preview
                        </button>
                    </form>

                    <form method="post" class="d-inline" onsubmit="return confirm('Attempt live push? This is currently stubbed and will not update OTA until provider connector is configured.');">
                        <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                        <input type="hidden" name="action" value="push_live">
                        <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="include_unmapped" value="<?php echo (int)$includeUnmapped; ?>">
                        <button class="btn btn-sm btn-danger" <?php echo !$selectedConnection ? 'disabled' : ''; ?>>
                            <i class="bi bi-cloud-upload me-2"></i>Push Live
                        </button>
                    </form>
                </div>
            </div>

            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Date</th>
                            <th>PMS Room Type</th>
                            <th>External Room</th>
                            <th class="text-end">Capacity</th>
                            <th class="text-end">Booked</th>
                            <th class="text-end">Available</th>
                            <th>Status</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$availabilityRows): ?>
                            <tr><td colspan="7" class="text-center text-muted py-4">No availability rows calculated.</td></tr>
                        <?php else: ?>
                            <?php foreach ($availabilityRows as $row): ?>
                                <?php
                                $status = 'Open';
                                $badge = 'text-bg-success';
                                $trClass = '';
                                if (!$row['mapped']) {
                                    $status = 'Unmapped';
                                    $badge = 'text-bg-warning';
                                } elseif ((int)$row['available'] <= 0) {
                                    $status = 'Closed / Sold Out';
                                    $badge = 'text-bg-danger';
                                    $trClass = 'table-danger';
                                } elseif ((int)$row['available'] < 3) {
                                    $status = 'Low Inventory';
                                    $badge = 'text-bg-warning';
                                    $trClass = 'table-warning';
                                }
                                ?>
                                <tr class="<?php echo h($trClass); ?>">
                                    <td><strong><?php echo h($row['date']); ?></strong></td>
                                    <td><?php echo h($row['room_type']); ?></td>
                                    <td>
                                        <?php if ($row['mapped']): ?>
                                            <strong><?php echo h($row['external_room_id']); ?></strong>
                                            <div class="small text-muted"><?php echo h($row['external_room_name'] ?: 'No external name'); ?></div>
                                        <?php else: ?>
                                            <span class="text-muted">Not mapped</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end"><?php echo (int)$row['capacity']; ?></td>
                                    <td class="text-end"><?php echo (int)$row['booked']; ?></td>
                                    <td class="text-end fw-bold"><?php echo (int)$row['available']; ?></td>
                                    <td><span class="badge <?php echo h($badge); ?>"><?php echo h($status); ?></span></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">Payload Preview</h5></div>
            <div class="card-body">
                <pre class="payload-box"><?php echo h(json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); ?></pre>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header"><h5 class="mb-0">Next Steps</h5></div>
            <div class="card-body small">
                <p class="text-muted">After availability preview is correct, build provider-specific connectors:</p>
                <ul class="mb-0">
                    <li>NightsBridge availability endpoint</li>
                    <li>Booking.com certified XML push</li>
                    <li>Expedia availability/rate connector</li>
                    <li>Airbnb approved partner connector</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<style>
.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'; ?>
