<?php

session_start();

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

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

requirePermission('can_manage_users');

$conn->set_charset("utf8mb4");

/*
|--------------------------------------------------------------------------
| CREAR TABLA ACTIVITY LOGS SI NO EXISTE
|--------------------------------------------------------------------------
*/

// Agregar columnas faltantes a activity_logs si no existen
$conn->query("ALTER TABLE activity_logs ADD COLUMN IF NOT EXISTS user_name VARCHAR(200) NULL");
$conn->query("ALTER TABLE activity_logs ADD COLUMN IF NOT EXISTS action VARCHAR(100) NULL");
$conn->query("ALTER TABLE activity_logs ADD COLUMN IF NOT EXISTS module VARCHAR(100) NULL");
$conn->query("ALTER TABLE activity_logs ADD COLUMN IF NOT EXISTS ip VARCHAR(50) NULL");

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

$filter_module = $_GET['module']  ?? '';
$filter_user   = $_GET['user_id'] ?? '';
$filter_from   = $_GET['date_from'] ?? '';
$filter_to     = $_GET['date_to']   ?? '';
$filter_search = trim($_GET['search'] ?? '');

$where = [];

if($filter_module) $where[] = "activity_logs.module = '" . $conn->real_escape_string($filter_module) . "'";
if($filter_user)   $where[] = "activity_logs.user_id = " . intval($filter_user);
if($filter_from)   $where[] = "DATE(activity_logs.created_at) >= '" . $conn->real_escape_string($filter_from) . "'";
if($filter_to)     $where[] = "DATE(activity_logs.created_at) <= '" . $conn->real_escape_string($filter_to) . "'";
if($filter_search){
    $s = $conn->real_escape_string($filter_search);
    $where[] = "(activity_logs.description LIKE '%$s%')";
}

$where_sql = count($where) ? 'WHERE ' . implode(' AND ', $where) : '';

/*
|--------------------------------------------------------------------------
| LOGS
|--------------------------------------------------------------------------
*/

$logs = $conn->query("
SELECT activity_logs.*, users.name AS real_name
FROM activity_logs
LEFT JOIN users ON users.id = activity_logs.user_id
$where_sql
ORDER BY activity_logs.created_at DESC
LIMIT 500
");

/*
|--------------------------------------------------------------------------
| STATS DEL DÍA
|--------------------------------------------------------------------------
*/

$today = date('Y-m-d');

$stats = [
    'logins'    => $conn->query("SELECT COUNT(*) AS c FROM activity_logs WHERE action_type='LOGIN' AND DATE(created_at)='$today'")->fetch_assoc()['c'] ?? 0,
    'calls'     => $conn->query("SELECT COUNT(*) AS c FROM call_logs WHERE DATE(created_at)='$today'")->fetch_assoc()['c'] ?? 0,
    'contracts' => $conn->query("SELECT COUNT(*) AS c FROM activity_logs WHERE (module='contratos' OR action_type LIKE '%contract%') AND DATE(created_at)='$today'")->fetch_assoc()['c'] ?? 0,
    'imports'   => $conn->query("SELECT COUNT(*) AS c FROM lead_imports WHERE DATE(created_at)='$today'")->fetch_assoc()['c'] ?? 0,
];

// Usuarios para filtro
$users_list = $conn->query("SELECT id, name FROM users ORDER BY name ASC");

// Módulos únicos
$modules_list = $conn->query("SELECT DISTINCT module FROM activity_logs WHERE module != '' ORDER BY module ASC");

/*
|--------------------------------------------------------------------------
| LLAMADAS HOY POR AGENTE
|--------------------------------------------------------------------------
*/

$calls_by_agent = $conn->query("
SELECT
    u.name,
    COUNT(cl.id)                                        AS total,
    SUM(CASE WHEN cl.disposition='SALE' THEN 1 ELSE 0 END) AS ventas,
    AVG(cl.duration_sec)                                AS tmo,
    SUM(cl.duration_sec)                                AS tiempo_total
FROM call_logs cl
INNER JOIN users u ON u.id = cl.user_id
WHERE DATE(cl.created_at) = '$today'
GROUP BY cl.user_id, u.name
ORDER BY total DESC
");

?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Logs y Actividad</title>
<link rel="stylesheet" href="/assets/css/style.css">
<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:#ffffff;
    border-radius:24px;
    padding:30px;
    margin-bottom:25px;
    box-shadow:0 10px 30px rgba(15,23,42,.06);
}

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

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

.stat-val{
    font-size:36px;
    font-weight:800;
    color:#02122c;
}

.stat-lbl{
    font-size:13px;
    font-weight:600;
    color:#64748b;
    margin-top:6px;
}

.filter-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(180px,1fr));
    gap:14px;
    margin-bottom:20px;
}

.form-control{
    height:48px;
    border:none;
    border-radius:14px;
    background:#f1f5f9;
    padding:0 16px;
    font-size:14px;
    width:100%;
}

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

.btn-reset{
    height:48px;
    padding:0 20px;
    border:none;
    border-radius:14px;
    background:#e2e8f0;
    color:#02122c;
    font-weight:700;
    cursor:pointer;
    font-size:14px;
    text-decoration:none;
    display:inline-flex;
    align-items:center;
}

.crm-table{
    width:100%;
    border-collapse:collapse;
}

.crm-table th{
    text-align:left;
    padding:14px 16px;
    font-size:12px;
    font-weight:700;
    color:#64748b;
    text-transform:uppercase;
    border-bottom:2px solid #f1f5f9;
}

.crm-table td{
    padding:13px 16px;
    font-size:13px;
    border-bottom:1px solid #f8fafc;
    color:#02122c;
}

.badge{
    display:inline-flex;
    align-items:center;
    height:26px;
    padding:0 12px;
    border-radius:20px;
    font-size:11px;
    font-weight:700;
}

.badge-login     { background:#dbeafe; color:#1d4ed8; }
.badge-contratos { background:#dcfce7; color:#16a34a; }
.badge-llamadas  { background:#ede9fe; color:#5b4bff; }
.badge-importar  { background:#ffedd5; color:#ea580c; }
.badge-pipeline  { background:#fce7f3; color:#be185d; }
.badge-settings  { background:#f1f5f9; color:#64748b; }
.badge-default   { background:#f1f5f9; color:#64748b; }

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

</style>
</head>
<body>

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

<div class="content-area">

    <div class="page-title">Logs y Actividad</div>
    <div class="page-subtitle">Registro de acciones y movimientos del CRM</div>

    <!-- STATS HOY -->
    <div class="stats-grid">
        <div class="stat-box">
            <div class="stat-val"><?= $stats['logins'] ?></div>
            <div class="stat-lbl">Logins hoy</div>
        </div>
        <div class="stat-box">
            <div class="stat-val"><?= $stats['calls'] ?></div>
            <div class="stat-lbl">Llamadas hoy</div>
        </div>
        <div class="stat-box">
            <div class="stat-val"><?= $stats['contracts'] ?></div>
            <div class="stat-lbl">Contratos hoy</div>
        </div>
        <div class="stat-box">
            <div class="stat-val"><?= $stats['imports'] ?></div>
            <div class="stat-lbl">Importaciones hoy</div>
        </div>
    </div>

    <!-- LLAMADAS POR AGENTE HOY -->
    <?php if($calls_by_agent->num_rows > 0): ?>
    <div class="white-card">
        <div class="section-title">📞 Llamadas por agente hoy</div>
        <table class="crm-table">
            <thead>
                <tr>
                    <th>Agente</th>
                    <th>Llamadas</th>
                    <th>Ventas</th>
                    <th>TMO</th>
                    <th>Tiempo total</th>
                </tr>
            </thead>
            <tbody>
            <?php while($row = $calls_by_agent->fetch_assoc()): ?>
            <tr>
                <td><strong><?= htmlspecialchars($row['name']) ?></strong></td>
                <td><?= intval($row['total']) ?></td>
                <td style="color:#16a34a;font-weight:700"><?= intval($row['ventas']) ?></td>
                <td><?= gmdate('i:s', intval($row['tmo'])) ?></td>
                <td><?= gmdate('H:i:s', intval($row['tiempo_total'])) ?></td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>

    <!-- IMPORTACIONES RECIENTES -->
    <div class="white-card">
        <div class="section-title">📋 Importaciones de bases recientes</div>
        <table class="crm-table">
            <thead>
                <tr>
                    <th>Base</th>
                    <th>Campaña</th>
                    <th>Leads importados</th>
                    <th>Duplicados</th>
                    <th>Subido por</th>
                    <th>Fecha</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $imports = $conn->query("
            SELECT li.*, u.name AS uploader, c.campaign_name
            FROM lead_imports li
            LEFT JOIN users u ON u.id = li.uploaded_by
            LEFT JOIN campaigns c ON c.id = li.campaign_id
            ORDER BY li.created_at DESC
            LIMIT 20
            ");
            while($imp = $imports->fetch_assoc()):
            ?>
            <tr>
                <td><strong><?= htmlspecialchars($imp['import_batch']) ?></strong></td>
                <td><?= htmlspecialchars($imp['campaign_name'] ?? '—') ?></td>
                <td><?= intval($imp['total_leads']) ?></td>
                <td><?= intval($imp['duplicates_found']) ?></td>
                <td><?= htmlspecialchars($imp['uploader'] ?? '—') ?></td>
                <td><?= $imp['created_at'] ?></td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>

    <!-- HISTORIAL DE LLAMADAS -->
    <div class="white-card">
        <div class="section-title">📱 Historial de llamadas recientes</div>
        <table class="crm-table">
            <thead>
                <tr>
                    <th>Agente</th>
                    <th>Teléfono</th>
                    <th>Tipo</th>
                    <th>Duración</th>
                    <th>Resultado</th>
                    <th>Fecha</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $calls = $conn->query("
            SELECT cl.*, u.name AS agent_name
            FROM call_logs cl
            LEFT JOIN users u ON u.id = cl.user_id
            ORDER BY cl.created_at DESC
            LIMIT 50
            ");
            while($call = $calls->fetch_assoc()):
                $dur = $call['duration_sec'] > 0 ? gmdate('i:s', $call['duration_sec']) : '—';
            ?>
            <tr>
                <td><?= htmlspecialchars($call['agent_name'] ?? '—') ?></td>
                <td><?= htmlspecialchars($call['phone']) ?></td>
                <td>
                    <span class="badge <?= $call['type'] === 'predictive' ? 'badge-pipeline' : 'badge-llamadas' ?>">
                        <?= $call['type'] ?>
                    </span>
                </td>
                <td><?= $dur ?></td>
                <td><?= htmlspecialchars($call['disposition'] ?? '—') ?></td>
                <td><?= $call['created_at'] ?></td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>

    <!-- LOG DE ACTIVIDAD GENERAL -->
    <div class="white-card">

        <div class="section-title">🗂️ Log de actividad general</div>

        <!-- Filtros -->
        <form method="GET" style="margin-bottom:20px">
        <div class="filter-grid">

            <div>
                <select name="module" class="form-control">
                    <option value="">Todos los módulos</option>
                    <?php
                    $mods = ['login','contratos','leads','pipeline','settings','llamadas','importar'];
                    foreach($mods as $m):
                    ?>
                    <option value="<?= $m ?>" <?= $filter_module === $m ? 'selected' : '' ?>>
                        <?= ucfirst($m) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <select name="user_id" class="form-control">
                    <option value="">Todos los usuarios</option>
                    <?php
                    $users_list = $conn->query("SELECT id, name FROM users ORDER BY name ASC");
                    while($u = $users_list->fetch_assoc()):
                    ?>
                    <option value="<?= $u['id'] ?>" <?= $filter_user == $u['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($u['name']) ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div>
                <input type="date" name="date_from" class="form-control"
                    value="<?= htmlspecialchars($filter_from) ?>" placeholder="Desde">
            </div>

            <div>
                <input type="date" name="date_to" class="form-control"
                    value="<?= htmlspecialchars($filter_to) ?>" placeholder="Hasta">
            </div>

            <div>
                <input type="text" name="search" class="form-control"
                    value="<?= htmlspecialchars($filter_search) ?>" placeholder="Buscar...">
            </div>

            <div style="display:flex;gap:10px">
                <button type="submit" class="btn-filter">Filtrar</button>
                <a href="settings_logs.php" class="btn-reset">Limpiar</a>
            </div>

        </div>
        </form>

        <?php if($logs->num_rows > 0): ?>
        <table class="crm-table">
            <thead>
                <tr>
                    <th>Usuario</th>
                    <th>Módulo</th>
                    <th>Acción</th>
                    <th>Descripción</th>
                    <th>IP</th>
                    <th>Fecha</th>
                </tr>
            </thead>
            <tbody>
            <?php while($log = $logs->fetch_assoc()):
                $badge_class = match($log['module']) {
                    'login'     => 'badge-login',
                    'contratos' => 'badge-contratos',
                    'llamadas'  => 'badge-llamadas',
                    'importar'  => 'badge-importar',
                    'pipeline'  => 'badge-pipeline',
                    'settings'  => 'badge-settings',
                    default     => 'badge-default',
                };
            ?>
            <tr>
                <td><strong><?= htmlspecialchars($log['real_name'] ?? $log['user_name'] ?? '—') ?></strong></td>
                <td>
                    <span class="badge <?= $badge_class ?>">
                        <?= htmlspecialchars($log['module']) ?>
                    </span>
                </td>
                <td><?= htmlspecialchars($log['action']) ?></td>
                <td><?= htmlspecialchars($log['description']) ?></td>
                <td style="color:#94a3b8;font-size:12px"><?= htmlspecialchars($log['ip'] ?? '—') ?></td>
                <td style="color:#64748b"><?= $log['created_at'] ?></td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
        <?php else: ?>
        <p style="color:#94a3b8;text-align:center;padding:30px">
            No hay registros de actividad aún. Los logs se generarán automáticamente cuando los usuarios realicen acciones en el CRM.
        </p>
        <?php endif; ?>

    </div>

</div>

</body>
</html>