<?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');
$data = $data ?? date('Y-m-d');
?>

<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">Balanço Patrimonial</li>
            </ol>
        </nav>
        <div class="d-flex justify-content-between align-items-center">
            <h2 class="mb-0"><i class="bi bi-pie-chart me-2 text-info"></i> Balanço Patrimonial</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>

<!-- Filtros -->
<div class="card mb-4 no-print">
    <div class="card-header bg-info text-white">
        <i class="bi bi-funnel me-2"></i> Filtros
    </div>
    <div class="card-body">
        <form method="GET" action="<?= url('/relatorios/balanco') ?>" class="row g-3">
            <div class="col-md-4">
                <label for="data" class="form-label">Data</label>
                <input type="date" class="form-control" id="data" name="data" value="<?= htmlspecialchars($data) ?>"
                    required>
            </div>
            <div class="col-md-4 d-flex align-items-end">
                <button type="submit" class="btn btn-info me-2">
                    <i class="bi bi-search me-2"></i> Filtrar
                </button>
                <a href="<?= url('/relatorios/balanco') ?>" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-clockwise me-2"></i> Limpar
                </a>
            </div>
        </form>
    </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">Balanço Patrimonial</div>
            <div class="print-relatorio-periodo">Em <?= date('d/m/Y', strtotime($data)) ?> - Ano: <?= $ano ?></div>
        </div>
    </div>
</div>

<!-- Balanço Patrimonial -->
<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> Balanço Patrimonial - <?= date('d/m/Y', strtotime($data)) ?></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;">ATIVO</th>
                        <th class="text-end" style="min-width: 150px;">Valor (R$)</th>
                        <th style="min-width: 300px;">PASSIVO</th>
                        <th class="text-end" style="min-width: 150px;">Valor (R$)</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td colspan="2" class="bg-light"><strong>ATIVO CIRCULANTE</strong></td>
                        <td colspan="2" class="bg-light"><strong>PASSIVO CIRCULANTE</strong></td>
                    </tr>
                    <tr>
                        <td style="padding-left: 30px;">Contas a Receber</td>
                        <td class="text-end">R$ <?= formatCurrency($ativo['contas_receber'] ?? 0) ?></td>
                        <td style="padding-left: 30px;">Contas a Pagar</td>
                        <td class="text-end">R$ <?= formatCurrency($passivo['circulante'] ?? 0) ?></td>
                    </tr>
                    <tr>
                        <td style="padding-left: 30px;">Estoque</td>
                        <td class="text-end">R$ <?= formatCurrency($ativo['estoque'] ?? 0) ?></td>
                        <td colspan="2"></td>
                    </tr>
                    <tr class="table-primary">
                        <td><strong>Total do Ativo Circulante</strong></td>
                        <td class="text-end"><strong>R$ <?= formatCurrency($ativo['circulante'] ?? 0) ?></strong></td>
                        <td><strong>Total do Passivo Circulante</strong></td>
                        <td class="text-end"><strong>R$ <?= formatCurrency($passivo['circulante'] ?? 0) ?></strong></td>
                    </tr>
                    <tr>
                        <td colspan="2" class="bg-light"><strong>ATIVO NÃO CIRCULANTE</strong></td>
                        <td colspan="2" class="bg-light"><strong>PASSIVO NÃO CIRCULANTE</strong></td>
                    </tr>
                    <tr>
                        <td style="padding-left: 30px;">-</td>
                        <td class="text-end">-</td>
                        <td style="padding-left: 30px;">-</td>
                        <td class="text-end">-</td>
                    </tr>
                    <tr class="table-primary">
                        <td><strong>Total do Ativo Não Circulante</strong></td>
                        <td class="text-end"><strong>R$ <?= formatCurrency($ativo['nao_circulante'] ?? 0) ?></strong>
                        </td>
                        <td><strong>Total do Passivo Não Circulante</strong></td>
                        <td class="text-end"><strong>R$ <?= formatCurrency($passivo['nao_circulante'] ?? 0) ?></strong>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2"></td>
                        <td colspan="2" class="bg-light"><strong>PATRIMÔNIO LÍQUIDO</strong></td>
                    </tr>
                    <tr>
                        <td colspan="2"></td>
                        <td style="padding-left: 30px;">Resultado do Exercício (<?= $ano ?>)</td>
                        <td class="text-end">R$ <?= formatCurrency($resultadoExercicio ?? 0) ?></td>
                    </tr>
                    <tr class="table-<?= ($patrimonioLiquido ?? 0) >= 0 ? 'success' : 'danger' ?>">
                        <td colspan="2"></td>
                        <td><strong>Total do Patrimônio Líquido</strong></td>
                        <td class="text-end"><strong>R$ <?= formatCurrency($patrimonioLiquido ?? 0) ?></strong></td>
                    </tr>
                    <tr class="table-dark">
                        <td><strong>TOTAL DO ATIVO</strong></td>
                        <td class="text-end"><strong>R$ <?= formatCurrency($ativo['total'] ?? 0) ?></strong></td>
                        <td><strong>TOTAL DO PASSIVO + PL</strong></td>
                        <td class="text-end"><strong>R$ <?= formatCurrency($totalPassivoPL ?? 0) ?></strong></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </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 landscape;
            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;
            vertical-align: middle;
        }

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

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

        .bg-light {
            background-color: #f8f9fa !important;
        }
    }
</style>

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