<?php
/**
 * DashboardController - COMPLETO (CORREGIDO)
 * Todos los endpoints del dashboard
 * FIX: RoleMiddleware::require() es palabra reservada PHP → reemplazado por verificación inline
 */

class DashboardController {
    
    /**
     * Helper interno para verificar roles permitidos
     */
    private static function checkRole(array $payload, array $roles): void {
        if (!in_array($payload['rol'] ?? '', $roles)) {
            Response::error('No tienes permisos para acceder a este recurso', 403);
            exit;
        }
    }

    /**
     * GET /dashboard/stats - Estadísticas completas con tendencias
     */
    public static function stats(): void {
        $payload = AuthMiddleware::verificar();
        self::checkRole($payload, ['admin', 'supervisor', 'tecnico']);
        
        $db = getDB();
        
        // Tickets abiertos
        $ticketsAbiertos = $db->query("
            SELECT COUNT(*) as total 
            FROM tickets 
            WHERE estado IN ('abierto', 'en_progreso', 'pendiente')
        ")->fetch()['total'];
        
        // Tickets críticos
        $ticketsCriticos = $db->query("
            SELECT COUNT(*) as total 
            FROM tickets 
            WHERE prioridad = 'critica' 
            AND estado IN ('abierto', 'en_progreso', 'pendiente')
        ")->fetch()['total'];
        
        // Tickets reabiertos
        $ticketsReabiertos = $db->query("
            SELECT COUNT(*) as total 
            FROM tickets 
            WHERE reaberturas > 0 
            AND estado IN ('abierto', 'en_progreso', 'pendiente')
        ")->fetch()['total'];
        
        // Vencidos SLA
        $vencidosSla = $db->query("
            SELECT COUNT(*) as total 
            FROM tickets 
            WHERE fecha_vencimiento < NOW() 
            AND estado NOT IN ('resuelto', 'cerrado')
        ")->fetch()['total'];
        
        // Sin asignar
        $sinAsignar = $db->query("
            SELECT COUNT(*) as total 
            FROM tickets 
            WHERE tecnico_asignado_id IS NULL 
            AND estado IN ('abierto', 'en_progreso')
        ")->fetch()['total'];
        
        // Equipos activos
        $equiposOnline = $db->query("
            SELECT COUNT(*) as total 
            FROM activos 
            WHERE estado = 'activo'
        ")->fetch()['total'];
        
        // Promedio resolución
        $avgResolucion = $db->query("
            SELECT AVG(TIMESTAMPDIFF(HOUR, created_at, resuelto_at)) as promedio
            FROM tickets
            WHERE estado = 'resuelto'
            AND resuelto_at IS NOT NULL
            AND resuelto_at >= NOW() - INTERVAL 30 DAY
        ")->fetch();
        $promedioResolucion = $avgResolucion['promedio'] ? round($avgResolucion['promedio'], 1) : null;
        
        // Satisfacción
        $satisfaccion = $db->query("
            SELECT AVG(calificacion) as promedio
            FROM tickets
            WHERE calificacion IS NOT NULL
            AND calificacion > 0
            AND created_at >= NOW() - INTERVAL 30 DAY
        ")->fetch();
        $satisfaccionPromedio = $satisfaccion['promedio'] ? round($satisfaccion['promedio'], 1) : null;
        
        // Tendencias (comparar última semana vs semana anterior)
        $hace7dias = $db->query("
            SELECT COUNT(*) as total 
            FROM tickets 
            WHERE estado IN ('abierto', 'en_progreso', 'pendiente')
            AND created_at >= NOW() - INTERVAL 14 DAY
            AND created_at < NOW() - INTERVAL 7 DAY
        ")->fetch()['total'];
        
        $tendenciaTickets = $hace7dias > 0 ? round((($ticketsAbiertos - $hace7dias) / $hace7dias) * 100) : 0;
        
        $criticosAntes = $db->query("
            SELECT COUNT(*) as total 
            FROM tickets 
            WHERE prioridad = 'critica'
            AND created_at >= NOW() - INTERVAL 14 DAY
            AND created_at < NOW() - INTERVAL 7 DAY
        ")->fetch()['total'];
        
        $tendenciaCriticos = $criticosAntes > 0 ? round((($ticketsCriticos - $criticosAntes) / $criticosAntes) * 100) : 0;
        
        $reabiertosAntes = 0;
        try {
            $reabiertosAntes = $db->query("
                SELECT COUNT(*) as total 
                FROM tickets 
                WHERE reaberturas > 0
                AND reabierto_at >= NOW() - INTERVAL 14 DAY
                AND reabierto_at < NOW() - INTERVAL 7 DAY
            ")->fetch()['total'];
        } catch (\Exception $e) {
            // reabierto_at might not exist
        }
        
        $tendenciaReabiertos = $ticketsReabiertos - $reabiertosAntes;
        
        Response::success([
            'tickets_abiertos' => (int)$ticketsAbiertos,
            'tickets_criticos' => (int)$ticketsCriticos,
            'tickets_reabiertos' => (int)$ticketsReabiertos,
            'vencidos_sla' => (int)$vencidosSla,
            'sin_asignar' => (int)$sinAsignar,
            'equipos_online' => (int)$equiposOnline,
            'promedio_resolucion' => $promedioResolucion,
            'satisfaccion_promedio' => $satisfaccionPromedio,
            'tendencia_tickets' => (int)$tendenciaTickets,
            'tendencia_criticos' => (int)$tendenciaCriticos,
            'tendencia_reabiertos' => (int)$tendenciaReabiertos,
        ]);
    }
    
    /**
     * GET /dashboard/actividad-reciente
     */
    public static function actividadReciente(): void {
        $payload = AuthMiddleware::verificar();
        self::checkRole($payload, ['admin', 'supervisor', 'tecnico']);
        
        $db = getDB();
        
        $actividad = $db->query("
            SELECT 
                la.id,
                la.accion,
                la.created_at,
                la.entidad_id as ticket_id,
                u.nombre_completo as usuario_nombre,
                t.numero_ticket
            FROM log_actividad la
            LEFT JOIN usuarios u ON la.usuario_id = u.id
            LEFT JOIN tickets t ON la.entidad_id = t.id
            WHERE la.entidad_tipo = 'ticket'
            AND la.created_at >= NOW() - INTERVAL 2 HOUR
            ORDER BY la.created_at DESC
            LIMIT 20
        ")->fetchAll();
        
        Response::success($actividad);
    }
    
    /**
     * GET /dashboard/tickets-tendencia
     */
    public static function ticketsTendencia(): void {
        $payload = AuthMiddleware::verificar();
        self::checkRole($payload, ['admin', 'supervisor', 'tecnico']);
        
        $db = getDB();
        
        $tendencia = $db->query("
            SELECT 
                DATE(created_at) as fecha,
                COUNT(*) as total
            FROM tickets
            WHERE created_at >= NOW() - INTERVAL 30 DAY
            GROUP BY DATE(created_at)
            ORDER BY fecha ASC
        ")->fetchAll();
        
        Response::success($tendencia);
    }
    
    /**
     * GET /dashboard/tickets-por-estado
     */
    public static function ticketsPorEstado(): void {
        $payload = AuthMiddleware::verificar();
        self::checkRole($payload, ['admin', 'supervisor', 'tecnico']);
        
        $db = getDB();
        
        $estados = $db->query("
            SELECT 
                estado,
                COUNT(*) as total
            FROM tickets
            GROUP BY estado
            ORDER BY total DESC
        ")->fetchAll();
        
        Response::success($estados);
    }
    
    /**
     * GET /dashboard/tickets-por-categoria
     */
    public static function ticketsPorCategoria(): void {
        $payload = AuthMiddleware::verificar();
        self::checkRole($payload, ['admin', 'supervisor', 'tecnico']);
        
        $db = getDB();
        
        $categorias = $db->query("
            SELECT 
                c.nombre as categoria,
                COUNT(t.id) as total
            FROM tickets t
            LEFT JOIN categorias c ON t.categoria_id = c.id
            WHERE t.created_at >= NOW() - INTERVAL 30 DAY
            GROUP BY c.id, c.nombre
            ORDER BY total DESC
            LIMIT 10
        ")->fetchAll();
        
        Response::success($categorias);
    }
    
    /**
     * GET /dashboard/activos-por-tipo
     */
    public static function activosPorTipo(): void {
        $payload = AuthMiddleware::verificar();
        self::checkRole($payload, ['admin', 'supervisor', 'tecnico']);
        
        $db = getDB();
        
        $tipos = $db->query("
            SELECT 
                tipo,
                COUNT(*) as total
            FROM activos
            WHERE estado = 'activo'
            GROUP BY tipo
            ORDER BY total DESC
        ")->fetchAll();
        
        Response::success($tipos);
    }
    
    /**
     * GET /dashboard/rendimiento-tecnicos
     */
    public static function rendimientoTecnicos(): void {
        $payload = AuthMiddleware::verificar();
        self::checkRole($payload, ['admin', 'supervisor']);
        
        $db = getDB();
        
        $tecnicos = $db->query("
            SELECT 
                u.nombre_completo as tecnico,
                COUNT(t.id) as total_tickets,
                SUM(CASE WHEN t.estado = 'resuelto' THEN 1 ELSE 0 END) as resueltos,
                AVG(CASE WHEN t.resuelto_at IS NOT NULL 
                    THEN TIMESTAMPDIFF(HOUR, t.created_at, t.resuelto_at) 
                    ELSE NULL END) as promedio_horas
            FROM usuarios u
            LEFT JOIN tickets t ON u.id = t.tecnico_asignado_id
            WHERE u.rol IN ('tecnico', 'admin')
            AND (t.created_at >= NOW() - INTERVAL 30 DAY OR t.id IS NULL)
            GROUP BY u.id, u.nombre_completo
            ORDER BY total_tickets DESC
        ")->fetchAll();
        
        Response::success($tecnicos);
    }
}