<?php
/**
 * Authentication & Authorization Helper
 */

require_once __DIR__ . '/../Models/User.php';

class Auth {
    private static ?array $cachedUser = null;
    private static ?array $cachedRoles = null;

    /**
     * Check if a user is currently logged in and active
     */
    public static function check(): bool {
        return self::id() !== null;
    }

    /**
     * Get current authenticated user ID
     */
    public static function id(): ?int {
        return $_SESSION['user_id'] ?? null;
    }

    /**
     * Get current authenticated user data
     */
    public static function user(): ?array {
        $userId = self::id();
        if (!$userId) {
            return null;
        }

        if (self::$cachedUser === null || (self::$cachedUser['id'] ?? null) !== $userId) {
            $userModel = new User();
            $user = $userModel->findById($userId);
            if (!$user || $user['status'] !== 'active') {
                self::logout();
                return null;
            }
            self::$cachedUser = $user;
        }

        return self::$cachedUser;
    }

    /**
     * Get all roles assigned to current user
     */
    public static function roles(): array {
        $userId = self::id();
        if (!$userId) {
            return [];
        }

        if (self::$cachedRoles === null) {
            $userModel = new User();
            self::$cachedRoles = $userModel->getUserRoles($userId);
        }

        return self::$cachedRoles;
    }

    /**
     * Check if user has specific role name
     */
    public static function hasRole(string $roleName): bool {
        $roles = self::roles();
        return in_array($roleName, $roles, true);
    }

    public static function isCustomer(): bool {
        return self::hasRole('customer');
    }

    public static function isSeller(): bool {
        return self::hasRole('seller');
    }

    public static function isAdmin(): bool {
        return self::hasRole('admin') || self::hasRole('operation_admin') || self::hasRole('finance_admin') || self::hasRole('support_admin');
    }

    /**
     * Clear cached state (e.g. on logout or user profile update)
     */
    public static function clearCache(): void {
        self::$cachedUser = null;
        self::$cachedRoles = null;
    }

    public static function logout(): void {
        self::clearCache();
        Session::destroy();
    }
}
