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

<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">Apuração de Impostos</li>
            </ol>
        </nav>
        <div class="d-flex justify-content-between align-items-center">
            <h2 class="mb-0"><i class="bi bi-calculator me-2 text-dark"></i> Apuração de Impostos</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-dark text-white">
        <i class="bi bi-funnel me-2"></i> Filtros
    </div>
    <div class="card-body">
        <form method="GET" action="<?= url('/relatorios/apuracao-impostos') ?>" class="row g-3 align-items-end">
            <div class="col-md-5">
                <label for="data_inicio" class="form-label">Data Início</label>
                <input type="date" class="form-control" id="data_inicio" name="data_inicio"
                    value="<?= htmlspecialchars($dataInicio) ?>" required>
            </div>
            <div class="col-md-5">
                <label for="data_fim" class="form-label">Data Fim</label>
                <input type="date" class="form-control" id="data_fim" name="data_fim"
                    value="<?= htmlspecialchars($dataFim) ?>" required>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-dark w-100">
                    <i class="bi bi-search me-2"></i> Filtrar
                </button>
            </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">Apuração de Impostos</div>
            <div class="print-relatorio-periodo">Período: <?= date('d/m/Y', strtotime($dataInicio)) ?> a
                <?= date('d/m/Y', strtotime($dataFim)) ?>
            </div>
        </div>
    </div>
</div>

<!-- Tabela de Resultados -->
<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center bg-dark text-white no-print">
        <span><i class="bi bi-table me-2"></i> Apuração por 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>
            <span class="badge bg-light text-dark ms-2"><?= count($dados) ?> dia(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: 120px;">Data</th>
                            <th class="text-center" style="min-width: 100px;">Vendas</th>
                            <th class="text-end" style="min-width: 120px;">Faturamento</th>
                            <th class="text-end" style="min-width: 120px;">Base ICMS</th>
                            <th class="text-end" style="min-width: 120px;">ICMS</th>
                            <th class="text-end" style="min-width: 120px;">Base PIS</th>
                            <th class="text-end" style="min-width: 120px;">PIS</th>
                            <th class="text-end" style="min-width: 120px;">Base COFINS</th>
                            <th class="text-end" style="min-width: 120px;">COFINS</th>
                            <th class="text-end" style="min-width: 120px;">IPI</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($dados as $item): ?>
                            <tr>
                                <td><strong><?= date('d/m/Y', strtotime($item['data'])) ?></strong></td>
                                <td class="text-center"><?= number_format($item['total_vendas'] ?? 0, 0, ',', '.') ?></td>
                                <td class="text-end">R$ <?= number_format($item['total_faturamento'] ?? 0, 2, ',', '.') ?></td>
                                <td class="text-end">R$ <?= number_format($item['base_icms'] ?? 0, 2, ',', '.') ?></td>
                                <td class="text-end"><strong class="text-primary">R$
                                        <?= number_format($item['valor_icms'] ?? 0, 2, ',', '.') ?></strong></td>
                                <td class="text-end">R$ <?= number_format($item['base_pis'] ?? 0, 2, ',', '.') ?></td>
                                <td class="text-end"><strong class="text-success">R$
                                        <?= number_format($item['valor_pis'] ?? 0, 2, ',', '.') ?></strong></td>
                                <td class="text-end">R$ <?= number_format($item['base_cofins'] ?? 0, 2, ',', '.') ?></td>
                                <td class="text-end"><strong class="text-info">R$
                                        <?= number_format($item['valor_cofins'] ?? 0, 2, ',', '.') ?></strong></td>
                                <td class="text-end"><strong class="text-warning">R$
                                        <?= number_format($item['valor_ipi'] ?? 0, 2, ',', '.') ?></strong></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot class="table-dark">
                        <tr>
                            <th>TOTAL</th>
                            <th class="text-center"><?= number_format($totais['total_vendas'], 0, ',', '.') ?></th>
                            <th class="text-end">R$
                                <?= number_format(array_sum(array_column($dados, 'total_faturamento')), 2, ',', '.') ?></th>
                            <th class="text-end">R$ <?= number_format($totais['base_icms'], 2, ',', '.') ?></th>
                            <th class="text-end"><strong>R$
                                    <?= number_format($totais['valor_icms'], 2, ',', '.') ?></strong></th>
                            <th class="text-end">R$ <?= number_format($totais['base_pis'], 2, ',', '.') ?></th>
                            <th class="text-end"><strong>R$ <?= number_format($totais['valor_pis'], 2, ',', '.') ?></strong>
                            </th>
                            <th class="text-end">R$ <?= number_format($totais['base_cofins'], 2, ',', '.') ?></th>
                            <th class="text-end"><strong>R$
                                    <?= number_format($totais['valor_cofins'], 2, ',', '.') ?></strong></th>
                            <th class="text-end"><strong>R$ <?= number_format($totais['valor_ipi'], 2, ',', '.') ?></strong>
                            </th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        <?php else: ?>
            <div class="alert alert-info text-center m-4">
                <i class="bi bi-info-circle fs-3 d-block mb-2"></i>
                <h5>Nenhum dado encontrado</h5>
                <p class="mb-0">Não há movimentações fiscais no período selecionado.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Resumo -->
<?php if (!empty($dados)): ?>
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-primary">
                <div class="card-body text-center">
                    <h6 class="text-muted mb-2">ICMS</h6>
                    <h3 class="text-primary mb-0">R$ <?= number_format($totais['valor_icms'], 2, ',', '.') ?></h3>
                    <small class="text-muted">Base: R$ <?= number_format($totais['base_icms'], 2, ',', '.') ?></small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-success">
                <div class="card-body text-center">
                    <h6 class="text-muted mb-2">PIS</h6>
                    <h3 class="text-success mb-0">R$ <?= number_format($totais['valor_pis'], 2, ',', '.') ?></h3>
                    <small class="text-muted">Base: R$ <?= number_format($totais['base_pis'], 2, ',', '.') ?></small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-info">
                <div class="card-body text-center">
                    <h6 class="text-muted mb-2">COFINS</h6>
                    <h3 class="text-info mb-0">R$ <?= number_format($totais['valor_cofins'], 2, ',', '.') ?></h3>
                    <small class="text-muted">Base: R$ <?= number_format($totais['base_cofins'], 2, ',', '.') ?></small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-warning">
                <div class="card-body text-center">
                    <h6 class="text-muted mb-2">IPI</h6>
                    <h3 class="text-warning mb-0">R$ <?= number_format($totais['valor_ipi'], 2, ',', '.') ?></h3>
                    <small class="text-muted">Total de Vendas:
                        <?= number_format($totais['total_vendas'], 0, ',', '.') ?></small>
                </div>
            </div>
        </div>
    </div>

    <div class="card mb-4 no-print">
        <div class="card-header bg-dark text-white">
            <i class="bi bi-calculator me-2"></i> Total de Impostos
        </div>
        <div class="card-body">
            <div class="row text-center">
                <div class="col-md-12">
                    <h2 class="mb-0">
                        R$
                        <?= number_format($totais['valor_icms'] + $totais['valor_pis'] + $totais['valor_cofins'] + $totais['valor_ipi'], 2, ',', '.') ?>
                    </h2>
                    <small class="text-muted">Soma de todos os impostos apurados no período</small>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<style>
    @media print {
        .no-print {
            display: none !important;
        }

        .print-header {
            display: block !important;
            margin-bottom: 20px;
            padding: 20px;
            border-bottom: 2px solid #000;
        }

        .print-logo {
            max-width: 100px;
            max-height: 100px;
            margin-right: 20px;
        }

        .print-empresa-nome {
            font-size: 18px;
            font-weight: bold;
        }

        .print-empresa-doc {
            font-size: 12px;
            color: #666;
        }

        .print-relatorio-titulo {
            font-size: 16px;
            font-weight: bold;
            margin-top: 10px;
        }

        .print-relatorio-periodo {
            font-size: 12px;
            color: #666;
        }

        .table {
            font-size: 11px;
        }

        th,
        td {
            padding: 6px 8px !important;
            border: 1px solid #ddd !important;
        }
    }
</style>

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