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

<head>
    <meta charset="UTF-8">
    <title>Cupom #<?= htmlspecialchars($venda['sale_number'] ?? '') ?></title>
    <style>
        @page {
            size: 80mm auto;
            margin: 0;
        }

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

        body {
            font-family: 'Segoe UI', 'Arial', sans-serif;
            font-size: 11px;
            line-height: 1.4;
            width: 80mm;
            background: white;
            color: #1a1a1a;
        }

        .cupom {
            width: 100%;
            padding: 4mm;
        }

        /* Header com Logo */
        .header {
            text-align: center;
            padding-bottom: 10px;
            margin-bottom: 0;
        }

        .logo {
            max-width: 50mm;
            max-height: 18mm;
            margin-bottom: 6px;
        }

        .empresa-nome {
            font-size: 14px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: #000;
        }

        .empresa-info {
            font-size: 9px;
            margin-top: 5px;
            line-height: 1.5;
            color: #333;
        }

        .empresa-info span {
            display: block;
        }

        /* Tarja/Banner - Estilo moderno */
        .tarja {
            background: linear-gradient(135deg, #1a1a1a 0%, #333 100%);
            color: #fff;
            text-align: center;
            font-weight: 700;
            font-size: 11px;
            padding: 6px 8px;
            margin: 8px -4mm;
            letter-spacing: 1.5px;
            text-transform: uppercase;
        }

        .tarja-secundaria {
            background: linear-gradient(135deg, #444 0%, #666 100%);
            color: #fff;
            text-align: center;
            font-weight: 600;
            font-size: 10px;
            padding: 5px 8px;
            margin: 6px -4mm;
            letter-spacing: 1px;
        }

        .tarja-destaque {
            background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
            color: #fff;
            text-align: center;
            font-weight: 700;
            font-size: 12px;
            padding: 8px;
            margin: 8px -4mm;
            letter-spacing: 1px;
        }

        /* Info Venda */
        .info-venda {
            padding: 10px 0;
        }

        .info-linha {
            display: flex;
            justify-content: space-between;
            margin-bottom: 4px;
            font-size: 10px;
        }

        .info-linha:last-child {
            margin-bottom: 0;
        }

        .info-linha strong {
            color: #000;
        }

        .info-label {
            color: #555;
        }

        /* Itens */
        .itens-header {
            display: flex;
            justify-content: space-between;
            font-weight: 700;
            font-size: 9px;
            padding: 8px 0 6px;
            border-bottom: 2px solid #000;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #333;
        }

        .itens {
            padding: 8px 0;
        }

        .item {
            margin-bottom: 10px;
            padding-bottom: 8px;
            border-bottom: 1px dotted #ccc;
        }

        .item:last-child {
            margin-bottom: 0;
            border-bottom: none;
            padding-bottom: 0;
        }

        .item-nome {
            display: block;
            font-weight: 600;
            font-size: 10px;
            margin-bottom: 3px;
            word-wrap: break-word;
            color: #000;
        }

        .item-detalhes {
            display: flex;
            justify-content: space-between;
            font-size: 10px;
            color: #444;
        }

        .item-detalhes strong {
            color: #000;
            font-size: 11px;
        }

        /* Totais */
        .totais {
            padding: 10px 0;
            background: #f8f8f8;
            margin: 0 -4mm;
            padding-left: 4mm;
            padding-right: 4mm;
        }

        .total-linha {
            display: flex;
            justify-content: space-between;
            font-size: 11px;
            margin-bottom: 4px;
            color: #333;
        }

        .total-linha.destaque {
            font-size: 16px;
            font-weight: 700;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 2px solid #000;
            color: #000;
        }

        .total-linha.desconto {
            color: #dc2626;
        }

        /* Pagamento */
        .pagamento {
            padding: 10px 0;
        }

        .pagamento-metodo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            font-size: 12px;
            padding: 8px;
            background: #f0f9ff;
            border: 1px solid #bae6fd;
            border-radius: 4px;
            margin-top: 5px;
        }

        .pagamento-metodo strong {
            color: #0369a1;
        }

        .pagamento-icon {
            font-size: 14px;
        }

        /* Footer */
        .footer {
            text-align: center;
            padding: 12px 0 8px;
        }

        .footer-msg {
            font-weight: 700;
            font-size: 12px;
            margin-bottom: 4px;
            color: #000;
        }

        .footer-sub-msg {
            font-size: 11px;
            color: #444;
            margin-bottom: 8px;
        }

        .footer-info {
            font-size: 9px;
            color: #666;
            padding-top: 8px;
            border-top: 1px solid #ddd;
        }

        .footer-info .datetime {
            font-weight: 600;
            color: #333;
        }

        .footer-info .brand {
            margin-top: 4px;
            font-style: italic;
        }

        /* QR Code / PIX info */
        .pix-info {
            text-align: center;
            padding: 10px;
            background: #ecfdf5;
            border: 1px solid #a7f3d0;
            border-radius: 4px;
            margin: 8px 0;
        }

        .pix-info strong {
            color: #047857;
            font-size: 10px;
        }

        /* Decorativo */
        .divisor {
            height: 1px;
            background: linear-gradient(to right, transparent, #ccc, transparent);
            margin: 8px 0;
        }

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

            .tarja,
            .tarja-secundaria,
            .tarja-destaque,
            .totais,
            .pagamento-metodo {
                print-color-adjust: exact;
                -webkit-print-color-adjust: exact;
            }
        }
    </style>
</head>

<body>
    <div class="cupom">
        <!-- Header com Logo -->
        <div class="header">
            <?php
            // Buscar logo da empresa pelo CNPJ
            $cnpjLimpo = preg_replace('/\D/', '', $empresa['cnpj'] ?? '');
            $logoPath = '';

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

            // 2. Fallback: logo por CNPJ no storage
            if (empty($logoPath) && !empty($cnpjLimpo)) {
                $rootPath = defined('ROOT_PATH') ? ROOT_PATH : dirname(__DIR__, 2);
                $extensoes = ['jpg', 'jpeg', 'png', 'gif'];
                foreach ($extensoes as $ext) {
                    $arquivo = "storage/uploads/logos/{$cnpjLimpo}.{$ext}";
                    if (file_exists($rootPath . '/' . $arquivo)) {
                        $logoPath = $arquivo;
                        break;
                    }
                }
            }

            // 3. Montar URL completa
            if (!empty($logoPath)) {
                // Se já tem http, usar direto
                if (strpos($logoPath, 'http') === 0) {
                    $logoUrl = $logoPath;
                } else {
                    // Montar URL relativa à raiz do projeto
                    $scriptDir = dirname($_SERVER['SCRIPT_NAME']);
                    $baseUrl = rtrim($scriptDir, '/');
                    $logoUrl = $baseUrl . '/' . ltrim($logoPath, '/');
                }
            } else {
                $logoUrl = '';
            }
            ?>
            <?php if (!empty($logoUrl)): ?>
                <img src="<?= htmlspecialchars($logoUrl) ?>" alt="Logo" class="logo">
            <?php endif; ?>

            <div class="empresa-nome">
                <?= htmlspecialchars($empresa['nome_fantasia'] ?? $empresa['razao_social'] ?? 'EMPRESA') ?>
            </div>

            <div class="empresa-info">
                <?php if (!empty($empresa['cnpj'])): ?>
                    <span>CNPJ: <?= htmlspecialchars($empresa['cnpj']) ?></span>
                <?php endif; ?>
                <?php if (!empty($empresa['endereco'])): ?>
                    <span><?= htmlspecialchars($empresa['endereco']) ?><?= !empty($empresa['numero']) ? ', ' . $empresa['numero'] : '' ?></span>
                <?php endif; ?>
                <?php if (!empty($empresa['bairro']) || !empty($empresa['cidade'])): ?>
                    <span>
                        <?= htmlspecialchars($empresa['bairro'] ?? '') ?>
                        <?= (!empty($empresa['bairro']) && !empty($empresa['cidade'])) ? ' - ' : '' ?>
                        <?= htmlspecialchars($empresa['cidade'] ?? '') ?>/<?= htmlspecialchars($empresa['uf'] ?? '') ?>
                    </span>
                <?php endif; ?>
                <?php if (!empty($empresa['telefone'])): ?>
                    <span>Tel: <?= htmlspecialchars($empresa['telefone']) ?></span>
                <?php endif; ?>
            </div>
        </div>

        <!-- Tarja Principal -->
        <div class="tarja">📋 Cupom Não Fiscal</div>

        <!-- Info Venda -->
        <div class="info-venda">
            <div class="info-linha">
                <span class="info-label">Nº Venda:</span>
                <strong><?= htmlspecialchars($venda['sale_number'] ?? '-') ?></strong>
            </div>
            <div class="info-linha">
                <span class="info-label">Data/Hora:</span>
                <strong><?= date('d/m/Y H:i', strtotime($venda['created_at'] ?? $venda['sale_date'] ?? 'now')) ?></strong>
            </div>
            <?php if (!empty($venda['cliente_nome'])): ?>
                <div class="info-linha">
                    <span class="info-label">Cliente:</span>
                    <strong><?= htmlspecialchars($venda['cliente_nome']) ?></strong>
                </div>
            <?php endif; ?>
            <?php if (!empty($venda['cliente_documento'])): ?>
                <div class="info-linha">
                    <span class="info-label">CPF/CNPJ:</span>
                    <strong><?= htmlspecialchars($venda['cliente_documento']) ?></strong>
                </div>
            <?php endif; ?>
        </div>

        <!-- Tarja Itens -->
        <div class="tarja-secundaria">🛒 Itens do Pedido</div>

        <!-- Cabeçalho Itens -->
        <div class="itens-header">
            <span>Descrição</span>
            <span>Valor</span>
        </div>

        <!-- Itens -->
        <div class="itens">
            <?php foreach ($itens as $item): ?>
                <div class="item">
                    <span class="item-nome"><?= htmlspecialchars($item['product_name']) ?></span>
                    <div class="item-detalhes">
                        <span><?= number_format($item['quantity'], 2, ',', '.') ?> × R$
                            <?= number_format($item['unit_price'], 2, ',', '.') ?></span>
                        <strong>R$ <?= number_format($item['total_price'], 2, ',', '.') ?></strong>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Totais -->
        <div class="totais">
            <div class="total-linha">
                <span>Subtotal:</span>
                <span>R$ <?= number_format($venda['subtotal'], 2, ',', '.') ?></span>
            </div>
            <?php if ($venda['discount'] > 0): ?>
                <div class="total-linha desconto">
                    <span>Desconto:</span>
                    <span>- R$ <?= number_format($venda['discount'], 2, ',', '.') ?></span>
                </div>
            <?php endif; ?>
            <div class="total-linha destaque">
                <span>TOTAL</span>
                <span>R$ <?= number_format($venda['total'], 2, ',', '.') ?></span>
            </div>
        </div>

        <!-- Tarja Pagamento -->
        <div class="tarja-secundaria">💳 Pagamento</div>

        <!-- Pagamento -->
        <div class="pagamento">
            <div class="pagamento-metodo">
                <?php
                $metodoNome = strtolower($venda['metodo_nome'] ?? '');
                $icon = '💵';
                if (strpos($metodoNome, 'pix') !== false)
                    $icon = '📱';
                elseif (strpos($metodoNome, 'cartao') !== false || strpos($metodoNome, 'credito') !== false || strpos($metodoNome, 'debito') !== false)
                    $icon = '💳';
                elseif (strpos($metodoNome, 'boleto') !== false)
                    $icon = '📄';
                ?>
                <span class="pagamento-icon"><?= $icon ?></span>
                <strong><?= htmlspecialchars($venda['metodo_nome'] ?? 'Não informado') ?></strong>
            </div>

            <?php if (!empty($venda['troco']) && $venda['troco'] > 0): ?>
                <div class="info-linha" style="margin-top: 8px;">
                    <span class="info-label">Valor Recebido:</span>
                    <strong>R$
                        <?= number_format($venda['valor_recebido'] ?? $venda['total'] + $venda['troco'], 2, ',', '.') ?></strong>
                </div>
                <div class="info-linha">
                    <span class="info-label">Troco:</span>
                    <strong style="color: #059669;">R$ <?= number_format($venda['troco'], 2, ',', '.') ?></strong>
                </div>
            <?php endif; ?>
        </div>

        <div class="divisor"></div>

        <!-- Footer -->
        <div class="footer">
            <div class="footer-msg">✨ Obrigado pela preferência!</div>
            <div class="footer-sub-msg">Volte sempre!</div>

            <div class="footer-info">
                <div class="datetime"><?= date('d/m/Y H:i:s') ?></div>
                <div class="brand">Systhema ERP</div>
            </div>
        </div>
    </div>

    <script>
        // Impressão automática
        window.onload = function () {
            window.print();
        };
    </script>
</body>

</html>