<?php
namespace Utils;
session_start();
// Check destroyed time-stamp
if (isset($_SESSION['destroyed'])
    && $_SESSION['destroyed'] < time() - 300) {
    // Should not happen usually. This could be attack or due to unstable network.
    // Remove all authentication status of this users session.
    remove_all_authentication_flag_from_active_sessions($_SESSION['userid']);
    throw(new DestroyedSessionAccessException);
}

$old_sessionid = session_id();

// Set destroyed timestamp
$_SESSION['destroyed'] = time(); // session_regenerate_id() saves old session data

// Simply calling session_regenerate_id() may result in lost session, etc.
// See next example.
session_regenerate_id();

// New session does not need destroyed timestamp
unset($_SESSION['destroyed']);

$new_sessionid = session_id();

/* echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />"; */

class Auth {
    public static function init() {
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start([
            'cookie_secure' => false,
            'cookie_httponly' => true,
            'use_strict_mode' => true
        ]);
            }
        }

    public static function login($user) {
        self::init();
        // Affichage de débogage pour vérifier les données de l'utilisateur
        $_SESSION['user'] = [
            'id' => $user['id'],
            'username' => $user['username'],
            'email' => $user['email'],
            'role' => $user['user_roles']
        ];
        $user = $_SESSION['user'];
        session_regenerate_id(true);
    }

    public static function logout() {
        self::init();
        
        // 1. Effacement des données de session
        $_SESSION = [];
        
        // 2. Expiration du cookie
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(
                session_name(),
                '',
                time() - 42000,
                $params["path"],
                $params["domain"],
                $params["secure"],
                $params["httponly"]
            );
        }
    
        // 3. Destruction complète
        session_destroy();
    
        // 4. Régénération de l'ID pour éviter le fixation
        if (session_status() !== PHP_SESSION_NONE) {
            session_regenerate_id(true);
        }
    } // <-- ACCOLADE FERMANTE AJOUTÉE ICI

    public static function isLoggedIn() {
        self::init();
        return isset($_SESSION['user']);
    }

    public static function getUserRole() {
        self::init();
        return $_SESSION['user']['role'] ?? null;
    }

    public static function checkPermission($allowedRoles) {
        if (!is_array($allowedRoles)) {
            $allowedRoles = [$allowedRoles];
        }
        
        if (!in_array(self::getUserRole(), $allowedRoles)) {
            header('HTTP/1.0 403 Forbidden');
            echo 'Accès interdit';
            header('Location: /login');
            exit;
        }
    }

    public static function hasPermission($allowedRoles) {
        return self::isLoggedIn() && in_array(self::getUserRole(), $allowedRoles);
    }

    public static function generateCsrfToken() {
        self::init();
        $token = bin2hex(random_bytes(32));
        $_SESSION['csrf_token'] = $token;
        return $token;
    }

    public static function validateCsrfToken($token) {
        self::init();
        if (!isset($_SESSION['csrf_token'])) {
            throw new \RuntimeException("Token CSRF non généré");
        }
        return hash_equals($_SESSION['csrf_token'], $token);
    }
}
?>
