<?php
declare(strict_types=1);

session_start();

require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/config/quote_helpers.php';

$professional = $_SESSION['professional'] ?? [];
$services     = $_SESSION['services'] ?? [];
$preview      = $_SESSION['preview'] ?? [
    'model'        => ($_SESSION['model'] ?? 'template1'),
    'custom_color' => '#1e3a5f',
    'intensity'    => 100,
];

$model = trim((string) ($_GET['model'] ?? ($preview['model'] ?? 'template1')));
if (!in_array($model, ['template1', 'template2', 'template3'], true)) {
    $model = 'template1';
}

$color = trim((string) ($_GET['color'] ?? ($preview['custom_color'] ?? '#1e3a5f')));
if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
    $color = '#1e3a5f';
}

$intensity = (int) ($_GET['intensity'] ?? ($preview['intensity'] ?? 100));
$intensity = max(30, min(100, $intensity));

if (empty($professional['nome_profissional']) || empty($services) || !is_array($services)) {
    header('Location: wizard.php?step=1');
    exit;
}

if (function_exists('incrementBudgetMetrics')) {
    incrementBudgetMetrics(
        (string) ($professional['nome_profissional'] ?? ''),
        (string) ($professional['telefone_profissional'] ?? '')
    );
}

$query = http_build_query([
    'print'     => '1',
    'autoprint' => '1',
    'model'     => $model,
    'color'     => $color,
    'intensity' => (string) $intensity,
]);

header('Location: preview.php?' . $query);
exit;