<?php
declare(strict_types=1);

session_start();
require_once __DIR__ . '/config/quote_helpers.php';

function getPreviewParam(string $key, string $fallback): string
{
    return trim((string) ($_GET[$key] ?? $fallback));
}

function previewParseCurrency(string $value): float
{
    $value = trim($value);

    if ($value === '') {
        return 0.0;
    }

    $value = str_replace(['R$', ' '], '', $value);
    $value = str_replace('.', '', $value);
    $value = str_replace(',', '.', $value);

    return is_numeric($value) ? (float) $value : 0.0;
}

function previewFormatCurrency(float $value): string
{
    return 'R$ ' . number_format($value, 2, ',', '.');
}

function renderStandalonePreview(
    array $professional,
    array $payment,
    array $services,
    string $selectedModel,
    string $customColor,
    int $intensity
): string {
    [$normalizedServices, $total] = q_calc_services($services);

    $payment['formas_legenda'] = !empty($payment['formas_pagamento']) && is_array($payment['formas_pagamento'])
        ? implode(', ', $payment['formas_pagamento'])
        : '-';

    $parcelasTexto = trim((string) ($payment['parcelas'] ?? ''));
    $valorParceladoBruto = previewParseCurrency((string) ($payment['valor_parcelado'] ?? ''));
    $parcelasNumero = (int) preg_replace('/\D+/', '', $parcelasTexto);

    if ($parcelasNumero > 0 && $valorParceladoBruto > 0) {
        $valorParcela = $valorParceladoBruto / $parcelasNumero;
        $payment['parcelado_legenda'] = $parcelasNumero . 'x de ' . previewFormatCurrency($valorParcela);
    } elseif ($valorParceladoBruto > 0) {
        $payment['parcelado_legenda'] = previewFormatCurrency($valorParceladoBruto);
    } else {
        $payment['parcelado_legenda'] = '-';
    }

    $themeBase = q_mix_color_with_white($customColor, $intensity);
    $theme = [
        'base'  => $themeBase,
        'light' => q_rgba($themeBase, 0.22),
        'soft'  => q_rgba($themeBase, 0.10),
    ];

    $templatePath = __DIR__ . '/templates/' . $selectedModel . '.php';
    if (!is_file($templatePath)) {
        $templatePath = __DIR__ . '/templates/template1.php';
    }

    ob_start();
    $services = $normalizedServices;
    require $templatePath;
    return (string) ob_get_clean();
}

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

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

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

$intensity = (int) getPreviewParam('intensity', (string) ($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;
}

$html = renderStandalonePreview($professional, $payment, $services, $model, $color, $intensity);
$isPrint = isset($_GET['print']) && (string) $_GET['print'] === '1';
$isAutoPrint = isset($_GET['autoprint']) && (string) $_GET['autoprint'] === '1';
?>
<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Prévia do orçamento</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        html, body {
            margin: 0;
            padding: 0;
        }

        .page-shell {
            padding: 24px;
            background: #f3f4f6;
            min-height: 100vh;
        }

        .preview-shell {
            max-width: 210mm;
            margin: 0 auto;
        }

        /* Somente no print: preservar o MESMO layout da prévia */
        <?php if ($isPrint): ?>
        @page {
            size: A4 portrait;
            margin: 8mm;
        }

        .print-tip {
            display: none;
        }

        @media print {
            html, body {
                margin: 0 !important;
                padding: 0 !important;
                background: #ffffff !important;
            }

            body * {
                visibility: hidden !important;
            }

            #print-root,
            #print-root * {
                visibility: visible !important;
            }

            #print-root {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                margin: 0 !important;
                padding: 0 !important;
                background: #ffffff !important;
            }

            .page-shell {
                padding: 0 !important;
                background: #ffffff !important;
                min-height: auto !important;
            }

            /* Mantém a mesma largura visual da prévia */
            .preview-shell {
                max-width: 210mm !important;
                margin: 0 auto !important;
                padding: 0 !important;
                background: #ffffff !important;
            }

            /* Só limpa a “casca” externa, sem mexer no conteúdo interno */
            .quote-stage {
                background: #ffffff !important;
            }
        }
        <?php endif; ?>
    </style>
</head>
<body>
<?php if ($isAutoPrint): ?>
<div class="print-tip" style="max-width:960px; margin:12px auto 0 auto; padding:10px 14px; background:#fff8e1; border:1px solid #f1d37a; border-radius:10px; color:#5f4b00; font-size:14px; font-family:Arial, sans-serif;">
    No celular, escolha <strong>Imprimir</strong>, <strong>Salvar em PDF</strong> ou <strong>Compartilhar</strong>, conforme as opções do aparelho.
</div>
<?php endif; ?>

<div id="print-root" class="page-shell">
    <section class="preview-shell">
        <div class="quote-stage"><?php echo $html; ?></div>
    </section>
</div>

<?php if ($isAutoPrint): ?>
<script>
(function () {
    window.addEventListener('load', function () {
        setTimeout(function () {
            window.print();
        }, 350);
    });
})();
</script>
<?php elseif ($isPrint): ?>
<script>
window.addEventListener('load', function () {
    setTimeout(function () {
        window.print();
    }, 250);
});
</script>
<?php endif; ?>
</body>
</html>