<?php
/**
 * NEXUS IT - LogController (FASE 6 - Enhanced Auditing)
 */
class LogController {
    public static function index(): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireAdmin($payload);
        $db = getDB();
        $page = max(1, (int)($_GET['page'] ?? 1));
        $perPage = min(100, max(1, (int)($_GET['per_page'] ?? 30)));
        $offset = ($page - 1) * $perPage;

        $where = ["1=1"]; $params = [];
        if (!empty($_GET['usuario_id'])) { $where[] = "l.usuario_id = ?"; $params[] = (int)$_GET['usuario_id']; }
        if (!empty($_GET['accion'])) { $where[] = "l.accion = ?"; $params[] = $_GET['accion']; }
        if (!empty($_GET['entidad_tipo'])) { $where[] = "l.entidad_tipo = ?"; $params[] = $_GET['entidad_tipo']; }
        if (!empty($_GET['desde'])) { $where[] = "l.created_at >= ?"; $params[] = $_GET['desde']; }
        if (!empty($_GET['hasta'])) { $where[] = "l.created_at <= ?"; $params[] = $_GET['hasta'] . ' 23:59:59'; }
        if (!empty($_GET['buscar'])) { $s = '%'.$_GET['buscar'].'%'; $where[] = "(l.accion LIKE ? OR l.entidad_tipo LIKE ? OR l.ip_address LIKE ?)"; $params = array_merge($params, [$s,$s,$s]); }

        $whereStr = implode(' AND ', $where);
        $countStmt = $db->prepare("SELECT COUNT(*) FROM log_actividad l WHERE $whereStr");
        $countStmt->execute($params);
        $total = (int)$countStmt->fetchColumn();

        $stmt = $db->prepare("SELECT l.*, u.nombre_completo as usuario_nombre FROM log_actividad l LEFT JOIN usuarios u ON l.usuario_id = u.id WHERE $whereStr ORDER BY l.created_at DESC LIMIT $perPage OFFSET $offset");
        $stmt->execute($params);
        Response::paginated($stmt->fetchAll(), $total, $page, $perPage);
    }

    public static function acciones(): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireAdmin($payload);
        $db = getDB();
        $stmt = $db->query("SELECT DISTINCT accion FROM log_actividad ORDER BY accion");
        Response::success($stmt->fetchAll(PDO::FETCH_COLUMN));
    }

    public static function stats(): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireAdmin($payload);
        $db = getDB();
        $hoy = (int)$db->query("SELECT COUNT(*) FROM log_actividad WHERE DATE(created_at) = CURDATE()")->fetchColumn();
        $semana = (int)$db->query("SELECT COUNT(*) FROM log_actividad WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetchColumn();
        $total = (int)$db->query("SELECT COUNT(*) FROM log_actividad")->fetchColumn();
        $topAcciones = $db->query("SELECT accion, COUNT(*) as total FROM log_actividad WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) GROUP BY accion ORDER BY total DESC LIMIT 10")->fetchAll();
        $topUsuarios = $db->query("SELECT u.nombre_completo, COUNT(*) as total FROM log_actividad l JOIN usuarios u ON l.usuario_id = u.id WHERE l.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) GROUP BY l.usuario_id ORDER BY total DESC LIMIT 10")->fetchAll();
        $porHora = $db->query("SELECT HOUR(created_at) as hora, COUNT(*) as total FROM log_actividad WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) GROUP BY HOUR(created_at) ORDER BY hora")->fetchAll();
        Response::success(['hoy' => $hoy, 'semana' => $semana, 'total' => $total, 'top_acciones' => $topAcciones, 'top_usuarios' => $topUsuarios, 'actividad_por_hora' => $porHora]);
    }

    public static function exportar(): void {
        $payload = AuthMiddleware::verificar();
        RoleMiddleware::requireAdmin($payload);
        $db = getDB();
        $where = ["1=1"]; $params = [];
        if (!empty($_GET['desde'])) { $where[] = "l.created_at >= ?"; $params[] = $_GET['desde']; }
        if (!empty($_GET['hasta'])) { $where[] = "l.created_at <= ?"; $params[] = $_GET['hasta'] . ' 23:59:59'; }
        $whereStr = implode(' AND ', $where);
        $stmt = $db->prepare("SELECT l.created_at, u.nombre_completo as usuario, l.accion, l.entidad_tipo, l.entidad_id, l.ip_address FROM log_actividad l LEFT JOIN usuarios u ON l.usuario_id = u.id WHERE $whereStr ORDER BY l.created_at DESC LIMIT 5000");
        $stmt->execute($params);
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=audit_log_' . date('Y-m-d') . '.csv');
        $out = fopen('php://output', 'w');
        fputcsv($out, ['Fecha', 'Usuario', 'Acción', 'Entidad', 'ID Entidad', 'IP']);
        foreach ($stmt->fetchAll() as $row) fputcsv($out, array_values($row));
        fclose($out);
        exit;
    }
}
