<?php

namespace App\Security\Voter;

use App\Entity\User;
use App\Security\Voter\Tools\VoterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

class GroupVoter extends VoterInterface
{
    protected function supports(string $attribute, $subject): bool
    {

        return in_array($attribute, ['administrate', 'motd', 'fire', 'rank', 'employee', 'sanction'])
            && $subject instanceof \App\Entity\Group;
    }

    protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
    {
        //first, check if user is valid and has permissions
        /**
         * @var User $User
         */
        $User = $token->getUser();
        if (!$this->checkUser($User)) {
            return false;
        }

        //then set prefix
        $this->setPermissionsPrefix('group');

        if ($User->getMainGroup() != $subject && !$User->getAdminMode()) {
            return false;
        }

        if (!$this->hasPermission('administrate')) {
            return false;
        } //base permission

        switch ($attribute) {
            case 'administrate':
                return true;
                break;
            case 'motd':
            case 'fire':
            case 'employee':
            case 'rank':
            case 'sanction':
                return $this->hasPermission($attribute);
                break;
            default:
                return false;
                break;
        }

        return false;
    }
}
