<?php
class SessionManager {
    public static function startSession() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }

    public static function destroySession() {
        session_destroy();
    }

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

    public static function getCurrentUser() {
        if (self::isLoggedIn()) {
            return array(
                'id' => $_SESSION['user_id'],
                'username' => $_SESSION['username'],
                'email' => $_SESSION['email'] ?? '',
                'first_name' => $_SESSION['first_name'],
                'last_name' => $_SESSION['last_name'],
                'role' => $_SESSION['role']
            );
        }
        return null;
    }

    public static function requireAuth() {
        if (!self::isLoggedIn()) {
            http_response_code(401);
            echo json_encode(array('message' => 'Unauthorized'));
            exit();
        }
    }

    public static function requireRole($required_role) {
        $user = self::getCurrentUser();
        if (!$user || $user['role'] !== $required_role) {
            http_response_code(403);
            echo json_encode(array('message' => 'Insufficient permissions'));
            exit();
        }
    }

    public static function requireAdmin() {
        self::requireRole('admin');
    }
}
?>
