<?php
require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';

// 1. Verificación de seguridad: Solo Admin
if (!isset($_SESSION['usuario_id']) || $_SESSION['usuario_rol'] != ROL_ADMIN) {
    header("Location: ../../index.php");
    exit();
}

/** * 2. OBTENCIÓN DE ESTADÍSTICAS REALES
 */

// A. Tickets Abiertos (Cualquier estado que NO sea Cerrado - ID 4)
$stmt_abiertos = $pdo->query("SELECT COUNT(*) FROM tickets WHERE id_estado != 4");
$total_abiertos = $stmt_abiertos->fetchColumn();

// B. Tickets Urgentes (Prioridad Alta - ID 3 y que no estén cerrados)
$stmt_urgentes = $pdo->query("SELECT COUNT(*) FROM tickets WHERE id_prioridad = 3 AND id_estado != 4");
$total_urgentes = $stmt_urgentes->fetchColumn();

// C. Tickets Cerrados Hoy
$stmt_hoy = $pdo->query("SELECT COUNT(*) FROM tickets WHERE id_estado = 4 AND DATE(fecha_actualizacion) = CURDATE()");
$cerrados_hoy = $stmt_hoy->fetchColumn();

// D. Tickets por Categoría (Para un pequeño resumen visual)
$stmt_cat = $pdo->query("SELECT COUNT(*) as total, id_prioridad FROM tickets WHERE id_estado != 4 GROUP BY id_prioridad");
$por_prioridad = $stmt_cat->fetchAll(PDO::FETCH_KEY_PAIR);

/**
 * 3. LISTADO DE ACTIVIDAD RECIENTE
 */
$stmt_recientes = $pdo->query("SELECT t.id, t.titulo, u.nombre as solicitante, e.nombre as estado, e.color_hex, t.fecha_creacion 
                               FROM tickets t 
                               JOIN usuarios u ON t.id_solicitante = u.id 
                               JOIN ticket_estados e ON t.id_estado = e.id 
                               ORDER BY t.fecha_creacion DESC LIMIT 6");
$tickets_recientes = $stmt_recientes->fetchAll();

include '../layout/header.php';
?>

<div class="max-w-7xl mx-auto px-4 py-8">
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-slate-800">Panel de Administración TIC</h1>
        <p class="text-slate-500 text-sm">Resumen global de soporte - Unidad Educativa Giovanni Calles</p>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        
        <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
            <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Pendientes</p>
            <div class="flex items-center justify-between">
                <h3 class="text-3xl font-black text-slate-800"><?php echo $total_abiertos; ?></h3>
                <div class="w-10 h-10 bg-blue-50 text-blue-600 rounded-lg flex items-center justify-center">
                    <i class="fas fa-clock"></i>
                </div>
            </div>
        </div>

        <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 border-l-4 border-l-red-500">
            <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Urgencias</p>
            <div class="flex items-center justify-between">
                <h3 class="text-3xl font-black text-red-600"><?php echo $total_urgentes; ?></h3>
                <div class="w-10 h-10 bg-red-50 text-red-600 rounded-lg flex items-center justify-center">
                    <i class="fas fa-fire-alt"></i>
                </div>
            </div>
        </div>

        <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
            <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Solucionados Hoy</p>
            <div class="flex items-center justify-between">
                <h3 class="text-3xl font-black text-green-600"><?php echo $cerrados_hoy; ?></h3>
                <div class="w-10 h-10 bg-green-50 text-green-600 rounded-lg flex items-center justify-center">
                    <i class="fas fa-check-circle"></i>
                </div>
            </div>
        </div>

        <div class="bg-slate-800 p-6 rounded-2xl shadow-lg text-white">
            <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1">Acción Rápida</p>
            <a href="../tickets/index.php" class="flex items-center justify-between group">
                <span class="text-sm font-bold group-hover:underline">Ver Reportes</span>
                <i class="fas fa-arrow-right text-blue-400 group-hover:translate-x-1 transition"></i>
            </a>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        
        <div class="lg:col-span-2">
            <div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
                <div class="p-5 border-b border-slate-50 flex justify-between items-center bg-slate-50/50">
                    <h4 class="font-bold text-slate-800 text-sm italic">Últimos Tickets Generados</h4>
                    <span class="text-[10px] bg-blue-100 text-blue-700 px-2 py-0.5 rounded font-bold">TIEMPO REAL</span>
                </div>
                <div class="divide-y divide-slate-100">
                    <?php foreach($tickets_recientes as $tr): ?>
                    <div class="p-4 hover:bg-slate-50 transition flex items-center justify-between cursor-pointer" onclick="window.location='../tickets/detalle.php?id=<?php echo $tr['id']; ?>'">
                        <div class="flex items-center gap-4">
                            <div class="text-xs font-mono text-slate-400">#<?php echo $tr['id']; ?></div>
                            <div>
                                <p class="text-sm font-bold text-slate-700"><?php echo htmlspecialchars($tr['titulo']); ?></p>
                                <p class="text-[10px] text-slate-400"><?php echo $tr['solicitante']; ?> • <?php echo date('H:i', strtotime($tr['fecha_creacion'])); ?></p>
                            </div>
                        </div>
                        <span class="px-3 py-1 rounded-full text-[9px] font-bold text-white" style="background-color: <?php echo $tr['color_hex']; ?>">
                            <?php echo $tr['estado']; ?>
                        </span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <div class="space-y-6">
            <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100">
                <h4 class="text-xs font-bold text-slate-400 uppercase mb-4 tracking-widest">Herramientas Admin</h4>
                <div class="grid grid-cols-1 gap-3">
                    <a href="../usuarios/index.php" class="flex items-center gap-3 p-3 bg-slate-50 rounded-xl hover:bg-blue-50 transition border border-transparent hover:border-blue-100">
                        <i class="fas fa-users text-blue-500"></i>
                        <span class="text-xs font-bold text-slate-600">Gestión de Usuarios</span>
                    </a>
                    <a href="../inventario/index.php" class="flex items-center gap-3 p-3 bg-slate-50 rounded-xl hover:bg-purple-50 transition border border-transparent hover:border-purple-100">
                        <i class="fas fa-boxes text-purple-500"></i>
                        <span class="text-xs font-bold text-slate-600">Inventario General</span>
                    </a>
                    <a href="../tickets/index.php?estado=1" class="flex items-center gap-3 p-3 bg-slate-50 rounded-xl hover:bg-orange-50 transition border border-transparent hover:border-orange-100">
                        <i class="fas fa-exclamation-triangle text-orange-500"></i>
                        <span class="text-xs font-bold text-slate-600">Tickets sin Asignar</span>
                    </a>
                </div>
            </div>

            <div class="bg-gradient-to-br from-slate-800 to-slate-900 p-6 rounded-2xl text-white shadow-xl">
                <div class="flex items-center gap-2 mb-4">
                    <div class="w-2 h-2 bg-green-400 rounded-full animate-ping"></div>
                    <span class="text-[10px] font-bold uppercase tracking-widest">Estado del Servidor</span>
                </div>
                <p class="text-xs text-slate-400 mb-4 italic">Conexión establecida con la base de datos institucional en Coca, Orellana.</p>
                <div class="text-xs text-blue-400 font-mono">tic.comil12.edu.ec</div>
            </div>
        </div>
    </div>
</div>

<?php include '../layout/footer.php'; ?>