<?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 Rates';

if (file_exists(__DIR__ . '/../reports/pricing_engine_v2.php')) {
    require_once __DIR__ . '/../reports/pricing_engine_v2.php';
}

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('cpr_table_exists')) {
    function cpr_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('cpr_column_exists')) {
    function cpr_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('cpr_flash')) {
    function cpr_flash(string $type, string $message): void {
        $_SESSION['channel_push_rates_flash'][] = ['type' => $type, 'message' => $message];
    }
}
if (!function_exists('cpr_get_flash')) {
    function cpr_get_flash(): array {
        $items = $_SESSION['channel_push_rates_flash'] ?? [];
        unset($_SESSION['channel_push_rates_flash']);
        return $items;
    }
}
if (!function_exists('cpr_date_range')) {
    function cpr_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('cpr_log_sync')) {
    function cpr_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, 'rate_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('cpr_provider_stub_push')) {
    function cpr_provider_stub_push(array $connection, array $payload, bool $liveMode = false): array {
        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['rates'] ?? []),
            ];
        }
if (($connection['provider'] ?? '') === 'booking_com' && function_exists('bc_push_rates')) {
    return bc_push_rates($connection, $payload['rates'] ?? []);
}
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 rate push is blocked because provider-specific API connector is not configured yet.',
            'records_received' => count($payload['rates'] ?? []),
        ];
    }
}
if (!function_exists('cpr_get_base_rate')) {
    function cpr_get_base_rate(PDO $pdo, int $roomTypeId, int $ratePlanId, string $date, float $fallbackRate): float {
        if ($ratePlanId > 0 && cpr_table_exists($pdo, 'room_type_rate_plans')) {
            $hasValidFrom = cpr_column_exists($pdo, 'room_type_rate_plans', 'valid_from');
            $hasValidTo = cpr_column_exists($pdo, 'room_type_rate_plans', 'valid_to');
            $hasSharing = cpr_column_exists($pdo, 'room_type_rate_plans', 'sharing_rate');
            $hasSingle = cpr_column_exists($pdo, 'room_type_rate_plans', 'single_rate');
            $hasStatus = cpr_column_exists($pdo, 'room_type_rate_plans', 'status');

            if ($hasSharing) {
                $where = "id = :id";
                $params = [':id' => $ratePlanId];

                if ($hasValidFrom) {
                    $where .= " AND (valid_from IS NULL OR valid_from <= :date_from)";
                    $params[':date_from'] = $date;
                }
                if ($hasValidTo) {
                    $where .= " AND (valid_to IS NULL OR valid_to >= :date_to)";
                    $params[':date_to'] = $date;
                }
                if ($hasStatus) {
                    $where .= " AND (status IS NULL OR status IN ('active','1',1))";
                }

                $select = "sharing_rate";
                if ($hasSingle) {
                    $select = "COALESCE(NULLIF(sharing_rate,0), NULLIF(single_rate,0), 0)";
                }

                $stmt = $pdo->prepare("SELECT $select FROM room_type_rate_plans WHERE $where LIMIT 1");
                $stmt->execute($params);
                $rate = $stmt->fetchColumn();

                if ($rate !== false && (float)$rate > 0) {
                    return (float)$rate;
                }
            }
        }

        if (cpr_table_exists($pdo, 'room_types')) {
            foreach (['base_rate','rate','price','default_rate','sharing_rate'] as $col) {
                if (cpr_column_exists($pdo, 'room_types', $col)) {
                    $stmt = $pdo->prepare("SELECT $col FROM room_types WHERE id = :id LIMIT 1");
                    $stmt->execute([':id' => $roomTypeId]);
                    $rate = $stmt->fetchColumn();
                    if ($rate !== false && (float)$rate > 0) {
                        return (float)$rate;
                    }
                }
            }
        }

        return $fallbackRate;
    }
}

$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_rates = 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'))));
$fallbackRate = (float)($_GET['fallback_rate'] ?? $_POST['fallback_rate'] ?? 150);
$useDynamicPricing = (int)($_GET['use_dynamic_pricing'] ?? $_POST['use_dynamic_pricing'] ?? 1);
$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;
}
if ($fallbackRate <= 0) {
    $fallbackRate = 150;
}

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

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

$rateRows = [];
$payload = [
    'connection_id' => $connectionId,
    'provider' => $selectedConnection['provider'] ?? null,
    'external_property_id' => $selectedConnection['external_property_id'] ?? null,
    'date_from' => $dateFrom,
    'date_to' => $dateTo,
    'dynamic_pricing' => $useDynamicPricing === 1,
    'rates' => [],
];

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

        $stmt = $pdo->prepare("
            SELECT
                crm.*,
                rt.title AS room_type,
                rp.title AS rate_plan
            FROM channel_rate_mapping crm
            INNER JOIN room_types rt ON rt.id = crm.room_type_id
            LEFT JOIN room_type_rate_plans rp ON rp.id = crm.rate_plan_id
            WHERE crm.connection_id = :connection_id
              AND crm.is_active = 1
            ORDER BY rt.title ASC, rp.title ASC, crm.external_rate_name ASC
        ");
        $stmt->execute([':connection_id' => $connectionId]);
        $mappings = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($includeUnmapped === 1) {
            $stmt = $pdo->prepare("
                SELECT
                    0 AS id,
                    :connection_id AS connection_id,
                    rt.id AS room_type_id,
                    NULL AS rate_plan_id,
                    '' AS external_rate_id,
                    '' AS external_rate_name,
                    rt.title AS room_type,
                    NULL AS rate_plan
                FROM room_types rt
                WHERE NOT EXISTS (
                    SELECT 1
                    FROM channel_rate_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,
            ]);
            $mappings = array_merge($mappings, $stmt->fetchAll(PDO::FETCH_ASSOC));
        }

        foreach ($mappings as $mapping) {
            $roomTypeId = (int)$mapping['room_type_id'];
            $ratePlanId = (int)($mapping['rate_plan_id'] ?? 0);

            foreach ($dates as $day) {
                $baseRate = cpr_get_base_rate($pdo, $roomTypeId, $ratePlanId, $day, $fallbackRate);
                $finalRate = $baseRate;
                $pricingReasons = [];
                $adjustmentPercent = 0;
                $demandLevel = 'normal';

                if ($useDynamicPricing === 1 && function_exists('pricing_engine_v2_suggest_rate')) {
                    $suggestion = pricing_engine_v2_suggest_rate($pdo, [
                        'property_id' => $propertyId,
                        'room_type_id' => $roomTypeId,
                        'agent_id' => 0,
                        'stay_date' => $day,
                        'base_rate' => $baseRate,
                        'min_rate' => $baseRate * 0.75,
                        'max_rate' => $baseRate * 1.65,
                        'round_to' => 1,
                    ]);

                    if (!empty($suggestion['ok'])) {
                        $finalRate = (float)$suggestion['recommended_rate'];
                        $pricingReasons = $suggestion['reasons'] ?? [];
                        $adjustmentPercent = (float)($suggestion['adjustment_percent'] ?? 0);
                        $demandLevel = (string)($suggestion['demand_level'] ?? 'normal');
                    }
                }

                $mapped = trim((string)($mapping['external_rate_id'] ?? '')) !== '';

                $row = [
                    'date' => $day,
                    'room_type_id' => $roomTypeId,
                    'room_type' => $mapping['room_type'],
                    'rate_plan_id' => $ratePlanId,
                    'rate_plan' => $mapping['rate_plan'] ?: 'Default / BAR',
                    'external_rate_id' => (string)($mapping['external_rate_id'] ?? ''),
                    'external_rate_name' => (string)($mapping['external_rate_name'] ?? ''),
                    'base_rate' => $baseRate,
                    'final_rate' => $finalRate,
                    'adjustment_percent' => $adjustmentPercent,
                    'demand_level' => $demandLevel,
                    'pricing_reasons' => $pricingReasons,
                    'mapped' => $mapped,
                ];

                $rateRows[] = $row;

                if ($mapped) {
                    $payload['rates'][] = [
                        'date' => $day,
                        'external_rate_id' => $row['external_rate_id'],
                        'amount' => round($finalRate, 2),
                        'currency' => 'USD',
                        'closed' => 0,
                    ];
                }
            }
        }
    } catch (Throwable $e) {
        $errors[] = 'Could not calculate rates: ' . $e->getMessage();
    }
} elseif (!$selectedConnection && !$connections) {
    $errors[] = 'No active channel connection with rate 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 = cpr_provider_stub_push($selectedConnection ?: [], $payload, false);
            $logId = cpr_log_sync(
                $pdo,
                $connectionId,
                $selectedConnection['provider'] ?? 'unknown',
                'preview',
                $payload,
                $response,
                'Rate preview generated. Nothing sent to channel.'
            );

            cpr_flash('success', 'Rate preview payload generated and logged. Log ID: ' . $logId);
            header('Location: channel_push_rates.php?connection_id=' . $connectionId . '&date_from=' . urlencode($dateFrom) . '&date_to=' . urlencode($dateTo) . '&fallback_rate=' . urlencode((string)$fallbackRate) . '&use_dynamic_pricing=' . $useDynamicPricing);
            exit;
        }

        if ($action === 'push_live') {
            $response = cpr_provider_stub_push($selectedConnection ?: [], $payload, true);
            $status = !empty($response['ok']) ? 'success' : 'failed';

            $logId = cpr_log_sync(
                $pdo,
                $connectionId,
                $selectedConnection['provider'] ?? 'unknown',
                $status,
                $payload,
                $response,
                $response['message'] ?? 'Rate push attempted.'
            );

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

            header('Location: channel_push_rates.php?connection_id=' . $connectionId . '&date_from=' . urlencode($dateFrom) . '&date_to=' . urlencode($dateTo) . '&fallback_rate=' . urlencode((string)$fallbackRate) . '&use_dynamic_pricing=' . $useDynamicPricing);
            exit;
        }

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

$summary = [
    'rows' => count($rateRows),
    'payload_rows' => count($payload['rates']),
    'unmapped_rows' => 0,
    'increased_days' => 0,
    'decreased_days' => 0,
];

foreach ($rateRows as $row) {
    if (!$row['mapped']) $summary['unmapped_rows']++;
    if ((float)$row['final_rate'] > (float)$row['base_rate']) $summary['increased_days']++;
    if ((float)$row['final_rate'] < (float)$row['base_rate']) $summary['decreased_days']++;
}

$flashes = cpr_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-tags"></i> Channel Manager</div>
            <div class="hero-title mt-2">Push Rates</div>
            <div class="hero-subtitle mt-2">
                Prepare PMS rates and optional dynamic pricing recommendations for external channel rate plans.
            </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 rate 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-3">
                <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 rate-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-1">
                <label class="form-label">Fallback</label>
                <input type="number" step="0.01" name="fallback_rate" class="form-control" value="<?php echo h($fallbackRate); ?>">
            </div>

            <div class="col-md-2">
                <label class="form-label">Dynamic Pricing</label>
                <select name="use_dynamic_pricing" class="form-select">
                    <option value="1" <?php echo $useDynamicPricing === 1 ? 'selected' : ''; ?>>Use V2</option>
                    <option value="0" <?php echo $useDynamicPricing === 0 ? 'selected' : ''; ?>>Base rates only</option>
                </select>
            </div>

            <div class="col-md-1">
                <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-1 d-grid">
                <button class="btn btn-primary"><i class="bi bi-calculator"></i></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">Rate 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['payload_rows']; ?></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-graph-up"></i></div>
            <div><div class="metric-label">Increased</div><div class="metric-value"><?php echo (int)$summary['increased_days']; ?></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">Unmapped</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">Rate 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="fallback_rate" value="<?php echo h($fallbackRate); ?>">
                        <input type="hidden" name="use_dynamic_pricing" value="<?php echo (int)$useDynamicPricing; ?>">
                        <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 rate 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="fallback_rate" value="<?php echo h($fallbackRate); ?>">
                        <input type="hidden" name="use_dynamic_pricing" value="<?php echo (int)$useDynamicPricing; ?>">
                        <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 / Rate</th>
                            <th>External Rate</th>
                            <th class="text-end">Base</th>
                            <th class="text-end">Final</th>
                            <th class="text-end">Change</th>
                            <th>Demand</th>
                            <th>Status</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$rateRows): ?>
                            <tr><td colspan="8" class="text-center text-muted py-4">No rate rows calculated.</td></tr>
                        <?php else: ?>
                            <?php foreach ($rateRows as $row): ?>
                                <?php
                                $status = $row['mapped'] ? 'Mapped' : 'Unmapped';
                                $badge = $row['mapped'] ? 'text-bg-success' : 'text-bg-warning';

                                $change = (float)$row['base_rate'] > 0 ? (((float)$row['final_rate'] - (float)$row['base_rate']) / (float)$row['base_rate']) * 100 : 0;
                                $changeClass = $change >= 0 ? 'text-success' : 'text-danger';

                                $demandBadge = 'text-bg-secondary';
                                if ($row['demand_level'] === 'very_high') $demandBadge = 'text-bg-danger';
                                elseif ($row['demand_level'] === 'high') $demandBadge = 'text-bg-warning';
                                elseif (in_array($row['demand_level'], ['soft','low'], true)) $demandBadge = 'text-bg-info';
                                ?>
                                <tr>
                                    <td><strong><?php echo h($row['date']); ?></strong></td>
                                    <td>
                                        <strong><?php echo h($row['room_type']); ?></strong>
                                        <div class="small text-muted"><?php echo h($row['rate_plan']); ?></div>
                                        <?php if ($row['pricing_reasons']): ?>
                                            <div class="small text-muted"><?php echo h(mb_strimwidth(implode(' | ', $row['pricing_reasons']), 0, 120, '...')); ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($row['mapped']): ?>
                                            <strong><?php echo h($row['external_rate_id']); ?></strong>
                                            <div class="small text-muted"><?php echo h($row['external_rate_name'] ?: 'No external name'); ?></div>
                                        <?php else: ?>
                                            <span class="text-muted">Not mapped</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end"><?php echo money_fmt($row['base_rate']); ?></td>
                                    <td class="text-end fw-bold"><?php echo money_fmt($row['final_rate']); ?></td>
                                    <td class="text-end <?php echo h($changeClass); ?>">
                                        <?php echo $change >= 0 ? '+' : ''; ?><?php echo money_fmt($change); ?>%
                                    </td>
                                    <td>
                                        <span class="badge <?php echo h($demandBadge); ?>">
                                            <?php echo h(ucwords(str_replace('_', ' ', $row['demand_level']))); ?>
                                        </span>
                                    </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">Rate Source</h5></div>
            <div class="card-body small">
                <p class="text-muted mb-2">Base rate lookup order:</p>
                <ol class="mb-3">
                    <li>Mapped PMS rate plan</li>
                    <li>Room type rate column</li>
                    <li>Fallback rate</li>
                </ol>
                <p class="text-muted mb-0">
                    Dynamic pricing uses <strong>pricing_engine_v2.php</strong> when available.
                </p>
            </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'; ?>
