<?php

namespace App\Core;

class Auth {
    public static function login($user) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_role'] = $user['role'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['user_email'] = $user['email'];
        session_regenerate_id(true);
    }

    public static function logout() {
        session_unset();
        session_destroy();
    }

    public static function check() {
        return isset($_SESSION['user_id']);
    }

    public static function user() {
        if (self::check()) {
            $db = \App\Core\Database::getInstance();
            $stmt = $db->prepare("SELECT * FROM users WHERE id = :id LIMIT 1");
            $stmt->execute(['id' => $_SESSION['user_id']]);
            return $stmt->fetch();
        }
        return null;
    }

    public static function hasPermission($module) {
        $user = self::user();
        if (!$user) return false;
        if ($user['role'] === 'admin') return true;
        
        $permissions = json_decode($user['permissions'] ?? '[]', true);
        return in_array($module, $permissions);
    }
}
