<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
.kpi-card {
    background:#fff; border:1px solid #e2e6ea; border-radius:10px;
    padding:16px 18px; margin-bottom:14px; border-left:4px solid #1e3a5f;
    position:relative; overflow:hidden;
}
.kpi-card .kv { font-size:26px; font-weight:700; color:#1e3a5f; line-height:1; }
.kpi-card .kl { font-size:11px; color:#888; text-transform:uppercase; letter-spacing:.5px; margin-top:4px; }
.kpi-card .ki { position:absolute; right:14px; top:50%; transform:translateY(-50%); font-size:42px; opacity:.07; color:#1e3a5f; }
.kpi-card.g { border-left-color:#2e7d32; } .kpi-card.g .kv { color:#2e7d32; }
.kpi-card.r { border-left-color:#c0392b; } .kpi-card.r .kv { color:#c0392b; }
.kpi-card.o { border-left-color:#d35400; } .kpi-card.o .kv { color:#d35400; }
.kpi-card.p { border-left-color:#7f3fbf; } .kpi-card.p .kv { color:#7f3fbf; }

.chart-box { background:#fff; border:1px solid #e2e6ea; border-radius:10px; padding:16px 18px; margin-bottom:16px; }
.chart-box h4 { font-size:13px; font-weight:600; color:#1e3a5f; margin:0 0 14px; display:flex; align-items:center; gap:7px; }
.chart-box h4 .fa { font-size:14px; opacity:.7; }

.prod-row { display:flex; align-items:center; gap:10px; padding:9px 0; border-bottom:1px solid #f0f2f5; }
.prod-row:last-child { border-bottom:none; }
.prod-avatar { width:32px; height:32px; border-radius:50%; background:linear-gradient(135deg,#4a9fd4,#1e3a5f); display:flex; align-items:center; justify-content:center; font-size:11px; font-weight:700; color:#fff; flex-shrink:0; }
.prod-name { flex:1; font-size:13px; font-weight:600; color:#222; }
.prod-bar { flex:2; height:8px; background:#f0f2f5; border-radius:4px; overflow:hidden; }
.prod-bar-fill { height:100%; border-radius:4px; background:#1e3a5f; }
.prod-nums { font-size:11px; color:#888; white-space:nowrap; }
.prod-nums strong { color:#1e3a5f; }

.stage-item { display:flex; align-items:center; gap:10px; padding:8px 0; border-bottom:1px solid #f0f2f5; }
.stage-item:last-child { border-bottom:none; }
.stage-dot { width:10px; height:10px; border-radius:50%; flex-shrink:0; }
.stage-label { flex:1; font-size:12.5px; color:#333; }
.stage-bar { flex:2; height:6px; background:#f0f2f5; border-radius:3px; overflow:hidden; }
.stage-bar-fill { height:100%; border-radius:3px; }
.stage-count { font-size:12px; font-weight:700; color:#1e3a5f; min-width:28px; text-align:right; }

.nav-tabs-custom { border-radius:10px; overflow:hidden; box-shadow:0 1px 6px rgba(0,0,0,.07); }
.nav-tabs-custom > .nav-tabs { background:#f8f9fb; border-bottom:1px solid #e2e6ea; }
.nav-tabs-custom > .nav-tabs > li > a { border:none; border-radius:0; color:#666; padding:12px 16px; font-size:13px; }
.nav-tabs-custom > .nav-tabs > li.active > a { color:#1e3a5f; font-weight:600; border-bottom:3px solid #1e3a5f; background:#fff; }
.nav-tabs-custom > .tab-content { background:#fff; padding:16px; }
</style>

<section class="content-header">
    <h1><i class="fa fa-line-chart"></i> <?php echo lang('reports') ?> <small>Painel Gerencial do Escritório</small></h1>
    <ol class="breadcrumb">
        <li><a href="<?php echo site_url('admin') ?>"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        <li class="active"><?php echo lang('reports') ?></li>
    </ol>
</section>

<section class="content">

<!-- Filtro cliente -->
<div class="box box-default" style="margin-bottom:16px">
    <div class="box-body" style="padding:12px 16px">
        <form method="get" class="form-inline">
            <div class="form-group" style="margin-right:10px">
                <label style="font-size:12px;font-weight:600;margin-right:6px"><i class="fa fa-user text-muted"></i> Filtrar por Cliente:</label>
                <select name="client_id" class="form-control" style="min-width:200px;height:32px;font-size:12px">
                    <option value="">Todos os clientes</option>
                    <?php foreach($all_clients ?? [] as $cl): ?>
                    <option value="<?php echo $cl->id ?>" <?php echo ($client_id ?? '') == $cl->id ? 'selected' : '' ?>><?php echo htmlspecialchars($cl->name) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-search"></i> Filtrar</button>
            <a href="<?php echo site_url('admin/reports') ?>" class="btn btn-default btn-sm">Limpar</a>
        </form>
    </div>
</div>

<!-- KPIs -->
<?php if(isset($kpis)): ?>
<div class="row">
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="kpi-card">
            <div class="kv"><?php echo $kpis->total_clientes ?? 0 ?></div>
            <div class="kl">Total Clientes</div>
            <i class="fa fa-users ki"></i>
        </div>
    </div>
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="kpi-card">
            <div class="kv"><?php echo $kpis->total_processos ?? 0 ?></div>
            <div class="kl">Total Processos</div>
            <i class="fa fa-folder ki"></i>
        </div>
    </div>
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="kpi-card g">
            <div class="kv"><?php echo $kpis->processos_ativos ?? 0 ?></div>
            <div class="kl">Processos Ativos</div>
            <i class="fa fa-folder-open ki"></i>
        </div>
    </div>
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="kpi-card o">
            <div class="kv"><?php echo $kpis->tarefas_pendentes ?? 0 ?></div>
            <div class="kl">Tarefas Pendentes</div>
            <i class="fa fa-tasks ki"></i>
        </div>
    </div>
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="kpi-card g">
            <div class="kv">R$ <?php echo number_format(($kpis->honorarios_mes ?? 0)/1000, 1) ?>k</div>
            <div class="kl">Honorários/Mês</div>
            <i class="fa fa-money ki"></i>
        </div>
    </div>
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="kpi-card r">
            <div class="kv">R$ <?php echo number_format(($kpis->a_receber ?? 0)/1000, 1) ?>k</div>
            <div class="kl">A Receber</div>
            <i class="fa fa-clock-o ki"></i>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Linha 1: Crescimento + Financeiro -->
<div class="row">
    <!-- Novos clientes e processos -->
    <div class="col-md-6">
        <div class="chart-box">
            <h4><i class="fa fa-line-chart"></i> Crescimento — Novos Clientes & Processos (12 meses)</h4>
            <div id="chart-crescimento" style="height:240px"></div>
        </div>
    </div>
    <!-- Financeiro por mês -->
    <div class="col-md-6">
        <div class="chart-box">
            <h4><i class="fa fa-money"></i> Financeiro Mensal — Receitas x Despesas (12 meses)</h4>
            <div id="chart-financeiro" style="height:240px"></div>
        </div>
    </div>
</div>

<!-- Linha 2: Honorários + Produtividade -->
<div class="row">
    <div class="col-md-7">
        <div class="nav-tabs-custom">
            <ul class="nav nav-tabs">
                <li class="active"><a href="#tab-mes" data-toggle="tab"><i class="fa fa-calendar"></i> Por Mês</a></li>
                <li><a href="#tab-semana" data-toggle="tab"><i class="fa fa-calendar-o"></i> Por Semana</a></li>
                <li><a href="#tab-ano" data-toggle="tab"><i class="fa fa-calendar-check-o"></i> Por Ano</a></li>
                <li><a href="#tab-cliente" data-toggle="tab"><i class="fa fa-user"></i> Por Cliente</a></li>
            </ul>
            <div class="tab-content">
                <div class="tab-pane active" id="tab-mes">
                    <h4 style="font-size:13px;font-weight:600;color:#1e3a5f;margin-bottom:12px"><i class="fa fa-bar-chart"></i> Honorários por Mês</h4>
                    <div id="chart-mes" style="height:220px"></div>
                </div>
                <div class="tab-pane" id="tab-semana">
                    <h4 style="font-size:13px;font-weight:600;color:#1e3a5f;margin-bottom:12px"><i class="fa fa-bar-chart"></i> Honorários por Semana</h4>
                    <div id="chart-semana" style="height:220px"></div>
                </div>
                <div class="tab-pane" id="tab-ano">
                    <h4 style="font-size:13px;font-weight:600;color:#1e3a5f;margin-bottom:12px"><i class="fa fa-bar-chart"></i> Honorários por Ano</h4>
                    <div id="chart-ano" style="height:220px"></div>
                </div>
                <div class="tab-pane" id="tab-cliente">
                    <h4 style="font-size:13px;font-weight:600;color:#1e3a5f;margin-bottom:12px"><i class="fa fa-users"></i> Top Clientes por Honorários</h4>
                    <div id="chart-cliente" style="height:220px"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Produtividade -->
    <div class="col-md-5">
        <div class="chart-box" style="height:100%">
            <h4><i class="fa fa-trophy"></i> Produtividade por Colaborador</h4>
            <?php if(!empty($productivity)):
                $max_tasks = max(array_column((array)$productivity, 'total_tarefas')) ?: 1;
                foreach($productivity as $p):
                    $parts = explode(' ', trim($p->name ?? ''));
                    $ini = strtoupper(substr($parts[0],0,1).(isset($parts[1])?substr($parts[1],0,1):''));
                    $pct = $max_tasks > 0 ? round(($p->total_tarefas / $max_tasks) * 100) : 0;
                    $conc_pct = $p->total_tarefas > 0 ? round(($p->concluidas / $p->total_tarefas) * 100) : 0;
            ?>
            <div class="prod-row">
                <div class="prod-avatar"><?php echo $ini ?></div>
                <div style="flex:1;min-width:0">
                    <div class="prod-name"><?php echo htmlspecialchars($p->name ?? '') ?></div>
                    <div class="prod-bar" title="<?php echo $conc_pct ?>% concluídas">
                        <div class="prod-bar-fill" style="width:<?php echo $conc_pct ?>%;background:<?php echo $conc_pct>=70?'#2e7d32':($conc_pct>=40?'#1e3a5f':'#d35400') ?>"></div>
                    </div>
                </div>
                <div class="prod-nums">
                    <strong><?php echo $p->concluidas ?></strong>/<?php echo $p->total_tarefas ?>
                    <?php if($p->vencidas > 0): ?>
                    <span style="color:#c0392b;margin-left:4px"><i class="fa fa-clock-o"></i> <?php echo $p->vencidas ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; else: ?>
            <div class="text-center text-muted" style="padding:30px"><i class="fa fa-trophy" style="font-size:36px;opacity:.2;display:block;margin-bottom:8px"></i>Nenhum dado disponível</div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Linha 3: Fases + Agenda/Diligências + Top clientes financeiro -->
<div class="row">
    <!-- Processos por fase -->
    <div class="col-md-4">
        <div class="chart-box">
            <h4><i class="fa fa-sitemap"></i> Processos por Fase</h4>
            <?php
            $stage_colors = ['#1e3a5f','#2e75b6','#2e7d32','#d35400','#c0392b','#7f3fbf','#0097a7','#f39c12'];
            if(!empty($cases_by_stage)):
                $max_stage = max(array_column((array)$cases_by_stage, 'total')) ?: 1;
                foreach($cases_by_stage as $i => $s):
                    $cor = $stage_colors[$i % count($stage_colors)];
                    $pct = round(($s->total / $max_stage) * 100);
            ?>
            <div class="stage-item">
                <div class="stage-dot" style="background:<?php echo $cor ?>"></div>
                <div class="stage-label"><?php echo htmlspecialchars($s->stage ?? 'Sem fase') ?></div>
                <div class="stage-bar"><div class="stage-bar-fill" style="width:<?php echo $pct ?>%;background:<?php echo $cor ?>"></div></div>
                <div class="stage-count"><?php echo $s->total ?></div>
            </div>
            <?php endforeach; else: ?>
            <div class="text-center text-muted" style="padding:20px">Nenhum dado disponível</div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Agenda e Diligências -->
    <div class="col-md-4">
        <div class="chart-box">
            <h4><i class="fa fa-calendar"></i> Agendamentos & Diligências (6 meses)</h4>
            <div id="chart-agenda" style="height:200px"></div>
        </div>
    </div>

    <!-- Top clientes financeiro -->
    <div class="col-md-4">
        <div class="chart-box">
            <h4><i class="fa fa-users"></i> Top 10 Clientes — Financeiro</h4>
            <?php if(!empty($fin_clients)):
                $max_val = max(array_column((array)$fin_clients, 'recebido')) ?: 1;
                foreach($fin_clients as $fc):
                    $pct = round(($fc->recebido / $max_val) * 100);
            ?>
            <div class="stage-item">
                <div class="stage-label" style="font-size:12px"><?php echo htmlspecialchars(mb_substr($fc->name ?? '—', 0, 20)) ?></div>
                <div class="stage-bar"><div class="stage-bar-fill" style="width:<?php echo $pct ?>%;background:#2e7d32"></div></div>
                <div class="stage-count" style="font-size:11px;min-width:60px;color:#2e7d32">R$ <?php echo number_format($fc->recebido, 0, ',', '.') ?></div>
            </div>
            <?php endforeach; else: ?>
            <div class="text-center text-muted" style="padding:20px">Nenhum dado disponível</div>
            <?php endif; ?>
        </div>
    </div>
</div>

</section>

<!-- Scripts -->
<link rel="stylesheet" href="<?php echo base_url('assets/css/morris/morris.css') ?>">
<script src="<?php echo base_url('assets/js/plugins/morris/raphael-min.js') ?>"></script>
<script src="<?php echo base_url('assets/js/plugins/morris/morris.min.js') ?>"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>

<script>
<?php
// Prepara dados JSON
$d_crescimento_labels = $d_clientes = $d_processos = [];
$all_months = [];
foreach((array)$new_clients as $r) $all_months[$r->mes_label]['clientes'] = (int)$r->total;
foreach((array)$new_cases   as $r) $all_months[$r->mes_label]['processos'] = (int)$r->total;
foreach($all_months as $m => $v) {
    $d_crescimento_labels[] = $m;
    $d_clientes[]  = $v['clientes']  ?? 0;
    $d_processos[] = $v['processos'] ?? 0;
}

$d_fin_labels = $d_recebido = $d_pago = $d_a_receber = [];
foreach((array)$fin_months as $r) {
    $d_fin_labels[]  = $r->mes_label;
    $d_recebido[]    = (float)$r->recebido;
    $d_pago[]        = (float)$r->pago;
    $d_a_receber[]   = (float)$r->a_receber;
}

$d_agenda_labels = $d_agend = $d_dilig = [];
$agenda_months = [];
foreach((array)$appointments as $r) $agenda_months[$r->mes_label]['agend'] = (int)$r->total;
foreach((array)$diligencias   as $r) $agenda_months[$r->mes_label]['dilig'] = (int)$r->total;
foreach($agenda_months as $m => $v) {
    $d_agenda_labels[] = $m;
    $d_agend[] = $v['agend'] ?? 0;
    $d_dilig[] = $v['dilig'] ?? 0;
}
?>

// Chart.js — Crescimento
(function() {
    var ctx = document.getElementById('chart-crescimento');
    if (!ctx) return;
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($d_crescimento_labels) ?>,
            datasets: [
                { label:'Novos Clientes', data: <?php echo json_encode($d_clientes) ?>, borderColor:'#1e3a5f', backgroundColor:'rgba(30,58,95,.1)', tension:.4, fill:true, pointRadius:4 },
                { label:'Novos Processos', data: <?php echo json_encode($d_processos) ?>, borderColor:'#2e7d32', backgroundColor:'rgba(46,125,50,.08)', tension:.4, fill:true, pointRadius:4 }
            ]
        },
        options: { responsive:true, maintainAspectRatio:false, plugins:{ legend:{ position:'top' } }, scales:{ y:{ beginAtZero:true, ticks:{ precision:0 } } } }
    });
})();

// Chart.js — Financeiro
(function() {
    var ctx = document.getElementById('chart-financeiro');
    if (!ctx) return;
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($d_fin_labels) ?>,
            datasets: [
                { label:'Recebido', data: <?php echo json_encode($d_recebido) ?>, backgroundColor:'rgba(46,125,50,.8)', borderRadius:4 },
                { label:'Despesas', data: <?php echo json_encode($d_pago) ?>, backgroundColor:'rgba(192,57,43,.75)', borderRadius:4 },
                { label:'A Receber', data: <?php echo json_encode($d_a_receber) ?>, backgroundColor:'rgba(211,84,0,.6)', borderRadius:4 }
            ]
        },
        options: {
            responsive:true, maintainAspectRatio:false,
            plugins:{ legend:{ position:'top' }, tooltip:{ callbacks:{ label:function(c){ return c.dataset.label+': R$ '+c.parsed.y.toLocaleString('pt-BR',{minimumFractionDigits:2}); } } } },
            scales:{ y:{ beginAtZero:true, ticks:{ callback:function(v){ return 'R$ '+v.toLocaleString('pt-BR',{minimumFractionDigits:0}); } } } }
        }
    });
})();

// Chart.js — Agenda & Diligências
(function() {
    var ctx = document.getElementById('chart-agenda');
    if (!ctx) return;
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($d_agenda_labels) ?>,
            datasets: [
                { label:'Agendamentos', data: <?php echo json_encode($d_agend) ?>, backgroundColor:'rgba(30,58,95,.8)', borderRadius:4 },
                { label:'Diligências',  data: <?php echo json_encode($d_dilig) ?>, backgroundColor:'rgba(211,84,0,.75)', borderRadius:4 }
            ]
        },
        options: { responsive:true, maintainAspectRatio:false, plugins:{ legend:{ position:'top' } }, scales:{ y:{ beginAtZero:true, ticks:{ precision:0 } } } }
    });
})();

// Morris — Honorários por mês
<?php if(!empty($months)): ?>
Morris.Bar({
    element: 'chart-mes', resize: true, hideHover: 'auto', barColors: ['#1e3a5f'],
    data: <?php $d=[]; foreach($months as $r) $d[]=['y'=>$r->date,'a'=>(float)$r->amount]; echo json_encode($d) ?>,
    xkey:'y', ykeys:['a'], labels:['Honorários']
});
<?php endif; ?>
<?php if(!empty($weeks)): ?>
Morris.Bar({
    element: 'chart-semana', resize: true, hideHover: 'auto', barColors: ['#2e7d32'],
    data: <?php $d=[]; foreach($weeks as $r) $d[]=['y'=>$r->date,'a'=>(float)$r->amount]; echo json_encode($d) ?>,
    xkey:'y', ykeys:['a'], labels:['Honorários']
});
<?php endif; ?>
<?php if(!empty($years)): ?>
Morris.Bar({
    element: 'chart-ano', resize: true, hideHover: 'auto', barColors: ['#c0392b'],
    data: <?php $d=[]; foreach($years as $r) $d[]=['y'=>substr($r->date,0,4),'a'=>(float)$r->amount]; echo json_encode($d) ?>,
    xkey:'y', ykeys:['a'], labels:['Honorários']
});
<?php endif; ?>
<?php if(!empty($clients)): ?>
Morris.Bar({
    element: 'chart-cliente', resize: true, hideHover: 'auto', barColors: ['#7f3fbf'],
    data: <?php $d=[]; foreach($clients as $r) $d[]=['y'=>mb_substr($r->name??'',0,12),'a'=>(float)$r->amount]; echo json_encode($d) ?>,
    xkey:'y', ykeys:['a'], labels:['Honorários']
});
<?php endif; ?>
</script>
