<?php

declare(strict_types=1);

class Gate
{
    private const ADMIN_ABILITIES = [
        'manage_videos', 'manage_categories', 'manage_tags', 'manage_performers',
        'manage_users', 'manage_comments', 'manage_pages', 'manage_settings',
        'manage_plugins', 'manage_themes',
    ];

    private const MODERATOR_ABILITIES = [
        'manage_videos', 'manage_comments', 'manage_tags',
    ];

    public static function can(string $ability, mixed $resource = null): bool
    {
        $user = Auth::user();
        if ($user === null) {
            return false;
        }

        if ($user['role'] === 'admin') {
            return true;
        }

        if ($user['role'] === 'moderator') {
            return in_array($ability, self::MODERATOR_ABILITIES, true);
        }

         
         
         
        $ownerAbilities = ['edit_own_comment', 'delete_own_comment', 'edit_own_profile'];
        if (in_array($ability, $ownerAbilities, true)
            && is_array($resource) && isset($resource['user_id'])) {
            return (int) $resource['user_id'] === (int) $user['id'];
        }

        return false;
    }

    public static function authorize(string $ability, mixed $resource = null): void
    {
        if (!self::can($ability, $resource)) {
            http_response_code(403);
            if (class_exists('ThemeRenderer', false) && App::isInstalled()) {
                try {
                    ThemeRenderer::render('403', ['pageTitle' => '403 Forbidden']);
                } catch (\Throwable) {
                     
                    try {
                        ThemeRenderer::render('404', ['pageTitle' => '403 Forbidden']);
                    } catch (\Throwable) {
                        echo '<h1>403 Forbidden</h1>';
                    }
                }
            } else {
                echo '<h1>403 Forbidden</h1>';
            }
            exit;
        }
    }
}
