<?php
// Iniciar sesión si no está iniciada
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once 'config.php';
require_once 'database.php';

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function getUserRole() {
    return $_SESSION['user_role'] ?? null;
}

function requireAuth() {
    if (!isLoggedIn()) {
        header('Location: ' . APP_URL . '/auth/login.php');
        exit;
    }
}

function requireRole($role) {
    requireAuth();
    if (getUserRole() !== $role) {
        header('Location: ' . APP_URL . '/index.php');
        exit;
    }
}

function loginUser($email, $password) {
    global $db;
    
    $user = $db->fetchOne("SELECT * FROM usuarios WHERE email = ?", [$email]);

    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_role'] = $user['tipo'];
        $_SESSION['user_name'] = $user['nombre'];
        $_SESSION['user_email'] = $user['email'];
        
        // Redirigir según rol
        switch ($_SESSION['user_role']) {
            case 'admin':
                $redirect = 'admin';
                break;
            case 'direccion':
                $redirect = 'direccion';
                break;
            case 'docente':
                $redirect = 'teacher';
                break;
            case 'estudiante':
                $redirect = 'student';
                break;
            case 'auxiliar':
                $redirect = 'auxiliar';
                break;
            default:
                header("Location: " . APP_URL . "/auth/login.php");
                exit;
        }
        
        header("Location: " . APP_URL . "/modules/$redirect/dashboard.php");
        return true;
    }
    
    return false;
}

function logoutUser() {
    // Limpiar todas las variables de sesión
    $_SESSION = [];
    
    // Destruir la sesión
    if (session_status() === PHP_SESSION_ACTIVE) {
        session_destroy();
    }
}
?>