<?php
declare(strict_types=1);

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

date_default_timezone_set('America/Sao_Paulo');

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

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

function colunaExiste(
    mysqli $mysqli,
    string $tabela,
    string $coluna
): bool {
    $stmt = $mysqli->prepare("
        SELECT COUNT(*) AS total
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = ?
          AND COLUMN_NAME = ?
    ");

    if (!$stmt) {
        return false;
    }

    $stmt->bind_param('ss', $tabela, $coluna);
    $stmt->execute();
    $linha = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    return (int) ($linha['total'] ?? 0) > 0;
}

$loteId = filter_input(INPUT_GET, 'lote_id', FILTER_VALIDATE_INT);
$movimentacaoId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$itens = [];
$lote = null;

if ($loteId && $loteId > 0) {
    $stmt = $mysqli->prepare("
        SELECT *
        FROM tonner_saida_lotes
        WHERE id = ?
        LIMIT 1
    ");

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

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

    if (!$lote) {
        http_response_code(404);
        exit('Comprovante conjunto não encontrado.');
    }

    $stmt = $mysqli->prepare("
        SELECT
            m.id,
            m.modelo,
            m.tipo,
            m.quantidade,
            m.estoque_anterior,
            m.estoque_posterior,
            m.observacao,
            e.codigo_barras,
            e.estoque_minimo
        FROM tonner_movimentacoes AS m
        LEFT JOIN tonner_estoque AS e
          ON e.modelo = m.modelo
        WHERE m.saida_lote_id = ?
          AND m.tipo = 'SAIDA'
        ORDER BY m.id ASC
    ");

    $stmt->bind_param('i', $loteId);
    $stmt->execute();
    $resultado = $stmt->get_result();

    while ($linha = $resultado->fetch_assoc()) {
        $itens[] = $linha;
    }

    $stmt->close();
} elseif ($movimentacaoId && $movimentacaoId > 0) {
    $temResponsavelEntrega = colunaExiste(
        $mysqli,
        'tonner_movimentacoes',
        'responsavel_entrega'
    );

    $campoResponsavelEntrega = $temResponsavelEntrega
        ? 'm.responsavel_entrega,'
        : 'NULL AS responsavel_entrega,';

    $stmt = $mysqli->prepare("
        SELECT
            m.id,
            m.modelo,
            m.tipo,
            m.quantidade,
            m.estoque_anterior,
            m.estoque_posterior,
            m.responsavel,
            {$campoResponsavelEntrega}
            m.destino,
            m.observacao,
            m.usuario_sistema,
            m.criado_em,
            e.codigo_barras,
            e.estoque_minimo
        FROM tonner_movimentacoes AS m
        LEFT JOIN tonner_estoque AS e
          ON e.modelo = m.modelo
        WHERE m.id = ?
        LIMIT 1
    ");

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

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

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

    $itens[] = $movimento;
    $lote = [
        'id' => null,
        'codigo' => str_pad(
            (string) $movimentacaoId,
            7,
            '0',
            STR_PAD_LEFT
        ),
        'responsavel_retirada' => (string) (
            $movimento['responsavel'] ?? ''
        ),
        'responsavel_entrega' => (string) (
            $movimento['responsavel_entrega'] ??
            $movimento['usuario_sistema'] ??
            ''
        ),
        'destino' => (string) ($movimento['destino'] ?? ''),
        'usuario_sistema' => (string) (
            $movimento['usuario_sistema'] ?? ''
        ),
        'criado_em' => (string) ($movimento['criado_em'] ?? '')
    ];
} else {
    http_response_code(400);
    exit('Comprovante de toner inválido.');
}

if (empty($itens)) {
    http_response_code(404);
    exit('Nenhum item foi encontrado para este comprovante.');
}

$entrada = strtoupper((string) $itens[0]['tipo']) === 'ENTRADA';
$titulo = $entrada
    ? 'TERMO DE ENTRADA DE TONER'
    : 'TERMO DE SAÍDA / ENTREGA DE TONER';

$timestamp = strtotime((string) ($lote['criado_em'] ?? ''));
$data = $timestamp !== false ? date('d/m/Y', $timestamp) : 'Data inválida';
$hora = $timestamp !== false ? date('H:i:s', $timestamp) : '--:--:--';
$codigo = (string) ($lote['codigo'] ?? '');
$totalUnidades = array_sum(
    array_map(
        static fn(array $item): int => (int) $item['quantidade'],
        $itens
    )
);
$totalModelos = count($itens);
$imprimirAutomaticamente = ($_GET['print'] ?? '') === '1';
?>
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="theme-color" content="#08396f">
<title><?= e($titulo) ?> <?= e($codigo) ?></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;--primary-dark:#05294f;--green:#087f5b;--red:#bd263d;--text:#172438;--muted:#65758a;--border:#d8e1ea;--soft:#f5f8fb;--blue-soft:#eaf4fc}
*{box-sizing:border-box}html,body{min-height:100%}body{margin:0;padding:22px;font-family:"Inter",Arial,sans-serif;color:var(--text);background:#eaf0f5}.actions{width:100%;max-width:900px;display:flex;justify-content:flex-end;gap:8px;margin:0 auto 13px}.action{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(--primary);cursor:pointer;font-size:9px;font-weight:850;text-decoration:none}.action.secondary{color:var(--primary);border:1px solid #cbd8e4;background:#fff}.sheet{width:100%;max-width:900px;min-height:1120px;display:flex;flex-direction:column;margin:auto;padding:34px 40px 27px;background:#fff;box-shadow:0 30px 80px rgba(8,57,111,.16)}.top-line{height:6px;margin:-34px -40px 21px;background:linear-gradient(90deg,var(--primary) 0 65%,var(--green) 65% 90%,#e8ad16 90%)}.header{display:flex;align-items:center;justify-content:space-between;gap:18px;padding-bottom:15px;border-bottom:2px solid var(--primary)}.brand{min-width:0;display:flex;align-items:center;gap:13px}.logo,.fallback{width:64px;height:64px;flex:0 0 64px}.logo{object-fit:contain}.fallback{display:none;place-items:center;border-radius:17px;color:var(--primary);background:var(--soft);font-size:28px}.government{color:var(--primary);font-size:8px;font-weight:900;letter-spacing:.65px;text-transform:uppercase}.department{margin-top:4px;font-size:15px;font-weight:900}.subtitle{margin-top:3px;color:var(--muted);font-size:8px}.document-code{text-align:right}.document-code span{display:block;color:var(--muted);font-size:6px;font-weight:850;text-transform:uppercase}.document-code strong{display:block;margin-top:4px;color:var(--primary);font-size:15px}.document-code .date{margin-top:6px;font-size:7px;text-transform:none}.title{margin:17px 0 5px;text-align:center;font-size:17px;letter-spacing:.25px}.description{max-width:700px;margin:0 auto 12px;text-align:center;color:var(--muted);font-size:7.5px;line-height:1.5}.summary{display:grid;grid-template-columns:repeat(4,1fr);gap:7px;margin-top:14px}.summary-card{padding:9px 10px;border:1px solid var(--border);border-radius:11px;background:var(--soft)}.summary-card span{display:block;color:var(--muted);font-size:5.5px;font-weight:850;letter-spacing:.45px;text-transform:uppercase}.summary-card strong{display:block;margin-top:4px;font-size:8px;line-height:1.3}.section{margin-top:13px}.section-title{display:flex;align-items:center;gap:6px;margin-bottom:6px;color:var(--primary);font-size:7px;font-weight:900;letter-spacing:.45px;text-transform:uppercase}.items-table{width:100%;border-collapse:separate;border-spacing:0;overflow:hidden;border:1px solid var(--border);border-radius:12px;font-size:7px}.items-table th{padding:7px 8px;color:#607086;background:#f2f6f9;font-size:5.5px;font-weight:900;letter-spacing:.4px;text-transform:uppercase;text-align:left}.items-table td{padding:7px 8px;border-top:1px solid var(--border);vertical-align:top}.items-table td strong{font-size:7.5px}.qty{display:inline-flex;min-width:27px;justify-content:center;padding:4px 6px;border-radius:8px;color:#fff;background:var(--primary);font-weight:900}.stock{white-space:nowrap;color:var(--muted)}.observation{color:var(--muted);line-height:1.35}.declaration{margin-top:13px;padding:10px 12px;border:1px solid var(--border);border-radius:12px;background:var(--soft);font-size:7px;line-height:1.55;text-align:justify}.bottom-area{display:flex;flex:1 1 auto;flex-direction:column;justify-content:flex-end}.signatures{display:grid;grid-template-columns:1fr 1fr;gap:44px;margin-top:58px}.signature{text-align:center}.signature-line{padding-top:6px;border-top:1px solid #4b596b;font-size:8px;font-weight:800}.signature small{display:block;margin-top:3px;color:var(--muted);font-size:6px}.protocol{display:flex;justify-content:space-between;gap:18px;margin-top:30px;padding-top:9px;border-top:1px dashed #aab7c4;color:var(--muted);font-size:5.8px;line-height:1.4}.protocol strong{color:var(--text)}.print-note{margin-top:10px;text-align:center;color:var(--muted);font-size:5.5px}
@media(max-width:700px){body{padding:0;background:#fff}.actions{position:sticky;top:0;z-index:10;margin:0;padding:9px;border-bottom:1px solid var(--border);background:#fff}.sheet{min-height:0;padding:22px 15px;box-shadow:none}.top-line{margin:-22px -15px 18px}.header{align-items:flex-start}.logo,.fallback{width:50px;height:50px;flex-basis:50px}.document-code strong{font-size:12px}.summary{grid-template-columns:1fr 1fr}.items-table{display:block;overflow:auto}.signatures{grid-template-columns:1fr;gap:60px}.protocol{flex-direction:column}}
@media print{@page{size:A4 portrait;margin:7mm}html,body{width:100%;height:auto;margin:0;padding:0;background:#fff}.actions,.print-note{display:none!important}.sheet{width:100%;max-width:none;height:283mm;min-height:283mm;margin:0;padding:0;box-shadow:none}.top-line{height:5px;margin:0 0 12px}.header{padding-bottom:9px}.logo,.fallback{width:50px;height:50px;flex-basis:50px}.government{font-size:6px}.department{font-size:11px}.subtitle{font-size:6px}.document-code span{font-size:4.8px}.document-code strong{font-size:11px}.title{margin:10px 0 3px;font-size:14px}.description{margin-bottom:7px;font-size:6px}.summary{gap:5px;margin-top:8px}.summary-card{padding:6px 7px}.summary-card span{font-size:4.5px}.summary-card strong{font-size:6.5px}.section{margin-top:8px;break-inside:avoid}.section-title{margin-bottom:4px;font-size:5.8px}.items-table{font-size:5.7px}.items-table th{padding:5px 6px;font-size:4.5px}.items-table td{padding:5px 6px}.items-table td strong{font-size:6px}.qty{min-width:22px;padding:3px 5px}.declaration{margin-top:8px;padding:6px 8px;font-size:5.8px;line-height:1.4}.signatures{gap:36px;margin-top:auto;padding-top:28px}.signature-line{font-size:6px}.signature small{font-size:4.8px}.protocol{margin-top:19px;padding-top:6px;font-size:4.6px}}
</style>
</head>
<body>
<div class="actions">
<a href="tonner.php" class="action secondary"><i class="bi bi-arrow-left"></i>Voltar ao estoque</a>
<button type="button" class="action" onclick="window.print()"><i class="bi bi-printer-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 Institucional de Suprimentos de Impressão</div></div>
</div>
<div class="document-code"><span>Número do comprovante</span><strong><?= e($codigo) ?></strong><span class="date"><?= e($data) ?> às <?= e($hora) ?></span></div>
</header>
<h1 class="title"><?= e($titulo) ?></h1>
<p class="description">Documento institucional que reúne todos os modelos entregues na mesma operação, com baixa de estoque confirmada e rastreabilidade pelo usuário autenticado.</p>
<section class="summary">
<div class="summary-card"><span>Responsável pela retirada</span><strong><?= e($lote['responsavel_retirada'] ?: 'Não informado') ?></strong></div>
<div class="summary-card"><span>Responsável pela entrega</span><strong><?= e($lote['responsavel_entrega'] ?: 'Não informado') ?></strong></div>
<div class="summary-card"><span>Destino / setor</span><strong><?= e($lote['destino'] ?: 'Não informado') ?></strong></div>
<div class="summary-card"><span>Resumo da entrega</span><strong><?= $totalModelos ?> modelo(s) • <?= $totalUnidades ?> unidade(s)</strong></div>
</section>
<section class="section">
<div class="section-title"><i class="bi bi-printer-fill"></i>Modelos entregues</div>
<table class="items-table">
<thead><tr><th>#</th><th>Modelo</th><th>Quantidade</th><th>Estoque</th><th>Observação</th></tr></thead>
<tbody>
<?php foreach ($itens as $indice => $item): ?>
<tr>
<td><?= $indice + 1 ?></td>
<td><strong><?= e($item['modelo']) ?></strong><?php if (!empty($item['codigo_barras'])): ?><br><span class="observation">Cód. <?= e($item['codigo_barras']) ?></span><?php endif; ?></td>
<td><span class="qty"><?= (int) $item['quantidade'] ?></span></td>
<td class="stock"><?= (int) $item['estoque_anterior'] ?> → <strong><?= (int) $item['estoque_posterior'] ?></strong></td>
<td class="observation"><?= e($item['observacao'] ?: 'Sem observação') ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</section>
<div class="declaration">
<?php if ($entrada): ?>Declaro, para fins de controle interno, que os suprimentos de impressão acima identificados foram recebidos, conferidos e incorporados ao estoque da Gerência de Tecnologia nas quantidades descritas neste documento.<?php else: ?>Declaro, para fins de controle interno, que recebi todos os suprimentos de impressão relacionados neste comprovante, responsabilizando-me por sua correta destinação, instalação e utilização no serviço público municipal.<?php endif; ?>
</div>
<div class="bottom-area">
<section class="signatures">
<div class="signature"><div class="signature-line"><?= e($lote['responsavel_retirada'] ?: 'Responsável pela retirada') ?></div><small>Responsável pela retirada — assinatura</small></div>
<div class="signature"><div class="signature-line"><?= e($lote['responsavel_entrega'] ?: 'Servidor responsável') ?></div><small>Gerência de Tecnologia — assinatura</small></div>
</section>
<div class="protocol">
<div><strong>Comprovante:</strong> <?= e($codigo) ?><br><strong>Registro:</strong> <?= e($data) ?> às <?= e($hora) ?></div>
<div style="text-align:right"><strong>Itens:</strong> <?= $totalModelos ?> modelo(s) / <?= $totalUnidades ?> unidade(s)<br><strong>Usuário:</strong> <?= e($lote['usuario_sistema'] ?: 'Não informado') ?></div>
</div>
<p class="print-note">Documento gerado eletronicamente pelo Sistema de Manutenção TI.</p>
</div>
</main>
<?php if ($imprimirAutomaticamente): ?>
<script>window.addEventListener('load',()=>window.setTimeout(()=>window.print(),350));</script>
<?php endif; ?>
</body>
</html>
