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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pedido #<?= htmlspecialchars($venda['sale_number']) ?></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: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            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)
                    $logoPath = 'storage/uploads/logo.png';
                    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 && file_exists(ROOT_PATH . '/storage/uploads/logos/' . $cnpjLimpo . '.jpg')) {
                        $logoPath = 'storage/uploads/logos/' . $cnpjLimpo . '.jpg';
                    }
                    ?>
                    <?php if (file_exists(ROOT_PATH . '/' . $logoPath)): ?>
                        <img src="<?= asset($logoPath) ?>" alt="Logo" class="logo-empresa">
                    <?php endif; ?>
                    <div class="empresa-info-header">
                        <div class="empresa-nome">
                            <?= strtoupper(htmlspecialchars($empresa['razao_social'] ?? $empresa['nome'] ?? $empresa['name'] ?? 'EMPRESA')) ?>
                        </div>
                        <?php if (!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">PEDIDO</div>
                    <div class="doc-numero">#<?= htmlspecialchars($venda['sale_number']) ?></div>
                </div>
            </div>

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

                    <!-- Endereço de Entrega -->
                    <?php if (!empty($venda['delivery_street']) || !empty($cliente['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($venda['delivery_street'] ?? $cliente['address'] ?? '') ?>
                                <?php if (!empty($venda['delivery_number']) || !empty($cliente['numero'])): ?>
                                    , <?= htmlspecialchars($venda['delivery_number'] ?? $cliente['numero'] ?? '') ?>
                                <?php endif; ?>
                                <?php if (!empty($venda['delivery_complement']) || !empty($cliente['complemento'])): ?>
                                    - <?= htmlspecialchars($venda['delivery_complement'] ?? $cliente['complemento'] ?? '') ?>
                                <?php endif; ?>
                            </span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">Cidade/UF:</span>
                            <span class="info-value">
                                <?= htmlspecialchars($venda['delivery_city'] ?? $cliente['city'] ?? '') ?>
                                <?php if (!empty($venda['delivery_state']) || !empty($cliente['state'])): ?>
                                    / <?= htmlspecialchars($venda['delivery_state'] ?? $cliente['state'] ?? '') ?>
                                <?php endif; ?>
                                <?php if (!empty($venda['delivery_zip']) || !empty($cliente['zip_code'])): ?>
                                    - CEP: <?= htmlspecialchars($venda['delivery_zip'] ?? $cliente['zip_code'] ?? '') ?>
                                <?php endif; ?>
                            </span>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Dados do Pedido -->
                <div class="info-section">
                    <div class="info-section-title">📊 INFORMAÇÕES DO PEDIDO</div>
                    <div class="info-row">
                        <span class="info-label">Status:</span>
                        <span class="info-value">
                            <span class="status-badge badge-<?= strtolower($venda['status']) ?>">
                                <?= strtoupper($venda['status']) ?>
                            </span>
                        </span>
                    </div>
                    <?php if (!empty($metodoPagamento)): ?>
                        <div class="info-row">
                            <span class="info-label">Forma Pagto:</span>
                            <span class="info-value"><?= htmlspecialchars($metodoPagamento['name']) ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($venda['installments']) && $venda['installments'] > 1): ?>
                        <div class="info-row">
                            <span class="info-label">Parcelas:</span>
                            <span class="info-value"><?= $venda['installments'] ?>x</span>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($vendedor)): ?>
                        <div class="info-row">
                            <span class="info-label">Vendedor:</span>
                            <span class="info-value"><?= htmlspecialchars($vendedor['name']) ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (!empty($venda['numero_nfe'])): ?>
                        <div class="info-row">
                            <span class="info-label">NF-e:</span>
                            <span class="info-value"><?= htmlspecialchars($venda['numero_nfe']) ?></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($venda['created_at'] ?? $venda['sale_date'])) ?></span>
                    </div>
                </div>
            </div>

            <!-- Itens do Pedido -->
            <div class="section-title">ITENS DO PEDIDO</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><?= htmlspecialchars($item['product_sku'] ?? '-') ?></td>
                            <td>
                                <div class="item-nome"><?= htmlspecialchars($item['product_name']) ?></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_price'], 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($venda['notes'])): ?>
                            <?= nl2br(htmlspecialchars($venda['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($venda['subtotal'] ?? 0, 2, ',', '.') ?></span>
                    </div>
                    <?php if (($venda['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($venda['discount'], 2, ',', '.') ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (($venda['shipping'] ?? 0) > 0): ?>
                        <div class="total-row">
                            <span class="total-row-label">Frete:</span>
                            <span class="total-row-value">R$ <?= number_format($venda['shipping'], 2, ',', '.') ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if (($venda['additions'] ?? 0) > 0): ?>
                        <div class="total-row">
                            <span class="total-row-label">Acréscimos:</span>
                            <span class="total-row-value">R$ <?= number_format($venda['additions'], 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($venda['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">Vendedor</div>
                    <div style="font-size: 9pt; font-weight: 600; color: #2c3e50; margin-top: 0.25rem;">
                        <?= htmlspecialchars($vendedor['name'] ?? '-') ?>
                    </div>
                </div>
                <div class="assinatura-box">
                    <div class="assinatura-linha"></div>
                    <div class="assinatura-label">Cliente</div>
                    <div style="font-size: 9pt; font-weight: 600; color: #2c3e50; margin-top: 0.25rem;">
                        <?= htmlspecialchars($venda['customer_name'] ?? ($cliente['name'] ?? 'Consumidor Final')) ?>
                    </div>
                </div>
                <div class="assinatura-box">
                    <div class="assinatura-linha"></div>
                    <div class="assinatura-label">Recebedor</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>