<?php

session_start();

if(!isset($_SESSION['user_id'])){
    header("Location: /login.php");
    exit;
}

include("../config/db.php");
include("../includes/auth.php");
include("../includes/hierarchy.php");

$conn->set_charset("utf8mb4");

requirePermission('can_view_reports');

$user_id      = intval($_SESSION['user_id']);
$is_admin     = isset($_SESSION['can_manage_users']) && $_SESSION['can_manage_users'] == 1;
$visible_str  = implode(',', getVisibleUsers($conn, $user_id));
if(empty($visible_str)) $visible_str = '0';

/*
|--------------------------------------------------------------------------
| FILTROS
|--------------------------------------------------------------------------
*/

$filter_from     = $_GET['date_from']   ?? date('Y-m-01');
$filter_to       = $_GET['date_to']     ?? date('Y-m-d');
$filter_agent    = isset($_GET['agent_id'])   ? intval($_GET['agent_id'])   : 0;
$filter_campaign = isset($_GET['campaign_id']) ? intval($_GET['campaign_id']) : 0;
$export          = isset($_GET['export']);

$from_safe = $conn->real_escape_string($filter_from);
$to_safe   = $conn->real_escape_string($filter_to);

// WHERE base para call_logs
$call_where = "DATE(cl.created_at) BETWEEN '$from_safe' AND '$to_safe'";
if(!$is_admin)     $call_where .= " AND cl.user_id IN ($visible_str)";
if($filter_agent)  $call_where .= " AND cl.user_id = $filter_agent";

// WHERE base para contratos
$con_where = "DATE(c.created_at) BETWEEN '$from_safe' AND '$to_safe'";
if(!$is_admin)      $con_where .= " AND c.assigned_user_id IN ($visible_str)";
if($filter_agent)   $con_where .= " AND c.assigned_user_id = $filter_agent";
if($filter_campaign) $con_where .= " AND c.campaign_id = $filter_campaign";

/*
|--------------------------------------------------------------------------
| KPIs GENERALES
|--------------------------------------------------------------------------
*/

$kpis = $conn->query("
SELECT
    COUNT(*)                                              AS total_llamadas,
    SUM(CASE WHEN disposition='SALE' THEN 1 ELSE 0 END)  AS ventas,
    AVG(NULLIF(duration_sec,0))                           AS tmo,
    SUM(duration_sec)                                     AS tiempo_total,
    COUNT(DISTINCT cl.user_id)                            AS agentes_activos
FROM call_logs cl
WHERE $call_where
")->fetch_assoc();

$total_ll  = intval($kpis['total_llamadas'] ?? 0);
$ventas    = intval($kpis['ventas'] ?? 0);
$tmo       = intval($kpis['tmo'] ?? 0);
$conversion = $total_ll > 0 ? round($ventas / $total_ll * 100, 1) : 0;
$agentes   = intval($kpis['agentes_activos'] ?? 0);
$t_total   = intval($kpis['tiempo_total'] ?? 0);

/*
|--------------------------------------------------------------------------
| POR AGENTE
|--------------------------------------------------------------------------
*/

$by_agent = $conn->query("
SELECT
    u.name,
    COUNT(cl.id)                                              AS llamadas,
    SUM(CASE WHEN cl.disposition='SALE' THEN 1 ELSE 0 END)   AS ventas,
    AVG(NULLIF(cl.duration_sec,0))                            AS tmo,
    SUM(cl.duration_sec)                                      AS tiempo_total,
    ROUND(SUM(CASE WHEN cl.disposition='SALE' THEN 1 ELSE 0 END)/COUNT(cl.id)*100,1) AS conversion
FROM call_logs cl
INNER JOIN users u ON u.id = cl.user_id
WHERE $call_where
GROUP BY cl.user_id, u.name
ORDER BY ventas DESC, llamadas DESC
");

/*
|--------------------------------------------------------------------------
| POR CAMPAÑA
|--------------------------------------------------------------------------
*/

$by_campaign = $conn->query("
SELECT
    COALESCE(cam.campaign_name, 'Sin campaña') AS campaign_name,
    COUNT(cl.id)                                              AS llamadas,
    SUM(CASE WHEN cl.disposition='SALE' THEN 1 ELSE 0 END)   AS ventas,
    ROUND(SUM(CASE WHEN cl.disposition='SALE' THEN 1 ELSE 0 END)/COUNT(cl.id)*100,1) AS conversion
FROM call_logs cl
LEFT JOIN leads l ON l.id = cl.lead_id
LEFT JOIN campaigns cam ON cam.id = l.campaign_id
WHERE $call_where
GROUP BY l.campaign_id, cam.campaign_name
ORDER BY ventas DESC
");

/*
|--------------------------------------------------------------------------
| EVOLUCIÓN DIARIA (últimos 30 días o rango seleccionado)
|--------------------------------------------------------------------------
*/

$daily = $conn->query("
SELECT
    DATE(cl.created_at)                                       AS dia,
    COUNT(*)                                                   AS llamadas,
    SUM(CASE WHEN cl.disposition='SALE' THEN 1 ELSE 0 END)   AS ventas
FROM call_logs cl
WHERE $call_where
GROUP BY DATE(cl.created_at)
ORDER BY dia ASC
");

$daily_data = [];
while($d = $daily->fetch_assoc()) $daily_data[] = $d;

/*
|--------------------------------------------------------------------------
| TIPIFICACIONES
|--------------------------------------------------------------------------
*/

$dispositions = $conn->query("
SELECT
    COALESCE(disposition, 'Sin tipificar') AS disposition,
    COUNT(*) AS total
FROM call_logs cl
WHERE $call_where
GROUP BY disposition
ORDER BY total DESC
LIMIT 10
");

/*
|--------------------------------------------------------------------------
| USUARIOS PARA FILTRO
|--------------------------------------------------------------------------
*/

if($is_admin){
    $agents_list = $conn->query("SELECT id, name FROM users ORDER BY name ASC");
} else {
    $agents_list = $conn->query("SELECT id, name FROM users WHERE id IN ($visible_str) ORDER BY name ASC");
}

$campaigns_list = $conn->query("SELECT id, campaign_name FROM campaigns ORDER BY campaign_name ASC");

/*
|--------------------------------------------------------------------------
| EXPORTAR CSV
|--------------------------------------------------------------------------
*/

if($export){
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="metricas_' . date('Ymd_His') . '.csv"');
    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF)); // BOM UTF-8

    fputcsv($out, ['MÉTRICAS POR AGENTE'], ';');
    fputcsv($out, ['Agente','Llamadas','Ventas','Conversión %','TMO','Tiempo total'], ';');

    // Re-query for export
    $export_q = $conn->query("
    SELECT u.name, COUNT(cl.id) AS llamadas,
        SUM(CASE WHEN cl.disposition='SALE' THEN 1 ELSE 0 END) AS ventas,
        ROUND(SUM(CASE WHEN cl.disposition='SALE' THEN 1 ELSE 0 END)/COUNT(cl.id)*100,1) AS conv,
        AVG(NULLIF(cl.duration_sec,0)) AS tmo,
        SUM(cl.duration_sec) AS tiempo_total
    FROM call_logs cl
    INNER JOIN users u ON u.id = cl.user_id
    WHERE $call_where
    GROUP BY cl.user_id, u.name ORDER BY ventas DESC
    ");
    while($r = $export_q->fetch_assoc()){
        fputcsv($out, [
            $r['name'],
            $r['llamadas'],
            $r['ventas'],
            $r['conv'] . '%',
            gmdate('i:s', intval($r['tmo'])),
            gmdate('H:i:s', intval($r['tiempo_total']))
        ], ';');
    }

    fputcsv($out, [], ';');
    fputcsv($out, ['MÉTRICAS POR CAMPAÑA'], ';');
    fputcsv($out, ['Campaña','Llamadas','Ventas','Conversión %'], ';');

    $camp_q = $conn->query("
    SELECT COALESCE(cam.campaign_name,'Sin campaña') AS campaign_name,
        COUNT(cl.id) AS llamadas,
        SUM(CASE WHEN cl.disposition='SALE' THEN 1 ELSE 0 END) AS ventas,
        ROUND(SUM(CASE WHEN cl.disposition='SALE' THEN 1 ELSE 0 END)/COUNT(cl.id)*100,1) AS conv
    FROM call_logs cl
    LEFT JOIN leads l ON l.id=cl.lead_id
    LEFT JOIN campaigns cam ON cam.id=l.campaign_id
    WHERE $call_where
    GROUP BY l.campaign_id, cam.campaign_name ORDER BY ventas DESC
    ");
    while($r = $camp_q->fetch_assoc()){
        fputcsv($out, [$r['campaign_name'], $r['llamadas'], $r['ventas'], $r['conv'].'%'], ';');
    }

    fputcsv($out, [], ';');
    fputcsv($out, ['EVOLUCIÓN DIARIA'], ';');
    fputcsv($out, ['Fecha','Llamadas','Ventas'], ';');
    foreach($daily_data as $d){
        fputcsv($out, [$d['dia'], $d['llamadas'], $d['ventas']], ';');
    }

    fclose($out);
    exit;
}

?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Métricas</title>
<link rel="stylesheet" href="/assets/css/style.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>

.content-area{ margin-left:260px; padding:40px; }

.page-title{ font-size:42px; font-weight:800; color:#02122c; margin-bottom:10px; }
.page-subtitle{ color:#64748b; margin-bottom:30px; }

.white-card{
    background:#fff;
    border-radius:24px;
    padding:30px;
    margin-bottom:25px;
    box-shadow:0 10px 30px rgba(15,23,42,.06);
}

.kpi-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(160px,1fr));
    gap:18px;
    margin-bottom:30px;
}

.kpi-box{
    background:#f8fafc;
    border-radius:18px;
    padding:22px;
    text-align:center;
}

.kpi-val{ font-size:34px; font-weight:800; color:#02122c; }
.kpi-val.green{ color:#16a34a; }
.kpi-val.purple{ color:#5b4bff; }
.kpi-lbl{ font-size:12px; font-weight:700; color:#64748b; margin-top:6px; text-transform:uppercase; }

.filter-bar{
    display:flex;
    gap:12px;
    flex-wrap:wrap;
    align-items:flex-end;
    margin-bottom:28px;
}

.filter-group{ display:flex; flex-direction:column; gap:6px; }
.filter-label{ font-size:12px; font-weight:700; color:#64748b; text-transform:uppercase; }

.form-control{
    height:46px;
    border:none;
    border-radius:12px;
    background:#f1f5f9;
    padding:0 14px;
    font-size:14px;
    min-width:160px;
}

.btn-filter{
    height:46px;
    padding:0 22px;
    border:none;
    border-radius:12px;
    background:linear-gradient(90deg,#5b4bff,#7b61ff);
    color:#fff;
    font-weight:700;
    cursor:pointer;
    font-size:14px;
}

.btn-export{
    height:46px;
    padding:0 22px;
    border:none;
    border-radius:12px;
    background:linear-gradient(90deg,#16a34a,#22c55e);
    color:#fff;
    font-weight:700;
    cursor:pointer;
    font-size:14px;
    text-decoration:none;
    display:inline-flex;
    align-items:center;
    gap:8px;
}

.section-title{ font-size:18px; font-weight:800; color:#02122c; margin-bottom:20px; }

.crm-table{ width:100%; border-collapse:collapse; }
.crm-table th{
    text-align:left; padding:12px 16px;
    font-size:11px; font-weight:700; color:#64748b;
    text-transform:uppercase; border-bottom:2px solid #f1f5f9;
}
.crm-table td{ padding:13px 16px; font-size:14px; border-bottom:1px solid #f8fafc; }

.rank{ font-size:18px; font-weight:800; color:#94a3b8; }
.rank-1{ color:#f59e0b; }
.rank-2{ color:#94a3b8; }
.rank-3{ color:#cd7c2f; }

.bar-wrap{ background:#f1f5f9; border-radius:6px; height:8px; overflow:hidden; }
.bar-fill{ height:8px; border-radius:6px; background:linear-gradient(90deg,#5b4bff,#7b61ff); }
.bar-fill.green{ background:linear-gradient(90deg,#16a34a,#22c55e); }

.charts-grid{
    display:grid;
    grid-template-columns:2fr 1fr;
    gap:24px;
    margin-bottom:25px;
}

@media(max-width:900px){ .charts-grid{ grid-template-columns:1fr; } }

</style>
</head>
<body>

<?php include("../includes/sidebar.php"); ?>

<div class="content-area">

    <div class="page-title">Métricas</div>
    <div class="page-subtitle">Análisis de rendimiento del equipo y campañas</div>

    <!-- FILTROS -->
    <form method="GET" class="filter-bar">
        <div class="filter-group">
            <span class="filter-label">Desde</span>
            <input type="date" name="date_from" class="form-control" value="<?= $filter_from ?>">
        </div>
        <div class="filter-group">
            <span class="filter-label">Hasta</span>
            <input type="date" name="date_to" class="form-control" value="<?= $filter_to ?>">
        </div>
        <div class="filter-group">
            <span class="filter-label">Agente</span>
            <select name="agent_id" class="form-control">
                <option value="0">Todos los agentes</option>
                <?php while($a = $agents_list->fetch_assoc()): ?>
                <option value="<?= $a['id'] ?>" <?= $filter_agent == $a['id'] ? 'selected':'' ?>>
                    <?= htmlspecialchars($a['name']) ?>
                </option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="filter-group">
            <span class="filter-label">Campaña</span>
            <select name="campaign_id" class="form-control">
                <option value="0">Todas las campañas</option>
                <?php while($c = $campaigns_list->fetch_assoc()): ?>
                <option value="<?= $c['id'] ?>" <?= $filter_campaign == $c['id'] ? 'selected':'' ?>>
                    <?= htmlspecialchars($c['campaign_name']) ?>
                </option>
                <?php endwhile; ?>
            </select>
        </div>
        <button type="submit" class="btn-filter">Filtrar</button>
        <a href="?date_from=<?= urlencode($filter_from) ?>&date_to=<?= urlencode($filter_to) ?>&agent_id=<?= $filter_agent ?>&campaign_id=<?= $filter_campaign ?>&export=1"
            class="btn-export">
            ⬇ Exportar CSV
        </a>
    </form>

    <!-- KPIs -->
    <div class="kpi-grid">
        <div class="kpi-box">
            <div class="kpi-val"><?= number_format($total_ll) ?></div>
            <div class="kpi-lbl">Llamadas totales</div>
        </div>
        <div class="kpi-box">
            <div class="kpi-val green"><?= number_format($ventas) ?></div>
            <div class="kpi-lbl">Ventas</div>
        </div>
        <div class="kpi-box">
            <div class="kpi-val purple"><?= $conversion ?>%</div>
            <div class="kpi-lbl">Conversión</div>
        </div>
        <div class="kpi-box">
            <div class="kpi-val"><?= gmdate('i:s', $tmo) ?></div>
            <div class="kpi-lbl">TMO</div>
        </div>
        <div class="kpi-box">
            <div class="kpi-val"><?= gmdate('H:i', $t_total) ?></div>
            <div class="kpi-lbl">Tiempo total</div>
        </div>
        <div class="kpi-box">
            <div class="kpi-val"><?= $agentes ?></div>
            <div class="kpi-lbl">Agentes activos</div>
        </div>
    </div>

    <!-- GRÁFICAS -->
    <div class="charts-grid">

        <div class="white-card">
            <div class="section-title">Evolución diaria</div>
            <canvas id="chartDaily" height="100"></canvas>
        </div>

        <div class="white-card">
            <div class="section-title">Tipificaciones</div>
            <canvas id="chartDisp" height="100"></canvas>
        </div>

    </div>

    <!-- RANKING AGENTES -->
    <div class="white-card">
        <div class="section-title">🏆 Ranking de agentes</div>
        <?php if($by_agent->num_rows > 0): ?>
        <table class="crm-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Agente</th>
                    <th>Llamadas</th>
                    <th>Ventas</th>
                    <th>Conversión</th>
                    <th>TMO</th>
                    <th>Tiempo total</th>
                    <th>Progreso</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $rank = 1;
            $max_ventas = null;
            $rows_agent = [];
            while($r = $by_agent->fetch_assoc()) $rows_agent[] = $r;
            if(!empty($rows_agent)) $max_ventas = max(array_column($rows_agent, 'ventas'));
            foreach($rows_agent as $r):
                $pct = $max_ventas > 0 ? round($r['ventas'] / $max_ventas * 100) : 0;
                $rank_class = $rank <= 3 ? "rank-$rank" : "";
            ?>
            <tr>
                <td><span class="rank <?= $rank_class ?>"><?= $rank++ ?></span></td>
                <td><strong><?= htmlspecialchars($r['name']) ?></strong></td>
                <td><?= intval($r['llamadas']) ?></td>
                <td style="color:#16a34a;font-weight:800"><?= intval($r['ventas']) ?></td>
                <td><?= $r['conversion'] ?>%</td>
                <td><?= gmdate('i:s', intval($r['tmo'])) ?></td>
                <td><?= gmdate('H:i:s', intval($r['tiempo_total'])) ?></td>
                <td style="width:120px">
                    <div class="bar-wrap">
                        <div class="bar-fill green" style="width:<?= $pct ?>%"></div>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php else: ?>
        <p style="color:#94a3b8;text-align:center;padding:20px">Sin datos en el período seleccionado</p>
        <?php endif; ?>
    </div>

    <!-- POR CAMPAÑA -->
    <div class="white-card">
        <div class="section-title">📋 Métricas por campaña</div>
        <?php if($by_campaign->num_rows > 0): ?>
        <table class="crm-table">
            <thead>
                <tr>
                    <th>Campaña</th>
                    <th>Llamadas</th>
                    <th>Ventas</th>
                    <th>Conversión</th>
                    <th>Progreso</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $rows_camp = [];
            while($r = $by_campaign->fetch_assoc()) $rows_camp[] = $r;
            $max_camp = !empty($rows_camp) ? max(array_column($rows_camp, 'ventas')) : 1;
            foreach($rows_camp as $r):
                $pct = $max_camp > 0 ? round($r['ventas'] / $max_camp * 100) : 0;
            ?>
            <tr>
                <td><strong><?= htmlspecialchars($r['campaign_name']) ?></strong></td>
                <td><?= intval($r['llamadas']) ?></td>
                <td style="color:#16a34a;font-weight:800"><?= intval($r['ventas']) ?></td>
                <td><?= $r['conversion'] ?>%</td>
                <td style="width:150px">
                    <div class="bar-wrap">
                        <div class="bar-fill" style="width:<?= $pct ?>%"></div>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php else: ?>
        <p style="color:#94a3b8;text-align:center;padding:20px">Sin datos en el período seleccionado</p>
        <?php endif; ?>
    </div>

</div>

<script>
// Datos evolución diaria
const dailyLabels = <?= json_encode(array_column($daily_data, 'dia')) ?>;
const dailyLlamadas = <?= json_encode(array_map('intval', array_column($daily_data, 'llamadas'))) ?>;
const dailyVentas = <?= json_encode(array_map('intval', array_column($daily_data, 'ventas'))) ?>;

new Chart(document.getElementById('chartDaily'), {
    type: 'line',
    data: {
        labels: dailyLabels,
        datasets: [
            {
                label: 'Llamadas',
                data: dailyLlamadas,
                borderColor: '#5b4bff',
                backgroundColor: 'rgba(91,75,255,.1)',
                fill: true,
                tension: .4,
                pointRadius: 3,
            },
            {
                label: 'Ventas',
                data: dailyVentas,
                borderColor: '#16a34a',
                backgroundColor: 'rgba(22,163,74,.1)',
                fill: true,
                tension: .4,
                pointRadius: 3,
            }
        ]
    },
    options: {
        responsive: true,
        plugins: { legend: { position: 'top' } },
        scales: { y: { beginAtZero: true } }
    }
});

// Tipificaciones
const dispLabels = <?= json_encode(array_column(iterator_to_array($dispositions ?? new ArrayIterator([])), 'disposition')) ?>;
const dispData   = <?= json_encode(array_map('intval', array_column(iterator_to_array($dispositions ?? new ArrayIterator([])), 'total'))) ?>;

<?php
// Re-query dispositions for JS
$disp2 = $conn->query("
SELECT COALESCE(disposition,'Sin tipificar') AS disposition, COUNT(*) AS total
FROM call_logs cl WHERE $call_where GROUP BY disposition ORDER BY total DESC LIMIT 8
");
$disp_labels = []; $disp_vals = [];
while($d = $disp2->fetch_assoc()){ $disp_labels[] = $d['disposition']; $disp_vals[] = intval($d['total']); }
?>

new Chart(document.getElementById('chartDisp'), {
    type: 'doughnut',
    data: {
        labels: <?= json_encode($disp_labels) ?>,
        datasets: [{
            data: <?= json_encode($disp_vals) ?>,
            backgroundColor: ['#5b4bff','#16a34a','#dc2626','#f59e0b','#06b6d4','#8b5cf6','#ec4899','#64748b'],
        }]
    },
    options: {
        responsive: true,
        plugins: { legend: { position: 'bottom', labels: { font: { size: 11 } } } }
    }
});
</script>

</body>
</html>