<?php
// Garantir que as funções helper estejam disponíveis
if (!function_exists('asset')) {
    require_once __DIR__ . '/../../src/Helpers/GlobalHelpers.php';
}
?>
<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Romaneio de Separação #<?= 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;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .qrcode-container {
            background: white;
            padding: 0.5rem;
            border-radius: 4px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .qrcode-img {
            width: 80px;
            height: 80px;
            display: block;
        }

        .qrcode-label {
            font-size: 7pt;
            margin-top: 0.25rem;
            opacity: 0.9;
        }

        .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 Observações */
        .observacoes-container {
            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;
        }

        /* 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;
            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;
        }

        /* 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>
                        <div class="doc-tipo">ROMANEIO DE SEPARAÇÃO</div>
                        <div class="doc-numero">#<?= htmlspecialchars($venda['sale_number']) ?></div>
                    </div>
                    <div class="qrcode-container">
                        <img src="https://api.qrserver.com/v1/create-qr-code/?size=80x80&data=<?= urlencode($venda['id']) ?>"
                            alt="QR Code" class="qrcode-img">
                        <div class="qrcode-label">ID: <?= $venda['id'] ?></div>
                    </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">Razão Social:</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">CNPJ:</span>
                            <span
                                class="info-value"><?= htmlspecialchars($venda['customer_document'] ?? $cliente['document'] ?? '') ?></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">Número:</span>
                        <span class="info-value"><strong><?= htmlspecialchars($venda['sale_number']) ?></strong></span>
                    </div>
                    <?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; ?>
                    <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 class="info-row">
                        <span class="info-label">Total Itens:</span>
                        <span class="info-value"><strong><?= count($itens) ?></strong></span>
                    </div>
                </div>
            </div>

            <!-- Itens para Separação -->
            <div class="section-title">ITENS PARA SEPARAÇÃO</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-center">QTD</th>
                        <th width="120" class="text-center">ENDEREÇO ESTOQUE</th>
                        <th width="100" class="text-center">LOTE</th>
                        <th width="100" class="text-center">VALIDADE</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-center"><strong><?= number_format($item['quantity'], 3, ',', '.') ?></strong>
                            </td>
                            <td class="text-center">
                                <?= !empty($item['stock_address']) ? htmlspecialchars($item['stock_address']) : '-' ?>
                            </td>
                            <td class="text-center"><?= htmlspecialchars($item['lote'] ?? '-') ?></td>
                            <td class="text-center">
                                <?php if (!empty($item['validade'])): ?>
                                    <?= date('d/m/Y', strtotime($item['validade'])) ?>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <!-- Observações -->
            <div class="observacoes-container">
                <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>
            </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">Separador</div>
                </div>
                <div class="assinatura-box">
                    <div class="assinatura-linha"></div>
                    <div class="assinatura-label">Conferente</div>
                </div>
            </div>
            <div class="footer-info">
                Romaneio de Separação gerado automaticamente pelo ERP Systhema em <?= date('d/m/Y H:i:s') ?><br>
                Este documento é exclusivo para controle interno de separação de mercadorias.
            </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>