<?php
ob_start();

if (!function_exists('formatPercent')) {
    function formatPercent($value)
    {
        return number_format((float) $value, 2, ',', '.') . '%';
    }
}

// Preparar logo da empresa
$logoPath = null;
if (!empty($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 = $empresa['razao_social'] ?? $empresa['nome'] ?? $empresa['name'] ?? 'Empresa';
$empresaDoc = $empresa['cnpj'] ?? $empresa['document'] ?? '';
$resumo = $resumo ?? [];
?>

<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">Resumo de Comissões</li>
            </ol>
        </nav>
        <div class="d-flex justify-content-between align-items-center">
            <h2 class="mb-0"><i class="bi bi-cash-stack me-2 text-danger"></i> Resumo de Comissões</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-danger text-white">
        <i class="bi bi-funnel me-2"></i> Filtros
    </div>
    <div class="card-body">
        <form method="GET" action="<?= url('/relatorios/comissoes-resumo') ?>" class="row g-3">
            <div class="col-md-4">
                <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 ?? date('Y-m-01')) ?>" required>
            </div>
            <div class="col-md-4">
                <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 ?? date('Y-m-t')) ?>" required>
            </div>
            <div class="col-md-4 d-flex align-items-end">
                <button type="submit" class="btn btn-danger me-2">
                    <i class="bi bi-search me-2"></i> Filtrar
                </button>
                <a href="<?= url('/relatorios/comissoes-resumo') ?>" 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">Resumo de Comissões</div>
            <div class="print-relatorio-periodo">
                Período: <?= date('d/m/Y', strtotime($dataInicio ?? date('Y-m-01'))) ?> até
                <?= date('d/m/Y', strtotime($dataFim ?? date('Y-m-t'))) ?>
            </div>
        </div>
    </div>
</div>
<!-- Informações Detalhadas -->
<div class="card mb-4 resumo-card">
    <div class="card-header bg-danger text-white no-print">
        <i class="bi bi-info-circle me-2"></i> Informações do Período
        <div class="float-end">
            <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">
        <div class="row">
            <div class="col-md-6">
                <p><strong>Período:</strong> <?= date('d/m/Y', strtotime($dataInicio ?? date('Y-m-01'))) ?> até
                    <?= date('d/m/Y', strtotime($dataFim ?? date('Y-m-t'))) ?>
                </p>
                <p><strong>Total de Vendas:</strong> <?= $resumo['total_vendas'] ?? 0 ?> venda(s)</p>
                <p><strong>Total de Itens Vendidos:</strong> <?= $resumo['total_itens'] ?? 0 ?> item(ns)</p>
            </div>
            <div class="col-md-6">
                <p><strong>Valor Total Vendido:</strong> R$ <?= formatCurrency($resumo['total_valor_vendido'] ?? 0) ?>
                </p>
                <p><strong>Total de Comissões:</strong> <span class="text-danger fw-bold">R$
                        <?= formatCurrency($resumo['total_comissao'] ?? 0) ?></span></p>
                <p><strong>Percentual Médio de Comissão:</strong> <?= formatPercent($resumo['media_percentual'] ?? 0) ?>
                </p>
            </div>
        </div>

        <?php if (($resumo['total_valor_vendido'] ?? 0) > 0): ?>
            <hr>
            <div class="alert alert-info mb-0">
                <i class="bi bi-calculator me-2"></i>
                <strong>Relação:</strong>
                As comissões representam
                <strong><?= formatPercent((($resumo['total_comissao'] ?? 0) / ($resumo['total_valor_vendido'] ?? 1)) * 100) ?></strong>
                do valor total vendido no período.
            </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-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;
            page-break-inside: avoid;
        }

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

        .card-body {
            padding: 12px !important;
        }
    }
</style>

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