<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Compra #<?= htmlspecialchars($compra['numero']) ?></title>
    <style>
        @page {
            size: A4;
            margin: 0;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html {
            height: 100%;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            font-size: 10pt;
            line-height: 1.4;
            color: #2c3e50;
            background: white;
            padding: 1.5cm;
            min-height: 100%;
            display: flex;
            flex-direction: column;
        }

        .documento {
            border: 2px solid #2c3e50;
            padding: 0;
            background: white;
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .documento-content {
            flex: 1;
        }

        /* Header */
        .header {
            background: #1e3c72;
            color: white;
            padding: 1rem 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .header-right {
            text-align: right;
        }

        .logo-empresa {
            max-width: 120px;
            max-height: 50px;
            background: white;
            padding: 0.25rem;
            border-radius: 4px;
        }

        .empresa-info-header {
            display: flex;
            flex-direction: column;
        }

        .empresa-nome {
            font-size: 14pt;
            font-weight: bold;
            margin-bottom: 0.1rem;
        }

        .empresa-cnpj {
            font-size: 8pt;
            opacity: 0.9;
        }

        .doc-tipo {
            font-size: 18pt;
            font-weight: bold;
            letter-spacing: 1px;
            margin-bottom: 0.25rem;
        }

        .doc-numero {
            font-size: 16pt;
            font-weight: bold;
        }

        /* Grid de Informações */
        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1px;
            background: #2c3e50;
            border-bottom: 2px solid #2c3e50;
        }

        .info-section {
            background: white;
            padding: 1rem;
        }

        .info-section-title {
            font-size: 9pt;
            font-weight: bold;
            color: #1e3c72;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 0.75rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #1e3c72;
        }

        .info-row {
            display: flex;
            margin-bottom: 0.5rem;
        }

        .info-label {
            font-weight: 600;
            color: #7f8c8d;
            font-size: 9pt;
            width: 120px;
            flex-shrink: 0;
        }

        .info-value {
            color: #2c3e50;
            font-size: 10pt;
            font-weight: 500;
        }

        /* Tabela de Itens */
        .section-title {
            background: #34495e;
            color: white;
            padding: 0.75rem 1rem;
            font-size: 11pt;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        table.itens {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 0;
        }

        table.itens thead {
            background: #2c3e50;
            color: white;
        }

        table.itens th {
            padding: 0.75rem;
            text-align: left;
            font-weight: 600;
            font-size: 9pt;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-right: 1px solid rgba(255, 255, 255, 0.2);
        }

        table.itens th:last-child {
            border-right: none;
        }

        table.itens td {
            padding: 0.75rem;
            border-bottom: 1px solid #ecf0f1;
            font-size: 9pt;
        }

        table.itens tbody tr:nth-child(even) {
            background: #f8f9fa;
        }

        table.itens tbody tr:hover {
            background: #e3f2fd;
        }

        .item-numero {
            background: #34495e;
            color: white;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 9pt;
        }

        .item-nome {
            font-weight: 600;
            color: #2c3e50;
            font-size: 10pt;
        }

        .item-sku {
            font-size: 8pt;
            color: #7f8c8d;
            font-style: italic;
        }

        /* Box de Totais */
        .totais-container {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 0;
            background: #2c3e50;
            margin-top: 0;
        }

        .observacoes-box {
            background: #ecf0f1;
            padding: 1rem;
        }

        .observacoes-title {
            font-size: 9pt;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 0.5rem;
            text-transform: uppercase;
        }

        .observacoes-text {
            font-size: 9pt;
            color: #34495e;
            line-height: 1.5;
        }

        .totais-box {
            background: white;
            padding: 1rem;
        }

        .total-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            font-size: 10pt;
        }

        .total-row-label {
            color: #7f8c8d;
            font-weight: 500;
        }

        .total-row-value {
            font-weight: 600;
            color: #2c3e50;
        }

        .total-final {
            border-top: 2px solid #1e3c72;
            margin-top: 0.5rem;
            padding-top: 0.5rem;
            background: #1e3c72;
            color: white;
            padding: 0.75rem 1rem;
            margin: 0.5rem -1rem -1rem -1rem;
        }

        .total-final .total-row-label {
            font-size: 10pt;
            font-weight: bold;
            color: white;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .total-final .total-row-value {
            font-size: 14pt;
            font-weight: bold;
            color: white;
        }

        /* Footer */
        .footer {
            margin-top: auto;
            padding: 1rem;
            background: #ecf0f1;
            border-top: 3px solid #2c3e50;
            page-break-inside: avoid;
        }

        .footer-grid {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 1.5rem;
            margin-bottom: 0.5rem;
        }

        .assinatura-box {
            text-align: center;
            padding-top: 3rem;
        }

        .assinatura-linha {
            border-top: 2px solid #2c3e50;
            margin: 0 1rem 0.5rem 1rem;
        }

        .assinatura-label {
            font-size: 7pt;
            color: #7f8c8d;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .footer-info {
            text-align: center;
            font-size: 7pt;
            color: #7f8c8d;
            padding-top: 0.5rem;
            border-top: 1px solid #bdc3c7;
        }

        .status-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 4px;
            font-size: 8pt;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .badge-orcamento {
            background: #3498db;
            color: white;
        }

        .badge-aprovado {
            background: #2ecc71;
            color: white;
        }

        .badge-faturado {
            background: #27ae60;
            color: white;
        }

        .badge-cancelado {
            background: #e74c3c;
            color: white;
        }

        .badge-pendente {
            background: #f39c12;
            color: white;
        }

        /* Impressão */
        @media print {

            html,
            body {
                height: 100%;
                margin: 0;
                padding: 0;
            }

            body {
                print-color-adjust: exact;
                -webkit-print-color-adjust: exact;
            }

            .no-print {
                display: none !important;
            }

            .documento {
                border: none;
                min-height: 100vh;
            }

            .documento-content {
                min-height: calc(100vh - 12cm);
            }
        }

        .no-print {
            position: fixed;
            top: 1rem;
            right: 1rem;
            z-index: 1000;
            background: white;
            padding: 0.5rem;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .btn {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 600;
            font-size: 10pt;
            margin: 0 0.25rem;
        }

        .btn-primary {
            background: #1e3c72;
            color: white;
        }

        .btn-secondary {
            background: #95a5a6;
            color: white;
        }

        .text-right {
            text-align: right;
        }

        .text-center {
            text-align: center;
        }
    </style>
</head>

<body>
    <!-- Botões (não imprime) -->
    <div class="no-print">
        <button onclick="window.print()" class="btn btn-primary">
            🖨 Imprimir
        </button>
        <button onclick="window.close()" class="btn btn-secondary">
            ✕ Fechar
        </button>
    </div>

    <div class="documento">
        <div class="documento-content">
            <!-- Header Corporativo -->
            <div class="header">
                <div class="header-left">
                    <?php
                    // Buscar logo da empresa (tenant)
                    $logoUrl = null;
                    if (!empty($empresa)) {
                        $logoPath = null;

                        // Tentar logo do campo logo
                        if (!empty($empresa['logo'])) {
                            $logoPath = $empresa['logo'];
                        }

                        // Verificar se existe logo por CNPJ (prioriza campo 'cnpj')
                        $cnpjLimpo = preg_replace('/\D/', '', $empresa['cnpj'] ?? ($empresa['document'] ?? ''));
                        if ($cnpjLimpo) {
                            $logoPorCnpj = 'storage/uploads/logos/' . $cnpjLimpo . '.jpg';
                            if (file_exists(ROOT_PATH . '/' . $logoPorCnpj)) {
                                $logoPath = $logoPorCnpj;
                            }
                        }

                        // Fallback para logo padrão
                        if (!$logoPath) {
                            $logoPadrao = 'storage/uploads/logo.png';
                            if (file_exists(ROOT_PATH . '/' . $logoPadrao)) {
                                $logoPath = $logoPadrao;
                            }
                        }

                        // Se encontrou logo, montar URL completa
                        if ($logoPath && file_exists(ROOT_PATH . '/' . $logoPath)) {
                            $logoUrl = \App\Helpers\UrlHelper::url('/' . $logoPath);
                        }
                    }
                    ?>
                    <?php if (!empty($logoUrl)): ?>
                        <img src="<?= $logoUrl ?>" alt="Logo" class="logo-empresa">
                    <?php endif; ?>
                    <div class="empresa-info-header">
                        <div class="empresa-nome">
                            <?php
                            if (!empty($empresa)) {
                                echo strtoupper(htmlspecialchars($empresa['razao_social'] ?? $empresa['nome'] ?? $empresa['name'] ?? 'EMPRESA'));
                            } else {
                                echo 'EMPRESA';
                            }
                            ?>
                        </div>
                        <?php if (!empty($empresa) && (!empty($empresa['cnpj']) || !empty($empresa['document']))): ?>
                            <div class="empresa-cnpj">CNPJ:
                                <?= htmlspecialchars($empresa['cnpj'] ?? $empresa['document']) ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="header-right">
                    <div class="doc-tipo">COMPRA</div>
                    <div class="doc-numero">#<?= htmlspecialchars($compra['numero']) ?></div>
                </div>
            </div>

            <!-- Grid de Informações Principais -->
            <div class="info-grid">
                <!-- Dados do Fornecedor -->
                <div class="info-section">
                    <div class="info-section-title">📋 DADOS DO FORNECEDOR</div>
                    <div class="info-row">
                        <span class="info-label">Nome/Razão:</span>
                        <span class="info-value"><?= htmlspecialchars($fornecedor['name'] ?? 'Não informado') ?></span>
                    </div>
                    <?php if (!empty($fornecedor['trade_name'])): ?>
                        <div class="info-row">
                            <span class="info-label">Nome Fantasia:</span>
                            <span class="info-value"><?= htmlspecialchars($fornecedor['trade_name']) ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($fornecedor['document'])): ?>
                        <div class="info-row">
                            <span class="info-label">CPF/CNPJ:</span>
                            <span class="info-value"><?= htmlspecialchars($fornecedor['document'] ?? '') ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($fornecedor['rg_ie'])): ?>
                        <div class="info-row">
                            <span class="info-label">RG/IE:</span>
                            <span class="info-value"><?= htmlspecialchars($fornecedor['rg_ie']) ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($fornecedor['email'])): ?>
                        <div class="info-row">
                            <span class="info-label">Email:</span>
                            <span class="info-value"><?= htmlspecialchars($fornecedor['email']) ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($fornecedor['mobile']) || !empty($fornecedor['phone'])): ?>
                        <div class="info-row">
                            <span class="info-label">Telefone:</span>
                            <span
                                class="info-value"><?= htmlspecialchars($fornecedor['mobile'] ?? $fornecedor['phone'] ?? '') ?></span>
                        </div>
                    <?php endif; ?>

                    <!-- Endereço -->
                    <?php if (!empty($fornecedor['address'])): ?>
                        <div class="info-row"
                            style="margin-top: 0.75rem; padding-top: 0.75rem; border-top: 1px solid #ecf0f1;">
                            <span class="info-label">Endereço:</span>
                            <span class="info-value">
                                <?= htmlspecialchars($fornecedor['address'] ?? '') ?>
                                <?php if (!empty($fornecedor['numero'])): ?>
                                    , <?= htmlspecialchars($fornecedor['numero'] ?? '') ?>
                                <?php endif; ?>
                                <?php if (!empty($fornecedor['complemento'])): ?>
                                    - <?= htmlspecialchars($fornecedor['complemento'] ?? '') ?>
                                <?php endif; ?>
                            </span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Cidade/UF:</span>
                            <span class="info-value">
                                <?= htmlspecialchars($fornecedor['city'] ?? '') ?>
                                <?php if (!empty($fornecedor['state'])): ?>
                                    / <?= htmlspecialchars($fornecedor['state'] ?? '') ?>
                                <?php endif; ?>
                                <?php if (!empty($fornecedor['zip_code'])): ?>
                                    - CEP: <?= htmlspecialchars($fornecedor['zip_code'] ?? '') ?>
                                <?php endif; ?>
                            </span>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Dados da Compra -->
                <div class="info-section">
                    <div class="info-section-title">📊 INFORMAÇÕES DA COMPRA</div>
                    <div class="info-row">
                        <span class="info-label">Status:</span>
                        <span class="info-value">
                            <?php
                            // Buscar status dinâmico
                            $statusAtual = null;
                            $statusCompras = $statusCompras ?? [];

                            if (is_array($statusCompras) && !empty($statusCompras)) {
                                foreach ($statusCompras as $st) {
                                    if ($st['codigo'] === $compra['status']) {
                                        $statusAtual = $st;
                                        break;
                                    }
                                }
                            }

                            if ($statusAtual) {
                                $cor = $statusAtual['cor'] ?? 'secondary';
                                $nome = $statusAtual['nome'] ?? $compra['status'];
                                $icone = $statusAtual['icone'] ?? '';
                                $iconeHtml = $icone ? "<i class=\"bi bi-{$icone} me-1\"></i>" : '';
                                echo "<span class=\"status-badge badge-{$cor}\">{$iconeHtml}{$nome}</span>";
                            } else {
                                // Fallback
                                echo "<span class=\"status-badge badge-secondary\">" . strtoupper($compra['status'] ?? 'N/A') . "</span>";
                            }
                            ?>
                        </span>
                    </div>
                    <?php if (!empty($compra['data_compra'])): ?>
                        <div class="info-row">
                            <span class="info-label">Data Compra:</span>
                            <span class="info-value"><?= date('d/m/Y', strtotime($compra['data_compra'])) ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($compra['data_entrega'])): ?>
                        <div class="info-row">
                            <span class="info-label">Prev. Entrega:</span>
                            <span class="info-value"><?= date('d/m/Y', strtotime($compra['data_entrega'])) ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($usuario)): ?>
                        <div class="info-row">
                            <span class="info-label">Comprador:</span>
                            <span class="info-value"><?= htmlspecialchars($usuario['name']) ?></span>
                        </div>
                    <?php endif; ?>
                    <div class="info-row">
                        <span class="info-label">Data Cadastro:</span>
                        <span
                            class="info-value"><?= date('d/m/Y H:i', strtotime($compra['created_at'] ?? $compra['data_compra'])) ?></span>
                    </div>
                </div>
            </div>

            <!-- Itens da Compra -->
            <div class="section-title">ITENS DA COMPRA</div>
            <table class="itens">
                <thead>
                    <tr>
                        <th width="40">#</th>
                        <th width="80">CÓDIGO</th>
                        <th>DESCRIÇÃO DO PRODUTO</th>
                        <th width="80" class="text-center">UNID.</th>
                        <th width="100" class="text-right">QTD</th>
                        <th width="120" class="text-right">VALOR UNIT.</th>
                        <th width="120" class="text-right">TOTAL</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($itens as $index => $item): ?>
                        <tr>
                            <td class="text-center">
                                <span class="item-numero"><?= $index + 1 ?></span>
                            </td>
                            <td>
                                <?php
                                $codigo = $item['item_code'] ?? $item['code'] ?? $item['sku'] ?? '-';
                                echo htmlspecialchars($codigo);
                                ?>
                            </td>
                            <td>
                                <div class="item-nome">
                                    <?php
                                    $nome = $item['item_name'] ?? $item['name'] ?? 'Item sem nome';
                                    echo htmlspecialchars($nome);
                                    ?>
                                </div>
                                <?php if (!empty($item['notes'])): ?>
                                    <div class="item-sku">Obs: <?= htmlspecialchars($item['notes']) ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="text-center"><?= htmlspecialchars($item['unit'] ?? 'UN') ?></td>
                            <td class="text-right"><?= number_format($item['quantity'], 3, ',', '.') ?></td>
                            <td class="text-right">R$ <?= number_format($item['unit_price'], 2, ',', '.') ?></td>
                            <td class="text-right"><strong>R$
                                    <?= number_format($item['total'], 2, ',', '.') ?></strong>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <!-- Totais e Observações -->
            <div class="totais-container">
                <!-- Observações -->
                <div class="observacoes-box">
                    <div class="observacoes-title">💬 OBSERVAÇÕES</div>
                    <div class="observacoes-text">
                        <?php if (!empty($compra['notes'])): ?>
                            <?= nl2br(htmlspecialchars($compra['notes'])) ?>
                        <?php else: ?>
                            <em style="color: #95a5a6;">Nenhuma observação registrada</em>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Totais -->
                <div class="totais-box">
                    <div class="total-row">
                        <span class="total-row-label">Subtotal:</span>
                        <span class="total-row-value">R$
                            <?= number_format($compra['subtotal'] ?? 0, 2, ',', '.') ?></span>
                    </div>
                    <?php if (($compra['discount'] ?? 0) > 0): ?>
                        <div class="total-row">
                            <span class="total-row-label">Desconto:</span>
                            <span class="total-row-value" style="color: #e74c3c;">- R$
                                <?= number_format($compra['discount'], 2, ',', '.') ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (($compra['shipping'] ?? 0) > 0): ?>
                        <div class="total-row">
                            <span class="total-row-label">Frete:</span>
                            <span class="total-row-value">R$ <?= number_format($compra['shipping'], 2, ',', '.') ?></span>
                        </div>
                    <?php endif; ?>
                    <div class="total-final">
                        <div class="total-row">
                            <span class="total-row-label">Valor Total</span>
                            <span class="total-row-value">R$ <?= number_format($compra['total'], 2, ',', '.') ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer com Assinaturas -->
        <div class="footer">
            <div class="footer-grid">
                <div class="assinatura-box">
                    <div class="assinatura-linha"></div>
                    <div class="assinatura-label">Comprador</div>
                    <div style="font-size: 9pt; font-weight: 600; color: #2c3e50; margin-top: 0.25rem;">
                        <?= htmlspecialchars($usuario['name'] ?? '-') ?>
                    </div>
                </div>
                <div class="assinatura-box">
                    <div class="assinatura-linha"></div>
                    <div class="assinatura-label">Fornecedor</div>
                    <div style="font-size: 9pt; font-weight: 600; color: #2c3e50; margin-top: 0.25rem;">
                        <?= htmlspecialchars($fornecedor['name'] ?? 'Não informado') ?>
                    </div>
                </div>
                <div class="assinatura-box">
                    <div class="assinatura-linha"></div>
                    <div class="assinatura-label">Resp. Recebimento</div>
                </div>
            </div>
            <div class="footer-info">
                Documento gerado automaticamente pelo ERP Aurion em <?= date('d/m/Y H:i:s') ?><br>
                Este documento não possui valor fiscal. Para emissão de NF-e, utilize a opção correspondente no sistema.
            </div>
        </div>
    </div>

    <script>
        // Auto-imprimir ao carregar (com pequeno delay para renderização)
        window.onload = function () {
            setTimeout(function () {
                window.print();
            }, 800);
        };
    </script>
</body>

</html>