<?php

declare(strict_types=1);

class Auth
{
    public static function check(): bool
    {
        return !empty($_SESSION['usuario_id']);
    }

    public static function user(): ?array
    {
        return $_SESSION['usuario'] ?? null;
    }

    public static function login(array $usuario): void
    {
        $_SESSION['usuario_id'] = $usuario['id'];
        $_SESSION['usuario'] = $usuario;
    }

    public static function logout(): void
    {
        unset($_SESSION['usuario_id'], $_SESSION['usuario']);
    }

    public static function requireLogin(): void
    {
        if (!self::check()) {
            header('Location: ' . base_url('/login'));
            exit;
        }
    }

    public static function isAdmin(): bool
    {
        return (string) (self::user()['perfil'] ?? '') === 'ADMIN';
    }

    public static function canViewOccurrences(): bool
    {
        $user = self::user();
        if (!$user) {
            return false;
        }

        if (self::isAdmin()) {
            return true;
        }

        return (int) ($user['pode_visualizar_ocorrencias'] ?? 0) === 1;
    }

    public static function canEditOccurrences(): bool
    {
        $user = self::user();
        if (!$user) {
            return false;
        }

        if (self::isAdmin()) {
            return true;
        }

        return self::canViewOccurrences() && (int) ($user['pode_editar_ocorrencias'] ?? 0) === 1;
    }

    public static function canViewAllOccurrences(): bool
    {
        $user = self::user();
        if (!$user) {
            return false;
        }

        if (self::isAdmin()) {
            return true;
        }

        return self::canViewOccurrences() && (int) ($user['visualiza_todas_ocorrencias'] ?? 0) === 1;
    }

    public static function occurrenceScope(): array
    {
        $user = self::user();
        if (!$user || !self::canViewOccurrences()) {
            return ['categoria_ids' => [-1]];
        }

        if (self::canViewAllOccurrences()) {
            return [];
        }

        $servicos = $user['servicos_ids'] ?? [];
        if (!is_array($servicos)) {
            $servicos = [];
        }

        $servicos = array_values(array_unique(array_filter(array_map('intval', $servicos), static function ($id) {
            return $id > 0;
        })));

        return ['categoria_ids' => !empty($servicos) ? $servicos : [-1]];
    }

    public static function requireOccurrenceView(): void
    {
        self::requireLogin();
        if (!self::canViewOccurrences()) {
            Session::flash('erro', 'Seu usuário não possui permissão para visualizar ocorrências.');
            header('Location: ' . base_url('/admin/usuarios'));
            exit;
        }
    }

    public static function requireOccurrenceEdit(): void
    {
        self::requireOccurrenceView();
        if (!self::canEditOccurrences()) {
            Session::flash('erro', 'Seu usuário possui acesso somente para consulta das ocorrências.');
            header('Location: ' . base_url('/admin/ocorrencias'));
            exit;
        }
    }

    public static function requireAdmin(): void
    {
        self::requireLogin();
        if (!self::isAdmin()) {
            Session::flash('erro', 'Acesso restrito ao administrador.');
            header('Location: ' . base_url('/admin'));
            exit;
        }
    }
}
