<?php
ob_start();
$codigo = str_pad($pessoa['id'], 4, '0', STR_PAD_LEFT);

// Função para agrupar dados por empresa
function agruparPorEmpresa($dados) {
    $agrupados = [];
    foreach ($dados as $item) {
        $empresaId = $item['empresa_id'] ?? 0;
        $empresaNome = $item['empresa_nome'] ?? 'Empresa Principal';

        if (!isset($agrupados[$empresaId])) {
            $agrupados[$empresaId] = [
                'id' => $empresaId,
                'nome' => $empresaNome,
                'itens' => []
            ];
        }
        $agrupados[$empresaId]['itens'][] = $item;
    }
    return $agrupados;
}

// Agrupar vendas por empresa
$vendasAgrupadas = agruparPorEmpresa($vendas);

// Agrupar vendas detalhadas por empresa
$vendasDetalhadasAgrupadas = agruparPorEmpresa($vendasDetalhadas);

// Agrupar contas a receber por empresa
$contasReceberAgrupadas = agruparPorEmpresa($contasReceber);

// Buscar logo da empresa
$logoPath = '';
if (!empty($empresa['logo'])) {
    $logoPath = $empresa['logo'];
}
$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';
}
?>

<!-- Cabeçalho de Impressão (visível apenas na impressão) -->
<div class="print-header">
    <div class="print-header-box">
        <div class="print-header-left">
            <?php if ($logoPath && file_exists(ROOT_PATH . '/' . $logoPath)): ?>
                <img src="<?= asset($logoPath) ?>" alt="Logo" class="print-logo-img">
            <?php endif; ?>
            <div class="print-empresa-info">
                <div class="print-empresa-nome">
                    <?= strtoupper(htmlspecialchars($empresa['razao_social'] ?? $empresa['nome'] ?? $empresa['trade_name'] ?? $empresa['name'] ?? 'EMPRESA')) ?>
                </div>
                <?php if (!empty($empresa['cnpj']) || !empty($empresa['document'])): ?>
                    <div class="print-empresa-cnpj">
                        CNPJ: <?= htmlspecialchars($empresa['cnpj'] ?? $empresa['document']) ?>
                    </div>
                <?php endif; ?>
                <?php
                $endereco = [];
                if (!empty($empresa['address']))
                    $endereco[] = $empresa['address'];
                if (!empty($empresa['number']))
                    $endereco[] = $empresa['number'];
                if (!empty($empresa['neighborhood']))
                    $endereco[] = $empresa['neighborhood'];
                if (!empty($empresa['city']))
                    $endereco[] = $empresa['city'];
                if (!empty($empresa['state']))
                    $endereco[] = $empresa['state'];
                if (!empty($endereco)): ?>
                    <div class="print-empresa-endereco">
                        <?= htmlspecialchars(implode(', ', $endereco)) ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <div class="print-header-right">
            <div class="print-doc-tipo">EXTRATO FINANCEIRO</div>
            <div class="print-doc-data"><?= date('d/m/Y H:i') ?></div>
        </div>
    </div>
</div>

<div class="row mb-4 no-print">
    <div class="col-md-12">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h2><i class="bi bi-file-text me-2"></i> Extrato - <?= htmlspecialchars($pessoa['name']) ?></h2>
                <p class="text-muted mb-0">
                    <?= htmlspecialchars($pessoa['document'] ?? '') ?>
                    <?php if (!empty($pessoa['email'])): ?>
                        | <i class="bi bi-envelope me-1"></i><?= htmlspecialchars($pessoa['email']) ?>
                    <?php endif; ?>
                    <?php if (!empty($pessoa['mobile'])): ?>
                        | <i class="bi bi-phone me-1"></i><?= htmlspecialchars($pessoa['mobile']) ?>
                    <?php endif; ?>
                </p>
            </div>
            <div>
                <a href="<?= url('/pessoas') ?>" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left me-2"></i> Voltar
                </a>
                <button onclick="window.print()" class="btn btn-primary">
                    <i class="bi bi-printer me-2"></i> Imprimir
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Dados da Pessoa (visível na impressão) -->
<div class="print-person-info">
    <div class="print-person-title">DADOS DO CLIENTE</div>
    <table class="print-person-table">
        <tr>
            <td width="50%">
                <div class="print-person-row">
                    <span class="label">Código:</span>
                    <span class="value"><?= $codigo ?></span>
                </div>
                <div class="print-person-row">
                    <span class="label">Razão Social:</span>
                    <span class="value"><?= htmlspecialchars($pessoa['name']) ?></span>
                </div>
                <?php if (!empty($pessoa['trade_name'])): ?>
                    <div class="print-person-row">
                        <span class="label">Nome Fantasia:</span>
                        <span class="value"><?= htmlspecialchars($pessoa['trade_name']) ?></span>
                    </div>
                <?php endif; ?>
            </td>
            <td width="50%">
                <div class="print-person-row">
                    <span class="label">CPF/CNPJ:</span>
                    <span class="value"><?= htmlspecialchars($pessoa['document'] ?? 'Não informado') ?></span>
                </div>
                <?php if (!empty($pessoa['phone']) || !empty($pessoa['mobile'])): ?>
                    <div class="print-person-row">
                        <span class="label">Telefone:</span>
                        <span class="value"><?= htmlspecialchars($pessoa['phone'] ?? $pessoa['mobile']) ?></span>
                    </div>
                <?php endif; ?>
                <?php if (!empty($pessoa['email'])): ?>
                    <div class="print-person-row">
                        <span class="label">Email:</span>
                        <span class="value"><?= htmlspecialchars($pessoa['email']) ?></span>
                    </div>
                <?php endif; ?>
            </td>
        </tr>
    </table>
</div>

<!-- Cards de Resumo -->
<div class="row mb-3 cards-resumo">
    <div class="col-md-3 col-6">
        <div class="card card-resumo border-primary">
            <div class="card-body">
                <div class="card-resumo-content">
                    <div class="card-resumo-icon bg-primary">
                        <i class="bi bi-cart4"></i>
                    </div>
                    <div class="card-resumo-info">
                        <span class="card-resumo-label">Total em Pedidos</span>
                        <span class="card-resumo-value text-primary">R$
                            <?= number_format($totalVendas, 2, ',', '.') ?></span>
                        <span class="card-resumo-count"><?= count($vendas) ?> pedido(s)</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6">
        <div class="card card-resumo border-info">
            <div class="card-body">
                <div class="card-resumo-content">
                    <div class="card-resumo-icon bg-info">
                        <i class="bi bi-cash-stack"></i>
                    </div>
                    <div class="card-resumo-info">
                        <span class="card-resumo-label">Total a Receber</span>
                        <span class="card-resumo-value text-info">R$
                            <?= number_format($totalReceber, 2, ',', '.') ?></span>
                        <span class="card-resumo-count"><?= count($contasReceber) ?> lançamento(s)</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6">
        <div class="card card-resumo border-success">
            <div class="card-body">
                <div class="card-resumo-content">
                    <div class="card-resumo-icon bg-success">
                        <i class="bi bi-check2-circle"></i>
                    </div>
                    <div class="card-resumo-info">
                        <span class="card-resumo-label">Total Recebido</span>
                        <span class="card-resumo-value text-success">R$
                            <?= number_format($totalPago, 2, ',', '.') ?></span>
                        <span class="card-resumo-count">Valores pagos</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6">
        <div class="card card-resumo border-warning">
            <div class="card-body">
                <div class="card-resumo-content">
                    <div class="card-resumo-icon bg-warning">
                        <i class="bi bi-exclamation-triangle"></i>
                    </div>
                    <div class="card-resumo-info">
                        <span class="card-resumo-label">Saldo Pendente</span>
                        <span class="card-resumo-value text-warning">R$
                            <?= number_format($totalRestante, 2, ',', '.') ?></span>
                        <span class="card-resumo-count">A receber</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Cards de Limite e Inadimplência -->
<div class="row mb-3 cards-detalhe">
    <div class="col-md-6">
        <div class="card card-detalhe h-100">
            <div class="card-body">
                <div class="card-detalhe-header">
                    <i class="bi bi-credit-card-2-front text-secondary"></i>
                    <span>Limite de Crédito</span>
                </div>
                <div class="card-detalhe-grid">
                    <div class="card-detalhe-item">
                        <span class="label">Disponível</span>
                        <span class="value text-success">R$ <?= number_format($limiteDisponivel, 2, ',', '.') ?></span>
                    </div>
                    <div class="card-detalhe-item">
                        <span class="label">Utilizado</span>
                        <span class="value text-danger">R$ <?= number_format($limiteUtilizado, 2, ',', '.') ?></span>
                    </div>
                    <div class="card-detalhe-item">
                        <span class="label">Limite Total</span>
                        <span class="value text-primary">R$ <?= number_format($limiteCredito, 2, ',', '.') ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card card-detalhe h-100 <?= $contasVencidas > 0 ? 'border-danger' : '' ?>">
            <div class="card-body">
                <div class="card-detalhe-header">
                    <i class="bi bi-exclamation-octagon text-danger"></i>
                    <span>Inadimplência</span>
                </div>
                <div class="card-detalhe-grid">
                    <div class="card-detalhe-item">
                        <span class="label">Contas Vencidas</span>
                        <span
                            class="value <?= $contasVencidas > 0 ? 'text-danger' : 'text-success' ?>"><?= $contasVencidas ?></span>
                    </div>
                    <div class="card-detalhe-item">
                        <span class="label">Valor Vencido</span>
                        <span class="value <?= $totalVencido > 0 ? 'text-danger' : 'text-success' ?>">R$
                            <?= number_format($totalVencido, 2, ',', '.') ?></span>
                    </div>
                    <div class="card-detalhe-item">
                        <span class="label">Situação</span>
                        <span
                            class="value <?= $contasVencidas > 0 ? 'text-danger' : 'text-success' ?>"><?= $contasVencidas > 0 ? 'Inadimplente' : 'Regular' ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Tabs (apenas na tela) -->
<ul class="nav nav-tabs mb-3 no-print" id="extratoTabs" role="tablist">
    <li class="nav-item" role="presentation">
        <button class="nav-link active" id="pedidos-tab" data-bs-toggle="tab" data-bs-target="#pedidos-content"
            type="button" role="tab">
            <i class="bi bi-receipt me-2"></i>Pedidos <span class="badge bg-primary ms-2"><?= count($vendas) ?></span>
        </button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="pedidos-detalhados-tab" data-bs-toggle="tab"
            data-bs-target="#pedidos-detalhados-content" type="button" role="tab">
            <i class="bi bi-list-columns-reverse me-2"></i>Pedidos Detalhados
        </button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="contas-tab" data-bs-toggle="tab" data-bs-target="#contas-content" type="button"
            role="tab">
            <i class="bi bi-cash-stack me-2"></i>Contas a Receber <span
                class="badge bg-info ms-2"><?= count($contasReceber) ?></span>
        </button>
    </li>
</ul>

<div class="tab-content" id="extratoTabsContent">
    <!-- Aba Pedidos -->
    <div class="tab-pane fade show active" id="pedidos-content" role="tabpanel">
        <?php if (!empty($vendasAgrupadas)): ?>
            <?php foreach ($vendasAgrupadas as $grupo): ?>
                <div class="card mb-3">
                    <div class="card-header print-section-header bg-light">
                        <i class="bi bi-building me-2"></i> <strong><?= htmlspecialchars($grupo['nome']) ?></strong>
                        <span class="badge bg-secondary ms-2"><?= count($grupo['itens']) ?> pedido(s)</span>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover table-print">
                                <thead>
                                    <tr>
                                        <th width="100">Número</th>
                                        <th>Data</th>
                                        <th>Status</th>
                                        <th>Método Pagamento</th>
                                        <th class="text-end">Total</th>
                                        <th width="100" class="text-center no-print">Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $totalGrupo = 0;
                                    foreach ($grupo['itens'] as $venda):
                                        $totalGrupo += (float) ($venda['total'] ?? 0);
                                    ?>
                                        <tr>
                                            <td><strong><?= htmlspecialchars($venda['sale_number']) ?></strong></td>
                                            <td><?= date('d/m/Y', strtotime($venda['sale_date'])) ?></td>
                                            <td>
                                                <?php if (!empty($venda['status_nome'])): ?>
                                                    <span class="badge"
                                                        style="background-color: <?= htmlspecialchars($venda['status_cor'] ?? '#6c757d') ?>">
                                                        <?= htmlspecialchars($venda['status_nome']) ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary"><?= htmlspecialchars($venda['status']) ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?= htmlspecialchars($venda['payment_method_name'] ?? '-') ?></td>
                                            <td class="text-end"><strong>R$
                                                    <?= number_format($venda['total'], 2, ',', '.') ?></strong></td>
                                            <td class="text-center no-print">
                                                <a href="<?= url('/vendas/visualizar?id=' . $venda['id']) ?>"
                                                    class="btn btn-sm btn-outline-primary" title="Ver Detalhes">
                                                    <i class="bi bi-eye"></i>
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr class="table-light">
                                        <td colspan="4" class="text-end"><strong>Total <?= htmlspecialchars($grupo['nome']) ?>:</strong></td>
                                        <td class="text-end"><strong>R$ <?= number_format($totalGrupo, 2, ',', '.') ?></strong>
                                        </td>
                                        <td class="no-print"></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
            <!-- Total Geral -->
            <div class="card bg-light">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <strong>Total Geral em Pedidos:</strong>
                        <strong class="text-primary" style="font-size: 1.2rem;">R$ <?= number_format($totalVendas, 2, ',', '.') ?></strong>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="card">
                <div class="card-body text-center py-5">
                    <i class="bi bi-receipt-cutoff" style="font-size: 4rem; opacity: 0.3;"></i>
                    <p class="text-muted mt-3">Nenhum pedido encontrado para este cliente</p>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Aba Pedidos Detalhados -->
    <div class="tab-pane fade" id="pedidos-detalhados-content" role="tabpanel">
        <?php if (!empty($vendasDetalhadasAgrupadas)): ?>
            <?php foreach ($vendasDetalhadasAgrupadas as $grupo): ?>
                <div class="card mb-3">
                    <div class="card-header bg-light">
                        <h5 class="mb-0">
                            <i class="bi bi-building me-2"></i> <strong><?= htmlspecialchars($grupo['nome']) ?></strong>
                            <span class="badge bg-secondary ms-2"><?= count($grupo['itens']) ?> pedido(s)</span>
                        </h5>
                    </div>
                    <div class="card-body p-0">
                        <?php foreach ($grupo['itens'] as $venda): ?>
                            <div class="venda-card" style="border-bottom: 2px solid #dee2e6; margin-bottom: 1rem; padding-bottom: 1rem;">
                                <!-- Cabeçalho da Venda -->
                                <div class="venda-header" style="background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-bottom: 1px solid #dee2e6; padding: 12px 16px;">
                                    <div class="d-flex justify-content-between align-items-center flex-wrap">
                                        <div class="venda-info">
                                            <span class="venda-numero">
                                                <i class="bi bi-receipt me-2"></i>Pedido #<?= htmlspecialchars($venda['sale_number']) ?>
                                            </span>
                                            <span class="venda-data ms-3">
                                                <i class="bi bi-calendar3 me-1"></i><?= date('d/m/Y', strtotime($venda['sale_date'])) ?>
                                            </span>
                                        </div>
                                        <div class="venda-status-total">
                                            <?php if (!empty($venda['status_nome'])): ?>
                                                <span class="badge me-2"
                                                    style="background-color: <?= htmlspecialchars($venda['status_cor'] ?? '#6c757d') ?>">
                                                    <?= htmlspecialchars($venda['status_nome']) ?>
                                                </span>
                                            <?php else: ?>
                                                <span
                                                    class="badge bg-secondary me-2"><?= htmlspecialchars($venda['status'] ?? 'Pendente') ?></span>
                                            <?php endif; ?>
                                            <span class="venda-total">
                                                R$ <?= number_format($venda['total'], 2, ',', '.') ?>
                                            </span>
                                        </div>
                                    </div>
                                    <?php if (!empty($venda['payment_method_name'])): ?>
                                        <small class="text-muted d-block mt-1">
                                            <i class="bi bi-credit-card me-1"></i><?= htmlspecialchars($venda['payment_method_name']) ?>
                                        </small>
                                    <?php endif; ?>
                                </div>

                                <!-- Itens da Venda -->
                                <div style="padding: 0;">
                                    <?php if (!empty($venda['itens'])): ?>
                                        <table class="table table-sm mb-0 venda-itens-table">
                                            <thead class="table-light">
                                                <tr>
                                                    <th width="80">SKU</th>
                                                    <th>Produto</th>
                                                    <th class="text-center" width="80">Qtd</th>
                                                    <th class="text-end" width="120">Unitário</th>
                                                    <th class="text-end" width="100">Desc.</th>
                                                    <th class="text-end" width="120">Subtotal</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($venda['itens'] as $item): ?>
                                                    <?php
                                                    $subtotal = ($item['quantity'] * $item['unit_price']) - ($item['discount'] ?? 0);
                                                    ?>
                                                    <tr>
                                                        <td><small class="text-muted"><?= htmlspecialchars($item['product_sku'] ?? '-') ?></small>
                                                        </td>
                                                        <td><?= htmlspecialchars($item['product_name'] ?? 'Produto') ?></td>
                                                        <td class="text-center"><?= number_format($item['quantity'], 2, ',', '.') ?></td>
                                                        <td class="text-end">R$ <?= number_format($item['unit_price'], 2, ',', '.') ?></td>
                                                        <td class="text-end text-danger">
                                                            <?php if (($item['discount'] ?? 0) > 0): ?>
                                                                -R$ <?= number_format($item['discount'], 2, ',', '.') ?>
                                                            <?php else: ?>
                                                                -
                                                            <?php endif; ?>
                                                        </td>
                                                        <td class="text-end fw-bold">R$ <?= number_format($subtotal, 2, ',', '.') ?></td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                            <tfoot>
                                                <tr class="table-secondary">
                                                    <td colspan="5" class="text-end"><strong>Total do Pedido:</strong></td>
                                                    <td class="text-end"><strong>R$ <?= number_format($venda['total'], 2, ',', '.') ?></strong>
                                                    </td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    <?php else: ?>
                                        <div class="text-center py-3 text-muted">
                                            <i class="bi bi-box-seam me-2"></i>Nenhum item encontrado para esta venda
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>

            <!-- Resumo Geral -->
            <div class="card bg-light mt-2">
                <div class="card-body py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="h6 mb-0">
                            <i class="bi bi-calculator me-2"></i>Total Geral (<?= count($vendasDetalhadas) ?>
                            pedido<?= count($vendasDetalhadas) != 1 ? 's' : '' ?>)
                        </span>
                        <span class="h5 mb-0 text-success fw-bold">
                            R$ <?= number_format($totalVendas, 2, ',', '.') ?>
                        </span>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="card">
                <div class="card-body text-center py-5">
                    <i class="bi bi-receipt-cutoff" style="font-size: 4rem; opacity: 0.3;"></i>
                    <p class="text-muted mt-3">Nenhum pedido encontrado para este cliente</p>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Aba Contas a Receber -->
    <div class="tab-pane fade" id="contas-content" role="tabpanel">
        <?php if (!empty($contasReceberAgrupadas)): ?>
            <?php foreach ($contasReceberAgrupadas as $grupo): ?>
                <div class="card mb-3">
                    <div class="card-header print-section-header bg-light">
                        <i class="bi bi-building me-2"></i> <strong><?= htmlspecialchars($grupo['nome']) ?></strong>
                        <span class="badge bg-secondary ms-2"><?= count($grupo['itens']) ?> lançamento(s)</span>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover table-print">
                                <thead>
                                    <tr>
                                        <th width="80">ID</th>
                                        <th>Descrição</th>
                                        <th>Vencimento</th>
                                        <th class="text-end">Valor</th>
                                        <th class="text-end">Pago</th>
                                        <th class="text-end">Restante</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $totalGrupoReceber = 0;
                                    $totalGrupoPago = 0;
                                    $totalGrupoRestante = 0;
                                    foreach ($grupo['itens'] as $conta):
                                        $totalGrupoReceber += (float) ($conta['amount'] ?? 0);
                                        $totalGrupoPago += (float) ($conta['amount_received'] ?? 0);
                                        $totalGrupoRestante += (float) ($conta['amount_remaining'] ?? 0);
                                    ?>
                                        <tr>
                                            <td><strong>#<?= $conta['id'] ?></strong></td>
                                            <td><?= htmlspecialchars($conta['description'] ?? '-') ?></td>
                                            <td>
                                                <?php
                                                $vencimento = strtotime($conta['due_date']);
                                                $hoje = strtotime(date('Y-m-d'));
                                                $valorPago = (float) ($conta['amount_received'] ?? 0);
                                                $vencido = $vencimento < $hoje && $conta['amount_remaining'] > 0;
                                                ?>
                                                <span class="<?= $vencido ? 'text-danger fw-bold' : '' ?>">
                                                    <?= date('d/m/Y', $vencimento) ?>
                                                </span>
                                                <?php if ($vencido): ?>
                                                    <i class="bi bi-exclamation-circle text-danger ms-1" title="Vencida"></i>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-end">R$ <?= number_format($conta['amount'], 2, ',', '.') ?></td>
                                            <td class="text-end text-success">R$ <?= number_format($valorPago, 2, ',', '.') ?></td>
                                            <td class="text-end text-warning">R$
                                                <?= number_format($conta['amount_remaining'], 2, ',', '.') ?>
                                            </td>
                                            <td>
                                                <?php if ($conta['amount_remaining'] <= 0): ?>
                                                    <span class="badge bg-success">Pago</span>
                                                <?php elseif ($valorPago > 0): ?>
                                                    <span class="badge bg-info">Parcial</span>
                                                <?php elseif ($vencido): ?>
                                                    <span class="badge bg-danger">Vencido</span>
                                                <?php else: ?>
                                                    <span class="badge bg-warning">Pendente</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr class="table-light">
                                        <td colspan="3" class="text-end"><strong>Total <?= htmlspecialchars($grupo['nome']) ?>:</strong></td>
                                        <td class="text-end"><strong>R$
                                                <?= number_format($totalGrupoReceber, 2, ',', '.') ?></strong></td>
                                        <td class="text-end text-success"><strong>R$
                                                <?= number_format($totalGrupoPago, 2, ',', '.') ?></strong></td>
                                        <td class="text-end text-warning"><strong>R$
                                                <?= number_format($totalGrupoRestante, 2, ',', '.') ?></strong></td>
                                        <td></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
            <!-- Total Geral -->
            <div class="card bg-light">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 text-center">
                            <div class="mb-2"><strong>Total a Receber</strong></div>
                            <div class="h5 text-primary mb-0">R$ <?= number_format($totalReceber, 2, ',', '.') ?></div>
                        </div>
                        <div class="col-md-4 text-center">
                            <div class="mb-2"><strong>Total Recebido</strong></div>
                            <div class="h5 text-success mb-0">R$ <?= number_format($totalPago, 2, ',', '.') ?></div>
                        </div>
                        <div class="col-md-4 text-center">
                            <div class="mb-2"><strong>Saldo Pendente</strong></div>
                            <div class="h5 text-warning mb-0">R$ <?= number_format($totalRestante, 2, ',', '.') ?></div>
                        </div>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="card">
                <div class="card-body text-center py-5">
                    <i class="bi bi-cash-stack" style="font-size: 4rem; opacity: 0.3;"></i>
                    <p class="text-muted mt-3">Nenhuma conta a receber encontrada para este cliente</p>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Rodapé de Impressão -->
<div class="print-footer">
    <div class="print-footer-content">
        <div class="print-footer-left">
            <i class="bi bi-file-earmark-text"></i>
            Documento gerado em <?= date('d/m/Y \à\s H:i:s') ?>
        </div>
        <div class="print-footer-center">
            <?= htmlspecialchars($empresa['trade_name'] ?? $empresa['name'] ?? '') ?>
        </div>
        <div class="print-footer-right">
            Systhema ERP
        </div>
    </div>
</div>

<style>
    /* Espaçamentos entre blocos */
    .print-person-info {
        margin-bottom: 1rem;
    }

    .cards-resumo {
        margin-bottom: 1rem !important;
    }

    .cards-detalhe {
        margin-bottom: 1rem !important;
    }

    .nav-tabs {
        margin-bottom: 1rem !important;
    }

    /* Estilos para Pedidos Detalhados */
    .venda-card {
        border: 1px solid #dee2e6;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        margin-bottom: 1rem;
    }

    .venda-header {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-bottom: 1px solid #dee2e6;
        padding: 12px 16px;
    }

    .venda-numero {
        font-weight: 700;
        font-size: 1.1rem;
        color: #1e3c72;
    }

    .venda-data {
        color: #6c757d;
        font-size: 0.9rem;
    }

    .venda-total {
        font-weight: 700;
        font-size: 1.15rem;
        color: #198754;
    }

    .venda-itens-table {
        font-size: 0.9rem;
    }

    .venda-itens-table thead th {
        font-weight: 600;
        font-size: 0.8rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #495057;
    }

    .venda-itens-table tbody td {
        vertical-align: middle;
    }

    .venda-itens-table tfoot td {
        font-size: 0.95rem;
    }

    /* Estilos para Tela */
    .cards-resumo .card-resumo {
        height: 100%;
        transition: transform 0.2s;
    }

    .cards-resumo .card-resumo:hover {
        transform: translateY(-2px);
    }

    .cards-resumo .card-resumo .card-body {
        padding: 0.75rem;
    }

    .card-resumo-content {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .card-resumo-icon {
        width: 40px;
        height: 40px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 1.1rem;
        flex-shrink: 0;
    }

    .card-resumo-info {
        display: flex;
        flex-direction: column;
    }

    .card-resumo-label {
        font-size: 0.7rem;
        color: #6c757d;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .card-resumo-value {
        font-size: 1.1rem;
        font-weight: 700;
        line-height: 1.2;
        line-height: 1.2;
    }

    .card-resumo-count {
        font-size: 0.75rem;
        color: #6c757d;
    }

    /* Cards de Detalhe */
    .card-detalhe .card-body {
        padding: 0.75rem 1rem;
    }

    .card-detalhe-header {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;
        font-weight: 600;
        font-size: 0.85rem;
    }

    .card-detalhe-header i {
        font-size: 1rem;
    }

    .card-detalhe-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 10px;
    }

    .card-detalhe-item {
        display: flex;
        flex-direction: column;
        text-align: center;
    }

    .card-detalhe-item .label {
        font-size: 0.65rem;
        color: #6c757d;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .card-detalhe-item .value {
        font-size: 0.9rem;
        font-weight: 700;
    }

    /* Cabeçalho e Rodapé de Impressão - ocultos na tela */
    .print-header,
    .print-footer,
    .print-person-info,
    .print-section-header {
        display: none;
    }

    /* Estilos de Impressão */
    @media print {
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            font-size: 10pt;
            line-height: 1.4;
            color: #2c3e50;
            background: white !important;
            padding: 0.5cm;
        }

        .no-print,
        .nav-tabs,
        .btn {
            display: none !important;
        }

        .print-header,
        .print-footer,
        .print-person-info {
            display: block !important;
        }

        .print-section-header {
            display: flex !important;
            background: #f8f9fa !important;
            padding: 8px 12px !important;
            font-weight: 600;
            border-bottom: 2px solid #dee2e6;
        }

        /* Cabeçalho estilo vendas */
        .print-header-box {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            padding: 1rem 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-radius: 8px;
            margin-bottom: 15px;
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }

        .print-header-left {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .print-logo-img {
            max-width: 100px;
            max-height: 45px;
            background: white;
            padding: 4px;
            border-radius: 4px;
        }

        .print-empresa-info {
            display: flex;
            flex-direction: column;
        }

        .print-empresa-nome {
            font-size: 13pt;
            font-weight: bold;
            margin-bottom: 2px;
        }

        .print-empresa-cnpj {
            font-size: 8pt;
            opacity: 0.9;
        }

        .print-empresa-endereco {
            font-size: 7pt;
            opacity: 0.85;
            margin-top: 2px;
        }

        .print-header-right {
            text-align: right;
        }

        .print-doc-tipo {
            font-size: 14pt;
            font-weight: bold;
            margin-bottom: 2px;
        }

        .print-doc-data {
            font-size: 9pt;
            opacity: 0.9;
        }

        /* Dados da pessoa */
        .print-person-info {
            background: #f8f9fa;
            padding: 0;
            margin-bottom: 15px;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            overflow: hidden;
        }

        .print-person-title {
            background: #e9ecef;
            padding: 8px 15px;
            font-weight: bold;
            font-size: 10pt;
            color: #495057;
            border-bottom: 1px solid #dee2e6;
        }

        .print-person-table {
            width: 100%;
            font-size: 10pt;
            padding: 12px 15px;
        }

        .print-person-table td {
            vertical-align: top;
            padding: 0 10px;
        }

        .print-person-row {
            margin-bottom: 4px;
        }

        .print-person-row .label {
            color: #6c757d;
            font-size: 8pt;
            display: block;
        }

        .print-person-row .value {
            font-weight: 600;
            color: #212529;
        }

        /* Rodapé */
        .print-footer {
            margin-top: 20px;
            padding: 10px 15px;
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
        }

        .print-footer-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 8pt;
            color: #666;
        }

        .print-footer-left,
        .print-footer-center,
        .print-footer-right {
            flex: 1;
        }

        .print-footer-center {
            text-align: center;
            font-weight: 600;
            color: #495057;
        }

        .print-footer-right {
            text-align: right;
            font-style: italic;
        }

        .card {
            border: 1px solid #dee2e6 !important;
            box-shadow: none !important;
            break-inside: avoid;
            margin-bottom: 12px !important;
        }

        .cards-resumo {
            display: flex !important;
            flex-wrap: nowrap !important;
        }

        .cards-resumo .col-md-3,
        .cards-resumo .col-6 {
            flex: 0 0 25% !important;
            max-width: 25% !important;
            padding: 4px !important;
        }

        .card-resumo {
            border-width: 1px !important;
        }

        .card-resumo .card-body {
            padding: 10px !important;
        }

        .card-resumo-icon {
            width: 32px !important;
            height: 32px !important;
            font-size: 0.9rem !important;
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }

        .card-resumo-label {
            font-size: 0.65rem !important;
        }

        .card-resumo-value {
            font-size: 0.95rem !important;
        }

        .card-resumo-count {
            font-size: 0.65rem !important;
        }

        .cards-detalhe .col-md-6 {
            flex: 0 0 50% !important;
            max-width: 50% !important;
            padding: 4px !important;
        }

        .card-detalhe .card-body {
            padding: 10px !important;
        }

        .card-detalhe-header {
            font-size: 0.8rem !important;
            margin-bottom: 8px !important;
        }

        .card-detalhe-item .label {
            font-size: 0.6rem !important;
        }

        .card-detalhe-item .value {
            font-size: 0.85rem !important;
        }

        .tab-pane {
            display: block !important;
            opacity: 1 !important;
            page-break-before: auto;
        }

        .table-print {
            font-size: 9pt;
        }

        .table-print th,
        .table-print td {
            padding: 5px 6px !important;
        }

        .badge {
            border: 1px solid currentColor !important;
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }

        /* Forçar cores na impressão */
        .text-primary {
            color: #0d6efd !important;
        }

        .text-success {
            color: #198754 !important;
        }

        .text-danger {
            color: #dc3545 !important;
        }

        .text-warning {
            color: #fd7e14 !important;
        }

        .text-info {
            color: #0dcaf0 !important;
        }

        .bg-primary {
            background-color: #0d6efd !important;
        }

        .bg-success {
            background-color: #198754 !important;
        }

        .bg-danger {
            background-color: #dc3545 !important;
        }

        .bg-warning {
            background-color: #fd7e14 !important;
        }

        .bg-info {
            background-color: #0dcaf0 !important;
        }
    }
</style>

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