<?php

namespace App\Security\Voter;

use App\Entity\Campaign\Report;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;

class ClientReportVoter extends Voter
{
    private $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    protected function supports($attribute, $subject)
    {
        return in_array($attribute, ['access'])
            && $subject instanceof Report;
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        $user = $token->getUser();
        // if the user is anonymous, do not grant access
        if (!$user instanceof UserInterface) {
            return false;
        }

        if (!$this->security->isGranted(['ROLE_CLIENT_ADMIN', 'ROLE_CLIENT_CONTENT', 'ROLE_CLIENT_REPORT'])) {
            return true;
        }

        if ($this->security->isGranted(['ROLE_CLIENT_ADMIN', 'ROLE_CLIENT_REPORT']) && $user->getClient()->getId() === $subject->getCampaign()->getClient()->getId()) {
            return true;
        }

        return false;
    }
}
