<?php

namespace App\Security\Voter;

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

class DirectoryVoter extends VoterInterface
{
    protected function supports(string $attribute, $subject): bool
    {
        return in_array($attribute, ['create', 'edit', 'delete', 'edit_medical', 'merge'])
            && $subject instanceof \App\Entity\Directory;
    }

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


        switch ($attribute) {
            case 'create':
            case 'edit':
            case 'delete':
            case 'merge':
                $this->setPermissionsPrefix('directory');
                return $this->hasPermission($attribute);
                break;
            case 'edit_medical':
                if (!$this->hasPermission('general_medical_view')) {
                    return false;
                }
                $this->setPermissionsPrefix('directory');
                return $this->hasPermission($attribute);
                break;
        }

        //finally, check if permission is in permission list of user
        return $this->hasPermission($attribute);
    }
}
