<?php
declare(strict_types=1);

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/conexao.php';
require_once __DIR__ . '/os_publico_helpers.php';

date_default_timezone_set('America/Sao_Paulo');

if ($mysqli instanceof mysqli) {
    $mysqli->set_charset('utf8mb4');
}

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

function e(mixed $valor): string
{
    return htmlspecialchars((string) $valor, ENT_QUOTES, 'UTF-8');
}

function dataComprovante(?string $data): string
{
    $data = trim((string) $data);
    if ($data === '') {
        return 'Não informado';
    }

    $timestamp = strtotime($data);
    return $timestamp !== false ? date('d/m/Y H:i', $timestamp) : 'Não informado';
}

function buscarOrdensComprovante(mysqli $mysqli, array $ids): array
{
    $ids = array_values(array_unique(array_filter(array_map('intval', $ids), static fn(int $id): bool => $id > 0)));
    if (!$ids) {
        return [];
    }

    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $tipos = str_repeat('i', count($ids));

    $stmt = $mysqli->prepare("\n        SELECT\n            id,\n            numero_os,\n            nome_solicitante,\n            setor,\n            telefone,\n            tipo_equipamento,\n            marca,\n            modelo,\n            patrimonio,\n            numero_serie,\n            problema,\n            data_entrada,\n            token_acompanhamento,\n            acompanhamento_ativo\n        FROM ordens_servico\n        WHERE id IN ($placeholders)\n        ORDER BY FIELD(id, " . implode(',', $ids) . ")\n    ");

    if (!$stmt) {
        return [];
    }

    $stmt->bind_param($tipos, ...$ids);
    $stmt->execute();
    $ordens = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    return $ordens;
}

$ids = [];
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT) ?: 0;
if ($id > 0) {
    $ids[] = $id;
}

$lote = strtolower(trim((string) ($_GET['lote'] ?? '')));
if ($lote !== '' && preg_match('/^[a-f0-9]{32}$/', $lote) === 1) {
    $registroLote = $_SESSION['lotes_comprovante_abertura_os'][$lote] ?? null;

    if (is_array($registroLote)) {
        $criadoEm = (int) ($registroLote['criado_em'] ?? 0);
        if ($criadoEm > 0 && (time() - $criadoEm) <= 7200) {
            $ids = array_merge($ids, (array) ($registroLote['ids'] ?? []));
        } else {
            unset($_SESSION['lotes_comprovante_abertura_os'][$lote]);
        }
    }
}

$ordens = buscarOrdensComprovante($mysqli, $ids);
foreach ($ordens as &$ordem) {
    $osId = (int) $ordem['id'];
    $token = trim((string) ($ordem['token_acompanhamento'] ?? ''));

    if ($token === '') {
        $token = osPublicoGarantirToken($mysqli, $osId);
        $ordem['token_acompanhamento'] = $token;
        $ordem['acompanhamento_ativo'] = 1;
    }

    $ordem['codigo_acompanhamento'] = osPublicoCodigoAcompanhamento($token);
    $ordem['url_acompanhamento'] = osPublicoUrl($token);
}
unset($ordem);

$autoPrint = isset($_GET['print']) && (string) $_GET['print'] === '1';
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
    <meta name="theme-color" content="#08396f">
    <title>Comprovante de abertura da OS</title>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">

    <style>
        :root {
            --blue: #08396f;
            --blue-dark: #05294f;
            --green: #087f5b;
            --text: #182536;
            --muted: #607086;
            --border: #d8e3ec;
            --soft: #f5f9fc;
            --soft-2: #edf7fc;
        }

        * { box-sizing: border-box; }
        html, body {
            margin: 0;
            padding: 0;
            background: #dfe8ef;
            color: var(--text);
            font-family: "Inter", system-ui, -apple-system, "Segoe UI", sans-serif;
        }
        body { padding: 10px; }

        .screen-actions {
            max-width: 210mm;
            margin: 0 auto 10px;
            display: flex;
            justify-content: flex-end;
            gap: 8px;
        }

        .screen-button {
            min-height: 40px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 7px;
            padding: 0 13px;
            border: 0;
            border-radius: 11px;
            color: #fff;
            background: var(--blue);
            box-shadow: 0 10px 22px rgba(8,57,111,.16);
            text-decoration: none;
            text-transform: uppercase;
            font-size: 9px;
            font-weight: 900;
            cursor: pointer;
        }

        .screen-button.secondary {
            color: var(--blue);
            background: #fff;
        }

        .sheet {
            width: 210mm;
            height: 297mm;
            margin: 0 auto 12px;
            padding: 8mm 9mm 7mm;
            background: #fff;
            box-shadow: 0 18px 45px rgba(5,41,79,.14);
            overflow: hidden;
            position: relative;
            page-break-after: always;
        }
        .sheet:last-child { page-break-after: auto; }

        .top-line {
            position: absolute;
            inset: 0 0 auto 0;
            height: 3.4mm;
            background: linear-gradient(90deg, var(--blue) 0 72%, var(--green) 72% 100%);
        }

        .header {
            display: grid;
            grid-template-columns: 20mm 1fr 48mm;
            gap: 4mm;
            align-items: center;
            padding-bottom: 3mm;
            border-bottom: 1px solid var(--border);
        }

        .logo {
            width: 20mm;
            height: 20mm;
            display: grid;
            place-items: center;
            padding: 1.6mm;
            border: 1px solid var(--border);
            border-radius: 4mm;
            background: linear-gradient(145deg,#fff,#eef5fa);
        }
        .logo img { max-width: 15mm; max-height: 15mm; object-fit: contain; }

        .kicker {
            color: var(--blue);
            font-size: 6.8px;
            font-weight: 900;
            text-transform: uppercase;
            letter-spacing: .45px;
        }
        .title {
            margin-top: 1mm;
            font-size: 13.5pt;
            line-height: 1.06;
            font-weight: 900;
            letter-spacing: -.3px;
        }
        .subtitle {
            margin-top: .8mm;
            color: var(--muted);
            font-size: 7pt;
        }

        .os-box {
            padding: 3mm;
            border-radius: 4mm;
            text-align: center;
            color: #fff;
            background: linear-gradient(145deg, var(--blue-dark), var(--blue));
        }
        .os-box span {
            display: block;
            opacity: .75;
            font-size: 5.8px;
            font-weight: 900;
            text-transform: uppercase;
        }
        .os-box strong {
            display: block;
            margin-top: .9mm;
            font-size: 9.7pt;
            line-height: 1.15;
            font-weight: 900;
            word-break: break-word;
        }

        .success {
            display: flex;
            align-items: center;
            gap: 2.4mm;
            margin-top: 3mm;
            padding: 2.8mm 3mm;
            border: 1px solid #bfe6d8;
            border-radius: 3.6mm;
            background: #e8f8f1;
            color: #076448;
        }
        .success i {
            width: 8.5mm;
            height: 8.5mm;
            display: grid;
            place-items: center;
            flex: 0 0 8.5mm;
            border-radius: 2.8mm;
            color: #fff;
            background: var(--green);
            font-size: 11pt;
        }
        .success strong { display: block; font-size: 8.2pt; font-weight: 900; }
        .success span { display: block; margin-top: .4mm; font-size: 6.3pt; line-height: 1.3; }

        .section { margin-top: 3mm; }
        .section-title {
            margin-bottom: 1.5mm;
            display: flex;
            align-items: center;
            gap: 1.5mm;
            color: var(--blue);
            font-size: 6.6pt;
            font-weight: 900;
            text-transform: uppercase;
            letter-spacing: .45px;
        }

        .grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2mm;
        }
        .card {
            min-height: 11.5mm;
            padding: 2.1mm 2.4mm;
            border: 1px solid var(--border);
            border-radius: 3.1mm;
            background: var(--soft);
        }
        .card span {
            display: block;
            color: var(--muted);
            font-size: 5.2pt;
            font-weight: 900;
            text-transform: uppercase;
            letter-spacing: .35px;
        }
        .card strong {
            display: block;
            margin-top: .8mm;
            font-size: 7.3pt;
            line-height: 1.25;
            font-weight: 850;
            word-break: break-word;
        }

        .problem {
            min-height: 13mm;
            max-height: 18mm;
            overflow: hidden;
            padding: 2.4mm;
            border: 1px solid var(--border);
            border-radius: 3.1mm;
            background: #fff;
            font-size: 6.9pt;
            line-height: 1.35;
            word-break: break-word;
        }

        .tracking {
            display: grid;
            grid-template-columns: 1fr 28mm;
            gap: 3mm;
            padding: 2.8mm;
            border: 1px solid #c7dce8;
            border-radius: 3.8mm;
            background: var(--soft-2);
            align-items: center;
        }
        .tracking-label {
            color: var(--blue);
            font-size: 6.2pt;
            font-weight: 900;
            text-transform: uppercase;
            letter-spacing: .45px;
        }
        .tracking-code {
            display: inline-block;
            margin-top: 1.1mm;
            padding: 1.8mm 2.5mm;
            border: 1px dashed var(--blue);
            border-radius: 2.6mm;
            color: var(--blue);
            background: #fff;
            font-family: monospace;
            font-size: 13pt;
            font-weight: 900;
            letter-spacing: .9px;
        }
        .tracking-text {
            margin-top: 1.1mm;
            color: #486075;
            font-size: 6pt;
            line-height: 1.3;
        }
        .tracking-site {
            margin-top: 1.2mm;
            padding: 1.6mm 2mm;
            border-radius: 2.1mm;
            background: rgba(255,255,255,.88);
            color: var(--blue);
            font-size: 5.5pt;
            line-height: 1.18;
            word-break: break-all;
        }
        .qr-box {
            width: 24mm;
            height: 24mm;
            display: grid;
            place-items: center;
            margin: auto;
            padding: 1mm;
            border: 1px solid var(--border);
            border-radius: 2.8mm;
            background: #fff;
        }
        .qr-box img,
        .qr-box canvas {
            width: 20mm !important;
            height: 20mm !important;
        }

        .status-line {
            display: flex;
            flex-wrap: wrap;
            gap: 5px 10px;
            padding: 2.2mm 2.5mm;
            border: 1px solid var(--border);
            border-radius: 3.1mm;
            background: var(--soft);
            color: var(--blue);
            font-size: 6.2pt;
            font-weight: 800;
            line-height: 1.3;
        }
        .status-line span::before {
            content: '• ';
            color: var(--green);
            font-weight: 900;
        }

        .footer {
            margin-top: 3mm;
            padding-top: 2mm;
            border-top: 1px solid var(--border);
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 4mm;
            color: var(--muted);
            font-size: 5.3pt;
            line-height: 1.28;
        }
        .footer strong { color: var(--blue); font-weight: 900; }

        .empty-state {
            max-width: 720px;
            margin: 60px auto;
            padding: 28px;
            border-radius: 20px;
            background: #fff;
            text-align: center;
            box-shadow: 0 18px 42px rgba(5,41,79,.12);
        }

        @page {
            size: A4 portrait;
            margin: 0;
        }

        @media print {
            html, body { background: #fff; }
            body { padding: 0; }
            .screen-actions { display: none !important; }
            .sheet {
                width: 210mm;
                height: 297mm;
                margin: 0;
                padding: 7mm 8mm 6mm;
                box-shadow: none;
                zoom: 0.96;
            }
        }

        @media (max-width: 860px) {
            body { padding: 8px; }
            .sheet {
                width: 100%;
                height: auto;
                min-height: auto;
                padding: 15px;
            }
            .header { grid-template-columns: 20mm 1fr; }
            .os-box { grid-column: 1 / -1; }
            .grid, .tracking { grid-template-columns: 1fr; }
            .footer { flex-direction: column; }
        }
    </style>
</head>
<body>
<?php if ($ordens): ?>
    <div class="screen-actions">
        <a href="listar_os.php?ok=1&quantidade=<?= count($ordens) ?>" class="screen-button secondary">
            <i class="bi bi-arrow-left-circle-fill"></i>
            Voltar às OS
        </a>
        <button type="button" class="screen-button" onclick="window.print()">
            <i class="bi bi-printer-fill"></i>
            Imprimir / salvar PDF
        </button>
    </div>

    <?php foreach ($ordens as $os): ?>
        <?php
        $equipamento = trim(implode(' • ', array_filter([
            trim((string) ($os['tipo_equipamento'] ?? '')),
            trim((string) ($os['marca'] ?? '')),
            trim((string) ($os['modelo'] ?? ''))
        ])));

        $patrimonioSerie = trim(implode(' • ', array_filter([
            trim((string) ($os['patrimonio'] ?? '')),
            trim((string) ($os['numero_serie'] ?? ''))
        ])));
        ?>
        <section class="sheet">
            <div class="top-line"></div>

            <header class="header">
                <div class="logo">
                    <img src="assets/logo_pref.jpg" alt="Prefeitura de Extrema" onerror="this.style.display='none';this.parentElement.innerHTML='<i class=&quot;bi bi-buildings-fill&quot; style=&quot;font-size:18pt;color:#08396f;&quot;></i>';">
                </div>

                <div>
                    <div class="kicker">Prefeitura Municipal de Extrema</div>
                    <div class="title">Comprovante de abertura da OS</div>
                    <div class="subtitle">Gerência de Tecnologia • acompanhamento da manutenção</div>
                </div>

                <div class="os-box">
                    <span>Ordem de serviço</span>
                    <strong><?= e((string) $os['numero_os']) ?></strong>
                </div>
            </header>

            <div class="success">
                <i class="bi bi-check-circle-fill"></i>
                <div>
                    <strong>Solicitação registrada com sucesso</strong>
                    <span>Guarde este comprovante para acompanhar a manutenção até a retirada.</span>
                </div>
            </div>

            <section class="section">
                <div class="section-title"><i class="bi bi-card-list"></i>Dados principais</div>
                <div class="grid">
                    <div class="card"><span>Solicitante</span><strong><?= e((string) ($os['nome_solicitante'] ?: 'Não informado')) ?></strong></div>
                    <div class="card"><span>Setor</span><strong><?= e((string) ($os['setor'] ?: 'Não informado')) ?></strong></div>
                    <div class="card"><span>Telefone / ramal</span><strong><?= e((string) ($os['telefone'] ?: 'Não informado')) ?></strong></div>
                    <div class="card"><span>Data de abertura</span><strong><?= e(dataComprovante($os['data_entrada'] ?? null)) ?></strong></div>
                    <div class="card"><span>Equipamento</span><strong><?= e($equipamento !== '' ? $equipamento : 'Não informado') ?></strong></div>
                    <div class="card"><span>Patrimônio / série</span><strong><?= e($patrimonioSerie !== '' ? $patrimonioSerie : 'Não informado') ?></strong></div>
                </div>
            </section>

            <section class="section">
                <div class="section-title"><i class="bi bi-chat-left-text-fill"></i>Problema informado</div>
                <div class="problem"><?= nl2br(e((string) ($os['problema'] ?: 'Não informado'))) ?></div>
            </section>

            <section class="section">
                <div class="section-title"><i class="bi bi-qr-code-scan"></i>Acompanhamento</div>
                <div class="tracking">
                    <div>
                        <div class="tracking-label">Código de acompanhamento</div>
                        <div class="tracking-code"><?= e((string) $os['codigo_acompanhamento']) ?></div>
                        <div class="tracking-text">Escaneie o QR Code ou acesse o link abaixo. Se preferir, entre no portal e informe o número da OS + este código.</div>
                        <div class="tracking-site"><?= e((string) $os['url_acompanhamento']) ?></div>
                    </div>
                    <div class="qr-box" data-qr-url="<?= e((string) $os['url_acompanhamento']) ?>">
                        <i class="bi bi-qr-code" style="font-size:20pt;color:#08396f;"></i>
                    </div>
                </div>
            </section>

            <section class="section">
                <div class="section-title"><i class="bi bi-signpost-fill"></i>Andamento</div>
                <div class="status-line">
                    <span>Recebida</span>
                    <span>Em análise / manutenção</span>
                    <span>Pronta para retirada</span>
                    <span>Entregue</span>
                </div>
            </section>

            <footer class="footer">
                <div>
                    Emitido em <?= e(date('d/m/Y H:i')) ?>.<br>
                    <strong>Importante:</strong> guarde o código de acompanhamento.
                </div>
                <div>Consulta protegida por link exclusivo e código curto.</div>
            </footer>
        </section>
    <?php endforeach; ?>
<?php else: ?>
    <div class="empty-state">
        <h1>Comprovante indisponível</h1>
        <p>Não foi possível localizar a ordem solicitada.</p>
        <a href="listar_os.php" class="screen-button">Voltar para a listagem</a>
    </div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
<script>
(() => {
    'use strict';
    document.querySelectorAll('[data-qr-url]').forEach(area => {
        const url = area.dataset.qrUrl || '';
        if (!url || typeof QRCode !== 'function') return;
        area.innerHTML = '';
        new QRCode(area, {
            text: url,
            width: 150,
            height: 150,
            colorDark: '#05294f',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.M
        });
    });

    const autoPrint = <?= $autoPrint ? 'true' : 'false' ?>;
    if (autoPrint) {
        setTimeout(() => window.print(), 650);
    }
})();
</script>
</body>
</html>
