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

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

// 2. Obtener Estadísticas Generales (Solo para Admin)
if ($_SESSION['usuario_rol'] == ROL_ADMIN) {
    // Total Abiertos
    $abiertos = $pdo->query("SELECT COUNT(*) FROM tickets WHERE id_estado != 4")->fetchColumn();
    // Urgentes
    $urgentes = $pdo->query("SELECT COUNT(*) FROM tickets WHERE id_prioridad = 3 AND id_estado != 4")->fetchColumn();
    // Cerrados este mes
    $cerrados_mes = $pdo->query("SELECT COUNT(*) FROM tickets WHERE id_estado = 4 AND MONTH(fecha_actualizacion) = MONTH(NOW())")->fetchColumn();
    
    // Tickets Recientes para la tabla
    $stmt = $pdo->query("SELECT t.id, t.titulo, u.nombre as solicitante, e.nombre as estado, e.color_hex 
                         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 5");
    $recientes = $stmt->fetchAll();
} else {
    // Estadísticas para el Docente/Usuario normal
    $mis_tickets = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE id_solicitante = ? AND id_estado != 4");
    $mis_tickets->execute([$_SESSION['usuario_id']]);
    $abiertos = $mis_tickets->fetchColumn();

    $stmt = $pdo->prepare("SELECT t.id, t.titulo, e.nombre as estado, e.color_hex 
                           FROM tickets t 
                           JOIN ticket_estados e ON t.id_estado = e.id 
                           WHERE t.id_solicitante = ? 
                           ORDER BY t.fecha_creacion DESC LIMIT 5");
    $stmt->execute([$_SESSION['usuario_id']]);
    $recientes = $stmt->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">Hola, <?php echo explode(' ', $_SESSION['usuario_nombre'])[0]; ?> 👋</h1>
        <p class="text-slate-500">Bienvenido al Sistema de Gestión TIC de la Unidad Educativa.</p>
    </div>

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

        <?php if ($_SESSION['usuario_rol'] == ROL_ADMIN): ?>
        <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 flex items-center gap-5">
            <div class="w-14 h-14 bg-red-50 text-red-600 rounded-xl flex items-center justify-center text-2xl animate-pulse">
                <i class="fas fa-exclamation-circle"></i>
            </div>
            <div>
                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Atención Urgente</p>
                <h3 class="text-2xl font-black text-slate-800"><?php echo $urgentes; ?></h3>
            </div>
        </div>

        <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 flex items-center gap-5">
            <div class="w-14 h-14 bg-green-50 text-green-600 rounded-xl flex items-center justify-center text-2xl">
                <i class="fas fa-check-double"></i>
            </div>
            <div>
                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Cerrados este mes</p>
                <h3 class="text-2xl font-black text-slate-800"><?php echo $cerrados_mes; ?></h3>
            </div>
        </div>
        <?php else: ?>
        <a href="../tickets/nuevo.php" class="bg-slate-800 p-6 rounded-2xl shadow-lg text-white flex items-center gap-5 hover:bg-slate-900 transition col-span-2">
            <div class="w-14 h-14 bg-white/10 rounded-xl flex items-center justify-center text-2xl">
                <i class="fas fa-plus"></i>
            </div>
            <div>
                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest italic">¿Necesitas ayuda técnica?</p>
                <h3 class="text-xl font-bold">Crear nuevo reporte</h3>
            </div>
        </a>
        <?php endif; ?>
    </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-6 border-b border-slate-50 flex justify-between items-center">
                    <h4 class="font-bold text-slate-800">Actividad Reciente</h4>
                    <a href="../tickets/index.php" class="text-xs text-blue-600 font-bold hover:underline">Ver todo</a>
                </div>
                <div class="divide-y divide-slate-50">
                    <?php foreach($recientes as $r): ?>
                    <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 $r['id']; ?>'">
                        <div class="flex items-center gap-4">
                            <div class="w-10 h-10 rounded-lg bg-slate-100 flex items-center justify-center text-xs font-bold text-slate-400">
                                #<?php echo $r['id']; ?>
                            </div>
                            <div>
                                <p class="text-sm font-bold text-slate-700"><?php echo htmlspecialchars($r['titulo']); ?></p>
                                <?php if(isset($r['solicitante'])): ?>
                                    <p class="text-[10px] text-slate-400"><?php echo htmlspecialchars($r['solicitante']); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                        <span class="px-3 py-1 rounded-full text-[9px] font-bold text-white shadow-sm" style="background-color: <?php echo $r['color_hex']; ?>">
                            <?php echo $r['estado']; ?>
                        </span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <div class="space-y-6">
            <div class="bg-slate-50 p-6 rounded-2xl border border-slate-200">
                <h4 class="text-xs font-bold text-slate-400 uppercase mb-4 tracking-widest">Enlaces TIC</h4>
                <div class="space-y-3">
                    <a href="../inventario/index.php" class="flex items-center gap-3 p-3 bg-white rounded-xl border border-slate-100 hover:shadow-md transition text-sm text-slate-600 font-medium">
                        <i class="fas fa-desktop text-blue-500"></i> Mi Inventario
                    </a>
                    <a href="perfil.php" class="flex items-center gap-3 p-3 bg-white rounded-xl border border-slate-100 hover:shadow-md transition text-sm text-slate-600 font-medium">
                        <i class="fas fa-user-cog text-purple-500"></i> Mi Perfil
                    </a>
                    <?php if ($_SESSION['usuario_rol'] == ROL_ADMIN): ?>
                    <a href="../reportes/index.php" class="flex items-center gap-3 p-3 bg-white rounded-xl border border-slate-100 hover:shadow-md transition text-sm text-slate-600 font-medium">
                        <i class="fas fa-chart-pie text-green-500"></i> Estadísticas Avanzadas
                    </a>
                    <?php endif; ?>
                </div>
            </div>

            <div class="bg-blue-600 p-6 rounded-2xl text-white shadow-lg shadow-blue-200">
                <h4 class="font-bold mb-2">¿Problemas Críticos?</h4>
                <p class="text-xs text-blue-100 leading-relaxed mb-4">Si el servicio de red institucional falla por completo, comunícate directamente con la extensión de soporte TIC.</p>
                <div class="text-xl font-black"><a href='https://wa.me/34123456789'>
    <svg class="h-8 w-8" fill="currentColor" viewBox="0 0 24 24">
        <path d="M.057 24l1.687-6.163c-1.041-1.804-1.588-3.849-1.587-5.946.003-6.559 5.338-11.894 11.896-11.894 3.181.001 6.167 1.239 8.414 3.486 2.247 2.247 3.482 5.233 3.481 8.414-.003 6.559-5.338 11.894-11.894 11.894-1.99-.001-3.951-.497-5.684-1.437l-6.086 1.603zm16.598-3.963c1.554-1.127 2.723-2.673 3.376-4.469.652-1.795.811-3.723.454-5.556-.357-1.833-1.285-3.486-2.656-4.856-1.371-1.371-3.023-2.299-4.856-2.656-1.833-.357-3.761-.198-5.556.454-1.795.652-3.342 1.821-4.469 3.376-1.127 1.554-1.75 3.421-1.75 5.342 0 4.606 3.748 8.354 8.354 8.354 1.713 0 3.398-.508 4.856-1.47l.156-.104 3.518.927-.927-3.518-.104-.156z"/>
    </svg> 0988281725</a></div>
            </div>
        </div>

    </div>
</div>

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