<?php

namespace App\Model;

use Nette\Database\Explorer;
use Nette\Security\Authorizator;
use Nette\Security\Permission;

class AuthorizatorManager extends BaseManager implements Authorizator
{

    private Permission $acl;

    public function __construct(Explorer $database)
    {
        parent::__construct($database);
        $this->acl = new Permission();

        // Resources
        $this->acl->addResource('article');
        // create - Vytvoreni clanku
        // edit-self - Uprava vlastniho clanku
        // edit-all - Uprava jakéhokoliv clanku
        // approve - Schvaleni clanku
        // display-all - Zobrazit vsechny clanky vcetne neschvalenych

        $this->acl->addResource('comments');
        // delete - Odstraneni jakehokoliv komentare


        // Roles
        $this->acl->addRole('ucitel');
        $this->acl->addRole('admin', 'ucitel');
        $this->acl->addRole('spravce', 'admin'); // Spravuje adminy

        // Permissions for roles
        $this->acl->allow('ucitel', 'article', array('create', 'edit-self'));

        $this->acl->allow('admin', 'article', array('approve', 'edit-all', 'display-all'));

        $this->acl->allow('admin', 'comments', array('delete'));
    }

    public function isAllowed($role, $resource, $privilege): bool
    {
        if (!in_array($role, $this->acl->getRoles()))
            return false;

        if (!$this->acl->hasResource($resource))
        {
            return false;
        }

        return $this->acl->isAllowed($role, $resource, $privilege);
    }

    public function getAcl(): Permission
    {
        return $this->acl;
    }
}