<?php
declare(strict_types=1);

require_once 'auth.php';
require_once 'conexao.php';

date_default_timezone_set('America/Sao_Paulo');

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

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

$id = (int) ($_GET['id'] ?? 0);

if ($id <= 0) {
    http_response_code(400);
    exit('Comprovante inválido.');
}

$stmt = $mysqli->prepare("\n    SELECT\n        m.*,\n        a.nome,\n        a.categoria,\n        a.marca,\n        a.modelo,\n        a.codigo_barras,\n        a.localizacao\n    FROM almoxarifado_movimentacoes m\n    INNER JOIN almoxarifado a ON a.id = m.item_id\n    WHERE m.id = ?\n    LIMIT 1\n");

if (!$stmt) {
    http_response_code(500);
    exit('Não foi possível preparar o comprovante.');
}

$stmt->bind_param('i', $id);
$stmt->execute();
$movement = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$movement) {
    http_response_code(404);
    exit('Movimentação não encontrada.');
}

$isEntry = $movement['tipo'] === 'ENTRADA';
$title = $isEntry
    ? 'TERMO DE ENTRADA DE MATERIAL'
    : 'TERMO DE SAÍDA / ENTREGA DE MATERIAL';

$originLabel = $isEntry ? 'Origem / fornecedor' : 'Destino / setor';
$responsibleLabel = $isEntry
    ? 'Responsável pelo recebimento'
    : 'Responsável pela retirada';

$timestamp = strtotime((string) $movement['criado_em']);
$date = $timestamp !== false ? date('d/m/Y', $timestamp) : 'Data inválida';
$time = $timestamp !== false ? date('H:i:s', $timestamp) : '--:--:--';
$code = str_pad((string) $id, 7, '0', STR_PAD_LEFT);
$autoPrint = ($_GET['print'] ?? '') === '1';
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= e($title) ?> #<?= e($code) ?></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{--primary:#08396f;--green:#087f5b;--red:#bd263d;--text:#172438;--muted:#65758a;--border:#d8e1ea;--soft:#f5f8fb}
        *{box-sizing:border-box}
        body{margin:0;padding:28px;font-family:"Inter",Arial,sans-serif;color:var(--text);background:#eaf0f5}
        .actions{max-width:900px;margin:0 auto 15px;display:flex;justify-content:flex-end;gap:8px}
        .action{min-height:42px;display:inline-flex;align-items:center;gap:7px;padding:0 14px;border:0;border-radius:12px;color:#fff;background:var(--primary);cursor:pointer;font-size:12px;font-weight:800;text-decoration:none}.action.secondary{color:var(--primary);border:1px solid #cbd8e4;background:#fff}
        .sheet{max-width:900px;min-height:1120px;margin:auto;padding:44px 48px;background:#fff;box-shadow:0 30px 80px rgba(8,57,111,.16)}
        .top-line{height:6px;margin:-44px -48px 32px;background:linear-gradient(90deg,var(--primary) 0 65%,var(--green) 65% 90%,#e8ad16 90%)}
        .header{display:flex;justify-content:space-between;gap:24px;align-items:center;padding-bottom:25px;border-bottom:2px solid var(--primary)}
        .brand{display:flex;align-items:center;gap:16px}.logo{width:82px;height:82px;object-fit:contain}.fallback{width:82px;height:82px;display:none;place-items:center;border-radius:18px;color:var(--primary);background:var(--soft);font-size:35px}
        .government{font-size:11px;font-weight:900;letter-spacing:.8px;text-transform:uppercase;color:var(--primary)}
        .department{margin-top:7px;font-size:18px;font-weight:900}.subtitle{margin-top:5px;color:var(--muted);font-size:11px}
        .document-code{text-align:right}.document-code span{display:block;color:var(--muted);font-size:9px;font-weight:800;text-transform:uppercase}.document-code strong{display:block;margin-top:5px;color:var(--primary);font-size:20px}
        h1{margin:32px 0 8px;text-align:center;font-size:22px;letter-spacing:.5px}.description{max-width:720px;margin:0 auto 28px;text-align:center;color:var(--muted);font-size:11px;line-height:1.65}
        .type{display:inline-flex;align-items:center;gap:7px;padding:8px 12px;border-radius:999px;color:#086247;background:#e8f8f1;font-size:10px;font-weight:900}.type.exit{color:#922138;background:#fff0f3}
        .section{margin-top:23px}.section-title{display:flex;align-items:center;gap:8px;margin-bottom:10px;color:var(--primary);font-size:11px;font-weight:900;letter-spacing:.5px;text-transform:uppercase}
        .grid{display:grid;grid-template-columns:repeat(2,1fr);border:1px solid var(--border);border-radius:16px;overflow:hidden}.field{min-height:78px;padding:14px 16px;border-right:1px solid var(--border);border-bottom:1px solid var(--border)}.field:nth-child(2n){border-right:0}.field.last-row{border-bottom:0}.field.full{grid-column:1/-1;border-right:0}.field span{display:block;color:var(--muted);font-size:8px;font-weight:800;letter-spacing:.6px;text-transform:uppercase}.field strong{display:block;margin-top:7px;font-size:12px;line-height:1.45}.quantity{font-size:24px!important;color:var(--primary)}
        .declaration{margin-top:25px;padding:17px 19px;border:1px solid var(--border);border-radius:15px;background:var(--soft);font-size:10px;line-height:1.75;text-align:justify}
        .signatures{display:grid;grid-template-columns:1fr 1fr;gap:55px;margin-top:85px}.signature{text-align:center}.signature-line{border-top:1px solid #4b596b;padding-top:8px;font-size:10px;font-weight:800}.signature small{display:block;margin-top:4px;color:var(--muted);font-size:8px}
        .protocol{margin-top:52px;padding-top:14px;border-top:1px dashed #aab7c4;display:flex;justify-content:space-between;gap:20px;color:var(--muted);font-size:8px;line-height:1.5}.protocol strong{color:var(--text)}
        .print-note{margin-top:18px;text-align:center;color:var(--muted);font-size:8px}
        @media(max-width:700px){body{padding:0;background:#fff}.actions{position:sticky;top:0;z-index:10;margin:0;padding:10px;background:#fff;border-bottom:1px solid var(--border)}.sheet{min-height:0;padding:25px 18px;box-shadow:none}.top-line{margin:-25px -18px 22px}.header{align-items:flex-start}.logo,.fallback{width:60px;height:60px}.document-code strong{font-size:14px}.grid{grid-template-columns:1fr}.field,.field:nth-child(2n){border-right:0}.field.last-row{border-bottom:1px solid var(--border)}.grid .field:last-child{border-bottom:0}.signatures{grid-template-columns:1fr;gap:75px}.protocol{flex-direction:column}}
        @media print{@page{size:A4;margin:12mm}body{padding:0;background:#fff}.actions{display:none!important}.sheet{max-width:none;min-height:0;margin:0;padding:0;box-shadow:none}.top-line{margin:0 0 22px}.print-note{display:none}}


        /*
        |--------------------------------------------------------------------------
        | Impressão A4 - conteúdo grande ocupando a folha inteira
        |--------------------------------------------------------------------------
        */
        .type-wrap {
            text-align: center;
        }

        @media print {
            @page {
                size: A4 portrait;
                margin: 7mm;
            }

            html,
            body {
                width: 100%;
                height: 100%;
                margin: 0;
                padding: 0;
                background: #ffffff;
            }

            .actions,
            .print-note {
                display: none !important;
            }

            .sheet {
                width: 100%;
                max-width: none;
                height: 283mm;
                min-height: 283mm;
                margin: 0;
                padding: 0;
                box-shadow: none;

                display: flex;
                flex-direction: column;
                gap: 9px;
            }

            .top-line {
                width: 100%;
                height: 5px;
                flex: 0 0 5px;
                margin: 0;
            }

            .header {
                flex: 0 0 auto;
                gap: 18px;
                padding: 4px 0 13px;
                border-bottom-width: 2px;
                break-inside: avoid;
                page-break-inside: avoid;
            }

            .brand {
                gap: 14px;
            }

            .logo,
            .fallback {
                width: 68px;
                height: 68px;
                flex: 0 0 68px;
            }

            .government {
                font-size: 9px;
                letter-spacing: .7px;
            }

            .department {
                margin-top: 4px;
                font-size: 16px;
            }

            .subtitle {
                margin-top: 3px;
                font-size: 9px;
            }

            .document-code span {
                font-size: 7px;
            }

            .document-code strong {
                margin-top: 3px;
                font-size: 18px;
            }

            h1 {
                flex: 0 0 auto;
                margin: 0;
                font-size: 19px;
                line-height: 1.15;
            }

            .type-wrap {
                flex: 0 0 auto;
                margin: 0;
                text-align: center;
            }

            .type {
                padding: 6px 11px;
                font-size: 8px;
            }

            .section {
                min-height: 0;
                margin: 0;
                display: flex;
                flex-direction: column;
                break-inside: avoid;
                page-break-inside: avoid;
            }

            .material-section {
                flex: .95 1 185px;
            }

            .movement-section {
                flex: 1.55 1 315px;
            }

            .section-title {
                flex: 0 0 auto;
                margin-bottom: 6px;
                font-size: 8px;
            }

            .grid {
                flex: 1 1 auto;
                min-height: 0;
                border-radius: 12px;
                break-inside: avoid;
                page-break-inside: avoid;
            }

            .field {
                min-height: 0;
                padding: 10px 13px;
                display: flex;
                flex-direction: column;
                justify-content: center;
            }

            .field span {
                font-size: 6px;
                letter-spacing: .55px;
            }

            .field strong {
                margin-top: 5px;
                font-size: 9.5px;
                line-height: 1.35;
            }

            .quantity {
                font-size: 17px !important;
            }

            .declaration {
                flex: 0 0 auto;
                margin: 0;
                padding: 11px 13px;
                border-radius: 12px;
                font-size: 8px;
                line-height: 1.55;
                break-inside: avoid;
                page-break-inside: avoid;
            }

            .signatures {
                height: 88px;
                flex: 0 0 88px;
                margin: 0;
                padding-top: 43px;
                gap: 45px;
                break-inside: avoid;
                page-break-inside: avoid;
            }

            .signature-line {
                padding-top: 7px;
                font-size: 8px;
            }

            .signature small {
                margin-top: 4px;
                font-size: 6px;
            }

            .protocol {
                min-height: 32px;
                flex: 0 0 32px;
                margin: 0;
                padding-top: 7px;
                font-size: 5.5px;
                line-height: 1.35;
                break-inside: avoid;
                page-break-inside: avoid;
            }
        }

    </style>
</head>
<body>
<div class="actions">
    <a href="almoxarifado.php" class="action secondary"><i class="bi bi-arrow-left"></i>Voltar</a>
    <button type="button" class="action" onclick="window.print()"><i class="bi bi-file-earmark-pdf-fill"></i>Imprimir / Salvar PDF</button>
</div>

<main class="sheet">
    <div class="top-line"></div>

    <header class="header">
        <div class="brand">
            <img class="logo" src="assets/logo_pref.jpg" alt="Prefeitura de Extrema" onerror="this.style.display='none';this.nextElementSibling.style.display='grid';">
            <div class="fallback"><i class="bi bi-buildings-fill"></i></div>
            <div>
                <div class="government">Prefeitura Municipal de Extrema</div>
                <div class="department">GERÊNCIA DE TECNOLOGIA</div>
                <div class="subtitle">CONTROLE DO ALMOXARIFADO DO TI</div>
            </div>
        </div>

        <div class="document-code">
            <span>Número do comprovante</span>
            <strong>#<?= e($code) ?></strong>
            <span style="margin-top:8px"><?= e($date) ?> às <?= e($time) ?></span>
        </div>
    </header>

    <h1><?= e($title) ?></h1>

    <div class="type-wrap"><span class="type <?= $isEntry ? '' : 'exit' ?>"><i class="bi <?= $isEntry ? 'bi-box-arrow-in-down' : 'bi-box-arrow-up-right' ?>"></i><?= e((string) $movement['tipo']) ?></span></div>

    <section class="section material-section">
        <div class="section-title"><i class="bi bi-box-seam-fill"></i>Identificação do material</div>
        <div class="grid">
            <div class="field"><span>Produto</span><strong><?= e((string) $movement['nome']) ?></strong></div>
            <div class="field"><span>Categoria</span><strong><?= e((string) $movement['categoria']) ?></strong></div>
            <div class="field"><span>Marca</span><strong><?= e((string) ($movement['marca'] ?: 'Não informada')) ?></strong></div>
            <div class="field"><span>Modelo</span><strong><?= e((string) ($movement['modelo'] ?: 'Não informado')) ?></strong></div>
            <div class="field last-row"><span>Código de barras</span><strong><?= e((string) ($movement['codigo_barras'] ?: 'Não informado')) ?></strong></div>
            <div class="field last-row"><span>Localização no almoxarifado</span><strong><?= e((string) ($movement['localizacao'] ?: 'Não informada')) ?></strong></div>
        </div>
    </section>

    <section class="section movement-section">
        <div class="section-title"><i class="bi bi-arrow-left-right"></i>Dados da movimentação</div>
        <div class="grid">
            <div class="field"><span>Tipo de movimentação</span><strong><?= e((string) $movement['tipo']) ?></strong></div>
            <div class="field"><span>Quantidade movimentada</span><strong class="quantity"><?= (int) $movement['quantidade'] ?> unidade(s)</strong></div>
            <div class="field"><span>Estoque anterior</span><strong><?= (int) $movement['estoque_anterior'] ?> unidade(s)</strong></div>
            <div class="field"><span>Estoque após a movimentação</span><strong><?= (int) $movement['estoque_posterior'] ?> unidade(s)</strong></div>
            <div class="field"><span><?= e($responsibleLabel) ?></span><strong><?= e((string) $movement['responsavel']) ?></strong></div>
            <div class="field"><span><?= e($originLabel) ?></span><strong><?= e((string) $movement['origem_destino']) ?></strong></div>
            <div class="field"><span>Documento / requisição</span><strong><?= e((string) ($movement['documento'] ?: 'Não informado')) ?></strong></div>
            <div class="field"><span>Usuário que registrou</span><strong><?= e((string) ($movement['usuario_sistema'] ?: 'Não informado')) ?></strong></div>
            <div class="field full last-row"><span>Finalidade / observação</span><strong><?= e((string) ($movement['observacao'] ?: 'Nenhuma observação registrada.')) ?></strong></div>
        </div>
    </section>

    <div class="declaration">
        <?php if ($isEntry): ?>
            Declaro, para fins de controle interno, que o material acima identificado foi recebido e conferido nas quantidades descritas, sendo incorporado ao estoque do Almoxarifado da Gerência de Tecnologia.
        <?php else: ?>
            Declaro, para fins de controle interno, que recebi o material acima identificado nas quantidades descritas, responsabilizando-me por sua correta destinação e utilização no serviço público municipal.
        <?php endif; ?>
    </div>

    <section class="signatures">
        <div class="signature"><div class="signature-line"><?= e((string) $movement['responsavel']) ?></div><small><?= e($responsibleLabel) ?> - assinatura</small></div>
        <div class="signature"><div class="signature-line"><?= e((string) ($movement['usuario_sistema'] ?: 'Servidor responsável')) ?></div><small>Gerência de Tecnologia - assinatura</small></div>
    </section>

    <div class="protocol">
        <div><strong>Comprovante:</strong> #<?= e($code) ?><br><strong>Registro:</strong> <?= e($date) ?> às <?= e($time) ?></div>
        <div style="text-align:right"><strong>Validação:</strong> Movimento <?= (int) $movement['id'] ?> / Item <?= (int) $movement['item_id'] ?><br>Documento gerado eletronicamente pelo sistema interno.</div>
    </div>

    <div class="print-note">Para gerar o arquivo PDF, use o botão “Imprimir / Salvar PDF” e escolha “Salvar como PDF” no navegador.</div>
</main>

<?php if ($autoPrint): ?>
<script>window.addEventListener('load', () => setTimeout(() => window.print(), 450));</script>
<?php endif; ?>
</body>
</html>
