<?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'] ?? '') : '';

$ano = $ano ?? date('Y');
?>

<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">DRE</li>
            </ol>
        </nav>
        <div class="d-flex justify-content-between align-items-center">
            <h2 class="mb-0"><i class="bi bi-graph-up me-2 text-info"></i> DRE - Demonstrativo de Resultado do Exercício
            </h2>
            <div class="d-flex gap-2">
                <form method="GET" action="<?= url('/relatorios/dre') ?>" class="d-flex align-items-center gap-2">
                    <label for="ano" class="mb-0">Ano:</label>
                    <select name="ano" id="ano" class="form-select form-select-sm" style="width: auto;"
                        onchange="this.form.submit()">
                        <?php
                        $anoAtual = date('Y');
                        for ($i = $anoAtual; $i >= $anoAtual - 5; $i--):
                            $selected = ($i == ($ano ?? $anoAtual)) ? 'selected' : '';
                            ?>
                            <option value="<?= $i ?>" <?= $selected ?>><?= $i ?></option>
                        <?php endfor; ?>
                    </select>
                </form>
                <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>
</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">DRE - Demonstrativo de Resultado do Exercício</div>
            <div class="print-relatorio-periodo">Ano: <?= $ano ?></div>
        </div>
    </div>
</div>

<!-- DRE -->
<div class="card mb-4 resumo-card">
    <div class="card-header d-flex justify-content-between align-items-center bg-info text-white no-print">
        <span><i class="bi bi-table me-2"></i> DRE - Ano <?= $ano ?></span>
        <div>
            <button onclick="window.print()" class="btn btn-light btn-sm no-print">
                <i class="bi bi-printer me-2"></i> Imprimir
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-bordered mb-0">
                <thead class="table-light">
                    <tr>
                        <th style="min-width: 300px;">Descrição</th>
                        <th class="text-end" style="min-width: 150px;">Valor (R$)</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>Receitas</strong></td>
                        <td class="text-end"><strong>R$ <?= formatCurrency($receitas ?? 0) ?></strong></td>
                    </tr>
                    <tr>
                        <td style="padding-left: 30px;">(-) Custos dos Produtos Vendidos</td>
                        <td class="text-end">(R$ <?= formatCurrency($custos ?? 0) ?>)</td>
                    </tr>
                    <tr class="table-primary">
                        <td><strong>Lucro Bruto</strong></td>
                        <td class="text-end"><strong>R$ <?= formatCurrency($lucroBruto ?? 0) ?></strong></td>
                    </tr>
                    <tr>
                        <td style="padding-left: 30px;">(-) Despesas Operacionais</td>
                        <td class="text-end">(R$ <?= formatCurrency($despesas ?? 0) ?>)</td>
                    </tr>
                    <tr class="table-<?= ($lucroLiquido ?? 0) >= 0 ? 'success' : 'danger' ?>">
                        <td><strong>Lucro Líquido</strong></td>
                        <td class="text-end"><strong>R$ <?= formatCurrency($lucroLiquido ?? 0) ?></strong></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Detalhamento por Plano de Contas -->
<?php if ($hasPlanoContas ?? false && !empty($detalhamentoPlanoContas ?? [])): ?>
    <div class="card mb-4">
        <div class="card-header bg-secondary text-white">
            <h5 class="mb-0"><i class="bi bi-diagram-3 me-2"></i> Detalhamento por Plano de Contas</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-bordered table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Código</th>
                            <th>Plano de Contas</th>
                            <th class="text-end">Receitas (R$)</th>
                            <th class="text-end">Despesas (R$)</th>
                            <th class="text-end">Resultado (R$)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $totalReceitasPlano = 0;
                        $totalDespesasPlano = 0;
                        foreach ($detalhamentoPlanoContas as $item):
                            $receitasItem = (float) ($item['receitas'] ?? 0);
                            $despesasItem = (float) ($item['despesas'] ?? 0);
                            $resultadoItem = $receitasItem - $despesasItem;
                            $totalReceitasPlano += $receitasItem;
                            $totalDespesasPlano += $despesasItem;
                            ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($item['codigo'] ?? '') ?></strong></td>
                                <td><?= htmlspecialchars($item['nome'] ?? '') ?></td>
                                <td class="text-end text-success">
                                    <?= $receitasItem > 0 ? 'R$ ' . formatCurrency($receitasItem) : '-' ?>
                                </td>
                                <td class="text-end text-danger">
                                    <?= $despesasItem > 0 ? 'R$ ' . formatCurrency($despesasItem) : '-' ?>
                                </td>
                                <td class="text-end <?= $resultadoItem >= 0 ? 'text-success' : 'text-danger' ?>">
                                    <strong><?= $resultadoItem != 0 ? 'R$ ' . formatCurrency($resultadoItem) : '-' ?></strong>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <tr class="table-info">
                            <td colspan="2"><strong>Total</strong></td>
                            <td class="text-end"><strong>R$ <?= formatCurrency($totalReceitasPlano) ?></strong></td>
                            <td class="text-end"><strong>R$ <?= formatCurrency($totalDespesasPlano) ?></strong></td>
                            <td class="text-end">
                                <strong
                                    class="<?= ($totalReceitasPlano - $totalDespesasPlano) >= 0 ? 'text-success' : 'text-danger' ?>">
                                    R$ <?= formatCurrency($totalReceitasPlano - $totalDespesasPlano) ?>
                                </strong>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- Detalhamento por Centro de Custos -->
<?php if ($hasCentroCusto ?? false && !empty($detalhamentoCentroCustos ?? [])): ?>
    <div class="card mb-4">
        <div class="card-header bg-secondary text-white">
            <h5 class="mb-0"><i class="bi bi-folder me-2"></i> Detalhamento por Centro de Custos</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-bordered table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Código</th>
                            <th>Centro de Custos</th>
                            <th class="text-end">Receitas (R$)</th>
                            <th class="text-end">Despesas (R$)</th>
                            <th class="text-end">Resultado (R$)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $totalReceitasCentro = 0;
                        $totalDespesasCentro = 0;
                        foreach ($detalhamentoCentroCustos as $item):
                            $receitasItem = (float) ($item['receitas'] ?? 0);
                            $despesasItem = (float) ($item['despesas'] ?? 0);
                            $resultadoItem = $receitasItem - $despesasItem;
                            $totalReceitasCentro += $receitasItem;
                            $totalDespesasCentro += $despesasItem;
                            ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($item['codigo'] ?? '') ?></strong></td>
                                <td><?= htmlspecialchars($item['nome'] ?? '') ?></td>
                                <td class="text-end text-success">
                                    <?= $receitasItem > 0 ? 'R$ ' . formatCurrency($receitasItem) : '-' ?>
                                </td>
                                <td class="text-end text-danger">
                                    <?= $despesasItem > 0 ? 'R$ ' . formatCurrency($despesasItem) : '-' ?>
                                </td>
                                <td class="text-end <?= $resultadoItem >= 0 ? 'text-success' : 'text-danger' ?>">
                                    <strong><?= $resultadoItem != 0 ? 'R$ ' . formatCurrency($resultadoItem) : '-' ?></strong>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <tr class="table-info">
                            <td colspan="2"><strong>Total</strong></td>
                            <td class="text-end"><strong>R$ <?= formatCurrency($totalReceitasCentro) ?></strong></td>
                            <td class="text-end"><strong>R$ <?= formatCurrency($totalDespesasCentro) ?></strong></td>
                            <td class="text-end">
                                <strong
                                    class="<?= ($totalReceitasCentro - $totalDespesasCentro) >= 0 ? 'text-success' : 'text-danger' ?>">
                                    R$ <?= formatCurrency($totalReceitasCentro - $totalDespesasCentro) ?>
                                </strong>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- 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-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;
        }

        .print-relatorio-periodo {
            font-size: 9pt;
            color: #666;
        }

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

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

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

        th,
        td {
            padding: 8px 12px !important;
            border: 1px solid #ddd !important;
        }

        th {
            background-color: #f8f9fa !important;
            font-weight: bold;
        }

        .text-end {
            text-align: right !important;
        }
    }
</style>

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