<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-12">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h2><i class="bi bi-cart4 me-2"></i> Venda #<?= htmlspecialchars($venda['sale_number']) ?></h2>
                <p class="text-muted mb-0">
                    Emitida em <?= date('d/m/Y', strtotime($venda['sale_date'])) ?>
                </p>
            </div>
            <div>
                <button onclick="voltarPaginaAnterior()" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left me-2"></i> Voltar
                </button>
                <?php if (!empty($venda['numero_nfe']) && !empty($venda['chave_nfe'])): ?>
                <a href="<?= url('/vendas/reimprimir-nfe?id=' . $venda['id']) ?>" class="btn btn-warning" target="_blank">
                    <i class="bi bi-receipt-cutoff me-2"></i> Reimprimir NF-e
                </a>
                <?php endif; ?>
                <a href="<?= url('/vendas/imprimir?id=' . $venda['id']) ?>" class="btn btn-primary" target="_blank">
                    <i class="bi bi-printer me-2"></i> Imprimir Pedido
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Primeira Linha de Cards -->
<div class="row cards-equal mb-4">
    <!-- Coluna Esquerda -->
    <div class="col-md-6">
        <!-- Informações da Venda -->
        <div class="card h-100">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="bi bi-info-circle me-2"></i> Informações da Venda</h5>
            </div>
            <div class="card-body">
                <table class="table table-borderless mb-0">
                    <tbody>
                        <tr>
                            <td class="text-muted" width="150"><strong>Número:</strong></td>
                            <td><?= htmlspecialchars($venda['sale_number']) ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Data:</strong></td>
                            <td><?= date('d/m/Y', strtotime($venda['sale_date'])) ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Status:</strong></td>
                            <td>
                                <span class="badge bg-secondary"><?= htmlspecialchars($venda['status']) ?></span>
                            </td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Cliente:</strong></td>
                            <td><?= htmlspecialchars($venda['customer_name']) ?></td>
                        </tr>
                        <?php if (!empty($venda['customer_document'])): ?>
                        <tr>
                            <td class="text-muted"><strong>CPF/CNPJ:</strong></td>
                            <td><?= htmlspecialchars($venda['customer_document']) ?></td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Coluna Direita -->
    <div class="col-md-6">
        <!-- Itens da Venda -->
        <div class="card h-100">
            <div class="card-header bg-info text-white">
                <h5 class="mb-0"><i class="bi bi-cart-check me-2"></i> Itens da Venda</h5>
            </div>
            <div class="card-body">
                <?php if (!empty($itens)): ?>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Produto</th>
                                <th class="text-center">Qtd</th>
                                <th class="text-end">Valor Un.</th>
                                <th class="text-end">Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($itens as $item): ?>
                            <tr>
                                <td>
                                    <strong><?= htmlspecialchars($item['product_name']) ?></strong>
                                    <?php if (!empty($item['product_sku'])): ?>
                                    <br><small class="text-muted">SKU: <?= htmlspecialchars($item['product_sku']) ?></small>
                                    <?php endif; ?>
                                </td>
                                <td class="text-center"><?= number_format($item['quantity'], 3, ',', '.') ?></td>
                                <td class="text-end">R$ <?= number_format($item['unit_price'], 2, ',', '.') ?></td>
                                <td class="text-end"><strong>R$ <?= number_format($item['total_price'], 2, ',', '.') ?></strong></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <p class="text-muted text-center py-3">Nenhum item encontrado</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Segunda Linha de Cards -->
<div class="row cards-equal">
    <div class="col-md-6">
        <!-- Valores -->
        <div class="card h-100">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="bi bi-cash-stack me-2"></i> Valores</h5>
            </div>
            <div class="card-body">
                <table class="table table-borderless mb-0">
                    <tbody>
                        <tr>
                            <td class="text-muted" width="150"><strong>Subtotal:</strong></td>
                            <td>R$ <?= number_format($venda['subtotal'] ?? 0, 2, ',', '.') ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Desconto:</strong></td>
                            <td class="text-danger">- R$ <?= number_format($venda['discount'] ?? 0, 2, ',', '.') ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Frete:</strong></td>
                            <td>R$ <?= number_format($venda['shipping'] ?? 0, 2, ',', '.') ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Acréscimos:</strong></td>
                            <td>R$ <?= number_format($venda['additions'] ?? 0, 2, ',', '.') ?></td>
                        </tr>
                        <tr class="border-top">
                            <td class="text-muted"><strong>TOTAL:</strong></td>
                            <td><strong class="text-success" style="font-size: 1.25rem;">R$ <?= number_format($venda['total'], 2, ',', '.') ?></strong></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <!-- NF-e (se existir) -->
        <?php if (!empty($venda['numero_nfe'])): ?>
        <div class="card h-100">
            <div class="card-header bg-warning text-dark">
                <h5 class="mb-0"><i class="bi bi-receipt-cutoff me-2"></i> NF-e</h5>
            </div>
            <div class="card-body">
                <table class="table table-borderless mb-0">
                    <tbody>
                        <tr>
                            <td class="text-muted" width="150"><strong>Número:</strong></td>
                            <td><?= htmlspecialchars($venda['numero_nfe']) ?></td>
                        </tr>
                        <?php if (!empty($venda['chave_nfe'])): ?>
                        <tr>
                            <td class="text-muted"><strong>Chave de Acesso:</strong></td>
                            <td><small><?= htmlspecialchars($venda['chave_nfe']) ?></small></td>
                        </tr>
                        <?php endif; ?>
                        <?php if (!empty($venda['protocolo_nfe'])): ?>
                        <tr>
                            <td class="text-muted"><strong>Protocolo:</strong></td>
                            <td><?= htmlspecialchars($venda['protocolo_nfe']) ?></td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php else: ?>
        <div class="card h-100">
            <div class="card-header bg-secondary text-white">
                <h5 class="mb-0"><i class="bi bi-receipt me-2"></i> NF-e</h5>
            </div>
            <div class="card-body d-flex align-items-center justify-content-center">
                <div class="text-center text-muted">
                    <i class="bi bi-receipt" style="font-size: 3rem; opacity: 0.3;"></i>
                    <p class="mb-0 mt-2">NF-e não emitida</p>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Observações -->
<?php if (!empty($venda['notes'])): ?>
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header bg-secondary text-white">
                <h5 class="mb-0"><i class="bi bi-sticky me-2"></i> Observações</h5>
            </div>
            <div class="card-body">
                <p class="mb-0"><?= nl2br(htmlspecialchars($venda['notes'])) ?></p>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<style>
/* Padronizar altura dos cards */
.cards-equal {
    display: flex;
    flex-wrap: wrap;
}

.cards-equal > [class*="col-"] {
    display: flex;
    flex-direction: column;
}

.cards-equal .card.h-100 {
    flex: 1;
}

@media print {
    .btn {
        display: none !important;
    }

    .card {
        border: 1px solid #dee2e6 !important;
        box-shadow: none !important;
        page-break-inside: avoid;
    }
}
</style>

<script>
function voltarPaginaAnterior() {
    // Verifica se há histórico para voltar
    if (window.history.length > 1) {
        // Verifica se há um referer válido
        const referer = document.referrer;
        if (referer && referer !== window.location.href) {
            window.history.back();
        } else {
            // Fallback: vai para a página de vendas
            window.location.href = '<?= url('/vendas') ?>';
        }
    } else {
        // Se não houver histórico, vai para a página de vendas
        window.location.href = '<?= url('/vendas') ?>';
    }
}
</script>

<?php
$content = ob_get_clean();
$activeMenu = 'vendas';
include ROOT_PATH . '/views/layouts/app.php';
?>
