<?php
ob_start();

// Preparar logo da empresa
$logoPath = null;
if (!empty($empresa) && is_array($empresa)) {
    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';
    }
    if (!$logoPath && file_exists(ROOT_PATH . '/public/assets/images/logo.png')) {
        $logoPath = 'public/assets/images/logo.png';
    }
}

$empresaNome = !empty($empresa) && is_array($empresa) ? ($empresa['razao_social'] ?? $empresa['nome'] ?? $empresa['name'] ?? 'Empresa') : 'Empresa';
$empresaDoc = !empty($empresa) && is_array($empresa) ? ($empresa['cnpj'] ?? $empresa['document'] ?? '') : '';

// Calcular totais
$totalReceber = !empty($dados) ? array_sum(array_column($dados, 'amount')) : 0;
$totalPago = !empty($dados) ? array_sum(array_column(array_filter($dados, fn($d) => ($d['status'] ?? '') === 'pago'), 'amount')) : 0;
$totalPendente = $totalReceber - $totalPago;
?>

<div class="row mb-4 no-print">
    <div class="col-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?= url('/dashboard') ?>">Dashboard</a></li>
                <li class="breadcrumb-item"><a href="<?= url('/relatorios') ?>">Relatórios</a></li>
                <li class="breadcrumb-item active">Contas a Receber</li>
            </ol>
        </nav>
        <div class="d-flex justify-content-between align-items-center">
            <h2 class="mb-0"><i class="bi bi-arrow-down-circle me-2 text-success"></i> Relatório de Contas a Receber
            </h2>
            <a href="<?= url('/relatorios') ?>" class="btn btn-outline-secondary no-print">
                <i class="bi bi-arrow-left me-2"></i> Voltar
            </a>
        </div>
    </div>
</div>

<!-- Cabeçalho de Impressão (só aparece na impressão) -->
<div class="print-header" style="display: none;">
    <div class="print-header-content">
        <div style="display: flex; align-items: center;">
            <?php if ($logoPath && file_exists(ROOT_PATH . '/' . $logoPath)): ?>
                <img src="<?= asset($logoPath) ?>" alt="Logo" class="print-logo">
            <?php endif; ?>
            <div class="print-empresa-info">
                <div class="print-empresa-nome"><?= strtoupper(htmlspecialchars($empresaNome)) ?></div>
                <?php if ($empresaDoc): ?>
                    <div class="print-empresa-doc">CNPJ: <?= htmlspecialchars($empresaDoc) ?></div>
                <?php endif; ?>
            </div>
        </div>
        <div class="print-relatorio-info">
            <div class="print-relatorio-titulo">Relatório de Contas a Receber</div>
        </div>
    </div>
</div>

<!-- Tabela de Resultados -->
<div class="card mb-4 resumo-card">
    <div class="card-header d-flex justify-content-between align-items-center bg-success text-white no-print">
        <span><i class="bi bi-table me-2"></i> Resultados</span>
        <div>
            <button onclick="window.print()" class="btn btn-light btn-sm no-print">
                <i class="bi bi-printer me-2"></i> Imprimir
            </button>
            <span class="badge bg-light text-dark ms-2"><?= count($dados ?? []) ?> conta(s)</span>
        </div>
    </div>
    <div class="card-body p-0">
        <?php if (!empty($dados)): ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th style="min-width: 200px;">Cliente</th>
                            <th style="min-width: 250px;">Descrição</th>
                            <th class="text-end" style="min-width: 120px;">Valor</th>
                            <th class="text-center" style="min-width: 120px;">Vencimento</th>
                            <th class="text-center" style="min-width: 100px;">Status</th>
                            <th class="text-center" style="min-width: 100px;">Dias Atraso</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($dados as $item): ?>
                            <?php
                            $diasAtraso = (int) ($item['dias_atraso'] ?? 0);
                            $status = $item['status'] ?? 'pendente';
                            $statusClass = $status === 'pago' ? 'success' : ($diasAtraso > 0 ? 'danger' : 'warning');
                            $statusText = $status === 'pago' ? 'Pago' : ($status === 'vencido' ? 'Vencido' : 'Pendente');
                            ?>
                            <tr>
                                <td><?= htmlspecialchars($item['customer_name'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($item['description'] ?? '-') ?></td>
                                <td class="text-end">
                                    <strong>R$ <?= formatCurrency($item['amount'] ?? 0) ?></strong>
                                </td>
                                <td class="text-center">
                                    <?= !empty($item['due_date']) ? date('d/m/Y', strtotime($item['due_date'])) : '-' ?>
                                </td>
                                <td class="text-center">
                                    <span class="badge bg-<?= $statusClass ?> no-print"><?= $statusText ?></span>
                                    <span class="print-only"><?= $statusText ?></span>
                                </td>
                                <td class="text-center">
                                    <?php if ($diasAtraso > 0): ?>
                                        <span class="text-danger"><?= $diasAtraso ?> dia(s)</span>
                                    <?php elseif ($diasAtraso < 0): ?>
                                        <span class="text-success"><?= abs($diasAtraso) ?> dia(s)</span>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot class="table-light">
                        <tr style="background-color: #f8f9fa !important;">
                            <th colspan="2" style="font-weight: bold; border-top: 2px solid #333 !important;">TOTAL</th>
                            <th class="text-end" style="font-weight: bold; border-top: 2px solid #333 !important;">
                                <strong>R$ <?= formatCurrency($totalReceber) ?></strong>
                            </th>
                            <th colspan="3" style="border-top: 2px solid #333 !important;"></th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        <?php else: ?>
            <div class="text-center py-5">
                <i class="bi bi-inbox fs-1 text-muted d-block mb-3"></i>
                <p class="text-muted">Nenhuma conta a receber encontrada.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Rodapé de Impressão -->
<div class="print-footer">
    <div>Impresso em <?= date('d/m/Y H:i:s') ?> - Systhema ERP</div>
</div>

<style>
    .print-header,
    .print-only,
    .print-footer {
        display: none;
    }

    @media print {
        @page {
            size: A4;
            margin: 0cm 2.5cm 2cm 2.5cm;
        }

        * {
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }

        html,
        body,
        body>main,
        body>main>.content-wrapper,
        .container,
        .container-fluid,
        .row,
        .main-content,
        .content-wrapper,
        main,
        .sidebar,
        .topbar {
            margin: 0 !important;
            padding: 0 !important;
            height: auto !important;
        }

        body {
            font-size: 9pt;
            line-height: 1.3;
        }

        .no-print,
        .breadcrumb,
        .btn,
        form,
        .sidebar,
        .topbar,
        header,
        nav,
        .row.no-print,
        .card.no-print,
        .no-print.card,
        .no-print.row,
        div.no-print {
            display: none !important;
            margin: 0 !important;
            padding: 0 !important;
            height: 0 !important;
            visibility: hidden !important;
            opacity: 0 !important;
            position: absolute !important;
            left: -9999px !important;
            width: 0 !important;
            border: none !important;
            box-shadow: none !important;
        }

        .print-header {
            display: block !important;
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            width: 98% !important;
            max-width: 98% !important;
            margin: 0 auto !important;
            background-color: white !important;
            z-index: 1000 !important;
            border-bottom: 2px solid #333;
            padding: 8px 0 !important;
            page-break-after: avoid;
            page-break-inside: avoid;
            min-height: 60px !important;
        }

        .print-footer {
            display: block !important;
            position: fixed !important;
            bottom: 0 !important;
            left: 0 !important;
            right: 0 !important;
            width: 98% !important;
            max-width: 98% !important;
            margin: 0 auto !important;
            background-color: white !important;
            z-index: 999 !important;
            border-top: 1px solid #ddd;
            padding: 10px 0 !important;
            font-size: 8pt !important;
            color: #666 !important;
            text-align: center !important;
            page-break-inside: avoid !important;
            min-height: 30px !important;
        }

        .resumo-card {
            margin-top: 70px !important;
            margin-bottom: 50px !important;
            padding-top: 10px !important;
            padding-bottom: 10px !important;
        }

        .print-only {
            display: block !important;
        }

        .badge {
            background: transparent !important;
            color: #000 !important;
            padding: 0 !important;
            border: none !important;
            font-weight: normal !important;
        }

        .print-header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100% !important;
        }

        .print-logo {
            max-width: 120px;
            max-height: 50px;
            object-fit: contain;
        }

        .print-empresa-info {
            flex: 1;
            margin-left: 15px;
        }

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

        .print-empresa-doc {
            font-size: 8pt;
            color: #666;
        }

        .print-relatorio-info {
            text-align: right;
        }

        .print-relatorio-titulo {
            font-size: 14pt;
            font-weight: bold;
            margin-bottom: 3px;
        }

        .card {
            border: 1px solid #ddd !important;
            box-shadow: none !important;
            page-break-inside: avoid;
        }

        .card-header {
            background-color: #f8f9fa !important;
            border-bottom: 2px solid #ddd !important;
            padding: 8px 12px !important;
        }

        .table-responsive {
            width: 98% !important;
            margin: 0 auto !important;
            overflow: visible !important;
        }

        table {
            width: 98% !important;
            margin: 0 auto !important;
            border-collapse: collapse !important;
            font-size: 8pt;
            table-layout: auto;
        }

        .card-body table,
        .resumo-card table {
            width: 98% !important;
            margin: 0 auto !important;
        }

        th,
        td {
            padding: 6px 8px !important;
            border: 1px solid #ddd !important;
            vertical-align: middle;
            word-wrap: break-word;
        }

        th {
            background-color: #f8f9fa !important;
            font-weight: bold;
            text-align: center;
            white-space: nowrap;
        }

        td.text-end,
        td.text-center,
        th.text-end,
        th.text-center {
            white-space: nowrap !important;
        }

        td:first-child,
        th:first-child {
            max-width: 250px;
            white-space: normal;
            word-break: break-word;
        }

        .text-end {
            text-align: right !important;
        }

        .text-center {
            text-align: center !important;
        }

        tr {
            page-break-inside: avoid;
        }

        tfoot tr {
            background-color: #f8f9fa !important;
        }

        tfoot th {
            border-top: 2px solid #333 !important;
            font-weight: bold !important;
        }
    }
</style>

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