<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Controller;

use Chill\MainBundle\Repository\Workflow\EntityWorkflowStepSignatureACLAwareRepository;
use Chill\MainBundle\Workflow\EntityWorkflowManager;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class PersonSignatureController extends AbstractController
{
    public function __construct(
        private readonly EntityWorkflowStepSignatureACLAwareRepository $signatureRepository,
        private readonly EntityWorkflowManager $entityWorkflowManager,
    ) {}

    #[Route(path: '/{_locale}/signatures/by-person/{id}', name: 'chill_person_signature_list')]
    public function listSignatures(Person $person): Response
    {
        $this->denyAccessUnlessGranted(PersonVoter::SEE, $person);

        $signatures = $this->signatureRepository->findByPersonAndPendingState($person);
        $signatureData = [];

        foreach ($signatures as $signature) {
            $entityWorkflow = $signature->getStep()->getEntityWorkflow();
            $handler = $this->entityWorkflowManager->getHandler($entityWorkflow);

            $workflow = [
                'handler_template' => $handler->getTemplate($entityWorkflow),
                'handler_template_data' => $handler->getTemplateData($entityWorkflow),
                'entity_workflow' => $entityWorkflow,
            ];

            $storedObject = $this->entityWorkflowManager->getAssociatedStoredObject($entityWorkflow);
            $signatureData[] = [
                'signature' => $signature,
                'document' => $storedObject,
                'workflow' => $workflow,
            ];
        }

        return $this->render('@ChillPerson/Person/signature_list.html.twig', [
            'signatures' => $signatureData,
            'person' => $person,
        ]);
    }
}
