<?php
/**
 * ASISMA CRM - Reportes e Indicadores
 */
$_estados = arr_estados_embudo();
$_origenes = arr_origenes_lead();

// Total para calcular proporciones de barras
$maxEstado = 1;
foreach ($leadsPorEstado as $e) { $maxEstado = max($maxEstado, (int)$e['cantidad']); }
$maxOrigen = 1;
foreach ($leadsPorOrigen as $o) { $maxOrigen = max($maxOrigen, (int)$o['cantidad']); }

function formatear_segundos($seg) {
    if ($seg === null || $seg === '') return '—';
    $seg = (int)$seg;
    if ($seg < 60) return $seg . ' seg';
    if ($seg < 3600) return round($seg / 60, 1) . ' min';
    return round($seg / 3600, 1) . ' hrs';
}
?>
<!-- Header -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8">
    <div>
        <h1 class="text-3xl font-extrabold text-white tracking-tight">Reportes e Indicadores</h1>
        <p class="text-slate-400 text-sm mt-1">Resumen estadístico del embudo de ventas y rendimiento de la red.</p>
    </div>
    <a href="<?php echo APP_URL; ?>/reportes/export"
       class="px-4 py-2.5 bg-emerald-600 hover:bg-emerald-500 text-white rounded-xl text-sm font-semibold transition-all shadow-md shadow-emerald-600/10 flex items-center gap-1.5 self-start">
        <i data-lucide="download" class="w-4 h-4"></i>
        <span>Exportar Leads (CSV)</span>
    </a>
</div>

<!-- KPI Cards -->
<div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
    <div class="bg-slate-900 border border-slate-800 rounded-2xl p-5 shadow-xl">
        <div class="flex items-center justify-between mb-2">
            <span class="text-xs font-semibold text-slate-500 uppercase tracking-wider">Leads Totales</span>
            <i data-lucide="target" class="w-4 h-4 text-blue-500"></i>
        </div>
        <span class="text-3xl font-extrabold text-white"><?php echo (int)$totales['total']; ?></span>
        <span class="block text-xs text-slate-500 mt-1"><?php echo (int)$totales['activos']; ?> activos en el embudo</span>
    </div>
    <div class="bg-slate-900 border border-slate-800 rounded-2xl p-5 shadow-xl">
        <div class="flex items-center justify-between mb-2">
            <span class="text-xs font-semibold text-slate-500 uppercase tracking-wider">Tasa de Conversión</span>
            <i data-lucide="trending-up" class="w-4 h-4 text-emerald-500"></i>
        </div>
        <span class="text-3xl font-extrabold text-emerald-400"><?php echo $tasaConversion; ?>%</span>
        <span class="block text-xs text-slate-500 mt-1"><?php echo (int)$totales['ganados']; ?> ganados / <?php echo (int)$totales['perdidos']; ?> perdidos</span>
    </div>
    <div class="bg-slate-900 border border-slate-800 rounded-2xl p-5 shadow-xl">
        <div class="flex items-center justify-between mb-2">
            <span class="text-xs font-semibold text-slate-500 uppercase tracking-wider">Respuesta Promedio</span>
            <i data-lucide="timer" class="w-4 h-4 text-amber-500"></i>
        </div>
        <span class="text-3xl font-extrabold text-white"><?php echo formatear_segundos($respuesta['promedio_seg']); ?></span>
        <span class="block text-xs text-slate-500 mt-1"><?php echo (int)$respuesta['aceptadas']; ?> aceptadas · <?php echo (int)$respuesta['timeouts']; ?> timeouts</span>
    </div>
    <div class="bg-slate-900 border border-slate-800 rounded-2xl p-5 shadow-xl">
        <div class="flex items-center justify-between mb-2">
            <span class="text-xs font-semibold text-slate-500 uppercase tracking-wider">Cotizaciones Aceptadas</span>
            <i data-lucide="file-check-2" class="w-4 h-4 text-purple-500"></i>
        </div>
        <span class="text-3xl font-extrabold text-white"><?php echo (int)$cotizaciones['aceptadas']; ?><span class="text-base text-slate-500 font-semibold"> / <?php echo (int)$cotizaciones['total']; ?></span></span>
        <span class="block text-xs text-slate-500 mt-1">$<?php echo number_format((float)$cotizaciones['monto_aceptado'], 0, ',', '.'); ?> CLP aceptado</span>
    </div>
</div>

<div class="grid grid-cols-1 md:grid-cols-2 gap-8 mb-8">

    <!-- Leads por Estado -->
    <div class="bg-slate-900 border border-slate-800 rounded-2xl p-6 shadow-xl">
        <h3 class="text-sm font-bold text-white mb-6 uppercase tracking-wider flex items-center gap-2">
            <i data-lucide="filter" class="w-4 h-4 text-blue-500"></i>
            <span>Leads por Etapa del Embudo</span>
        </h3>

        <div class="space-y-4">
            <?php if (empty($leadsPorEstado)): ?>
                <p class="text-xs text-slate-500 text-center py-8">No hay suficientes datos registrados.</p>
            <?php else: ?>
                <?php foreach ($leadsPorEstado as $e): ?>
                    <?php $est = isset($_estados[$e['estado_embudo']]) ? $_estados[$e['estado_embudo']] : array('label' => $e['estado_embudo']); ?>
                    <div class="flex items-center justify-between text-sm">
                        <span class="font-semibold text-slate-300"><?php echo $est['label']; ?></span>
                        <div class="flex items-center gap-3 w-2/3">
                            <div class="flex-1 bg-slate-950 h-2 rounded-full overflow-hidden">
                                <div class="bg-blue-500 h-full rounded-full" style="width: <?php echo round(($e['cantidad'] / $maxEstado) * 100); ?>%"></div>
                            </div>
                            <span class="font-mono font-bold text-slate-200 text-xs w-8 text-right"><?php echo $e['cantidad']; ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- Leads por Origen -->
    <div class="bg-slate-900 border border-slate-800 rounded-2xl p-6 shadow-xl">
        <h3 class="text-sm font-bold text-white mb-6 uppercase tracking-wider flex items-center gap-2">
            <i data-lucide="compass" class="w-4 h-4 text-indigo-500"></i>
            <span>Leads por Origen / Canal</span>
        </h3>

        <div class="space-y-4">
            <?php if (empty($leadsPorOrigen)): ?>
                <p class="text-xs text-slate-500 text-center py-8">No hay suficientes datos registrados.</p>
            <?php else: ?>
                <?php foreach ($leadsPorOrigen as $o): ?>
                    <div class="flex items-center justify-between text-sm">
                        <span class="font-semibold text-slate-300 capitalize"><?php echo isset($_origenes[$o['origen']]) ? $_origenes[$o['origen']] : $o['origen']; ?></span>
                        <div class="flex items-center gap-3 w-2/3">
                            <div class="flex-1 bg-slate-950 h-2 rounded-full overflow-hidden">
                                <div class="bg-indigo-500 h-full rounded-full" style="width: <?php echo round(($o['cantidad'] / $maxOrigen) * 100); ?>%"></div>
                            </div>
                            <span class="font-mono font-bold text-slate-200 text-xs w-8 text-right"><?php echo $o['cantidad']; ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Evolución Mensual -->
<div class="bg-slate-900 border border-slate-800 rounded-2xl p-6 shadow-xl mb-8">
    <h3 class="text-sm font-bold text-white mb-6 uppercase tracking-wider flex items-center gap-2">
        <i data-lucide="calendar-range" class="w-4 h-4 text-emerald-500"></i>
        <span>Evolución Mensual (últimos 6 meses)</span>
    </h3>
    <?php if (empty($serieMensual)): ?>
        <p class="text-xs text-slate-500 text-center py-8">Aún no hay datos históricos suficientes.</p>
    <?php else: ?>
        <?php $maxMes = 1; foreach ($serieMensual as $sm) { $maxMes = max($maxMes, (int)$sm['creados']); } ?>
        <div class="flex items-end gap-4 h-40 px-2">
            <?php foreach ($serieMensual as $sm): ?>
                <div class="flex-1 flex flex-col items-center gap-1 h-full justify-end">
                    <span class="text-[10px] font-mono text-slate-400"><?php echo (int)$sm['creados']; ?></span>
                    <div class="w-full max-w-[48px] flex gap-1 items-end" style="height: <?php echo round(((int)$sm['creados'] / $maxMes) * 100); ?>%">
                        <div class="flex-1 bg-blue-500/70 rounded-t-md h-full" title="Creados: <?php echo (int)$sm['creados']; ?>"></div>
                        <?php $altoGanado = (int)$sm['creados'] > 0 ? round(((int)$sm['ganados'] / (int)$sm['creados']) * 100) : 0; ?>
                        <div class="flex-1 bg-emerald-500/80 rounded-t-md" style="height: <?php echo $altoGanado; ?>%" title="Ganados: <?php echo (int)$sm['ganados']; ?>"></div>
                    </div>
                    <span class="text-[10px] text-slate-500 font-semibold"><?php echo date('M-y', strtotime($sm['mes'] . '-01')); ?></span>
                </div>
            <?php endforeach; ?>
        </div>
        <div class="flex items-center gap-4 mt-4 justify-center text-[11px] text-slate-400">
            <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-sm bg-blue-500/70"></span> Leads creados</span>
            <span class="flex items-center gap-1.5"><span class="w-2.5 h-2.5 rounded-sm bg-emerald-500/80"></span> Ganados</span>
        </div>
    <?php endif; ?>
</div>

<?php if (!empty($rankingFranquiciados)): ?>
<!-- Ranking de Franquiciados (solo admin) -->
<div class="bg-slate-900 border border-slate-800 rounded-2xl overflow-hidden shadow-xl">
    <div class="p-6 pb-0">
        <h3 class="text-sm font-bold text-white mb-4 uppercase tracking-wider flex items-center gap-2">
            <i data-lucide="trophy" class="w-4 h-4 text-amber-500"></i>
            <span>Ranking de Franquiciados</span>
        </h3>
    </div>
    <div class="overflow-x-auto">
        <table class="w-full text-left text-sm">
            <thead>
                <tr class="bg-slate-950 border-y border-slate-800 text-slate-400 uppercase text-xs tracking-wider">
                    <th class="px-6 py-3.5 font-semibold w-12">#</th>
                    <th class="px-6 py-3.5 font-semibold">Franquiciado</th>
                    <th class="px-6 py-3.5 font-semibold">Zona / Vertical</th>
                    <th class="px-6 py-3.5 font-semibold text-center">Leads</th>
                    <th class="px-6 py-3.5 font-semibold text-center">Ganados</th>
                    <th class="px-6 py-3.5 font-semibold text-center">Perdidos</th>
                    <th class="px-6 py-3.5 font-semibold text-center">Conversión</th>
                    <th class="px-6 py-3.5 font-semibold text-right">Respuesta Prom.</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-850 text-slate-300">
                <?php $pos = 0; foreach ($rankingFranquiciados as $rk): $pos++; ?>
                    <?php
                    $cerrados = (int)$rk['ganados'] + (int)$rk['perdidos'];
                    $conv = $cerrados > 0 ? round(((int)$rk['ganados'] / $cerrados) * 100) : null;
                    ?>
                    <tr class="hover:bg-slate-800/30 transition-colors">
                        <td class="px-6 py-3.5 font-mono text-xs <?php echo $pos <= 3 ? 'text-amber-400 font-bold' : 'text-slate-500'; ?>"><?php echo $pos; ?></td>
                        <td class="px-6 py-3.5 font-bold text-slate-100"><?php echo htmlspecialchars($rk['nombre_fantasia']); ?> <span class="text-slate-500 font-normal text-xs">#<?php echo $rk['id']; ?></span></td>
                        <td class="px-6 py-3.5 text-xs text-slate-400"><?php echo htmlspecialchars($rk['region_nombre']); ?> · <?php echo htmlspecialchars($rk['vertical_nombre']); ?></td>
                        <td class="px-6 py-3.5 text-center font-mono font-bold"><?php echo (int)$rk['total_leads']; ?></td>
                        <td class="px-6 py-3.5 text-center font-mono font-bold text-emerald-400"><?php echo (int)$rk['ganados']; ?></td>
                        <td class="px-6 py-3.5 text-center font-mono text-red-400"><?php echo (int)$rk['perdidos']; ?></td>
                        <td class="px-6 py-3.5 text-center">
                            <?php if ($conv !== null): ?>
                                <span class="text-xs font-bold <?php echo $conv >= 50 ? 'text-emerald-400' : ($conv >= 25 ? 'text-amber-400' : 'text-red-400'); ?>"><?php echo $conv; ?>%</span>
                            <?php else: ?>
                                <span class="text-xs text-slate-600">—</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-3.5 text-right font-mono text-xs text-slate-400"><?php echo formatear_segundos($rk['respuesta_seg']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>
