<?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> Ordem_servico #<?= htmlspecialchars($ordem['service_number']) ?></h2>
                <p class="text-muted mb-0">
                    Emitida em <?= date('d/m/Y', strtotime($ordem['service_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($ordem['numero_nfe']) && !empty($ordem['chave_nfe'])): ?>
                <a href="<?= url('/ordem-servico/reimprimir-nfe?id=' . $ordem['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('/ordem-servico/imprimir?id=' . $ordem['id']) ?>" class="btn btn-primary" target="_blank">
                    <i class="bi bi-printer me-2"></i> Imprimir OS
                </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 Ordem_servico -->
        <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 Ordem_servico</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($ordem['service_number']) ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Data:</strong></td>
                            <td><?= date('d/m/Y', strtotime($ordem['service_date'])) ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Status:</strong></td>
                            <td>
                                <span class="badge bg-secondary"><?= htmlspecialchars($ordem['status']) ?></span>
                            </td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Cliente:</strong></td>
                            <td><?= htmlspecialchars($ordem['customer_name']) ?></td>
                        </tr>
                        <?php if (!empty($ordem['customer_document'])): ?>
                        <tr>
                            <td class="text-muted"><strong>CPF/CNPJ:</strong></td>
                            <td><?= htmlspecialchars($ordem['customer_document']) ?></td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Coluna Direita -->
    <div class="col-md-6">
        <!-- Itens da Ordem_servico -->
        <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 Ordem_servico</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($ordem['subtotal'] ?? 0, 2, ',', '.') ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Desconto:</strong></td>
                            <td class="text-danger">- R$ <?= number_format($ordem['discount'] ?? 0, 2, ',', '.') ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Frete:</strong></td>
                            <td>R$ <?= number_format($ordem['shipping'] ?? 0, 2, ',', '.') ?></td>
                        </tr>
                        <tr>
                            <td class="text-muted"><strong>Acréscimos:</strong></td>
                            <td>R$ <?= number_format($ordem['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($ordem['total'], 2, ',', '.') ?></strong></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <!-- NF-e (se existir) -->
        <?php if (!empty($ordem['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($ordem['numero_nfe']) ?></td>
                        </tr>
                        <?php if (!empty($ordem['chave_nfe'])): ?>
                        <tr>
                            <td class="text-muted"><strong>Chave de Acesso:</strong></td>
                            <td><small><?= htmlspecialchars($ordem['chave_nfe']) ?></small></td>
                        </tr>
                        <?php endif; ?>
                        <?php if (!empty($ordem['protocolo_nfe'])): ?>
                        <tr>
                            <td class="text-muted"><strong>Protocolo:</strong></td>
                            <td><?= htmlspecialchars($ordem['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($ordem['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($ordem['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 ordens de serviço
            window.location.href = '<?= url('/ordem-servico') ?>';
        }
    } else {
        // Se não houver histórico, vai para a página de ordens de serviço
        window.location.href = '<?= url('/ordem-servico') ?>';
    }
}
</script>

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


