<?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\ReportBundle\Controller;

use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Privacy\PrivacyEvent;
use Chill\ReportBundle\Entity\Report;
use Chill\ReportBundle\Form\ReportType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Class ReportController.
 */
class ReportController extends AbstractController
{
    /**
     * ReportController constructor.
     */
    public function __construct(
        private readonly EventDispatcherInterface $eventDispatcher,
        private readonly AuthorizationHelper $authorizationHelper,
        private readonly PaginatorFactory $paginator,
        private readonly TranslatorInterface $translator,
        private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry,
    ) {}

    /**
     * Create a new report for a given person and of a given type.
     *
     * @param int     $person_id   the id of the person
     * @param int     $cf_group_id the id of the report type
     * @param Request $request     The request containing the form data (from the newAction)
     *
     * @return Response the web page
     */
    public function createAction($person_id, $cf_group_id, Request $request)
    {
        $em = $this->managerRegistry->getManager();

        $entity = new Report();
        $cFGroup = $em->getRepository(\Chill\CustomFieldsBundle\Entity\CustomFieldsGroup::class)
            ->find($cf_group_id);

        $person = $em->getRepository(Person::class)
            ->find($person_id);

        if (null === $person || null === $cFGroup) {
            throw $this->createNotFoundException();
        }

        $this->denyAccessUnlessGranted('CHILL_PERSON_SEE', $person);

        $form = $this->createCreateForm($entity, $person, $cFGroup);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entity->setCFGroup($cFGroup);
            $entity->setPerson($person);

            $this->denyAccessUnlessGranted('CHILL_REPORT_CREATE', $entity);

            $em->persist($entity);
            $em->flush();

            $this->get('session')
                ->getFlashBag()
                ->add(
                    'success',
                    $this->translator
                        ->trans('Success : report created!')
                );

            return $this->redirectToRoute('report_view', ['person_id' => $person_id, 'report_id' => $entity->getId()]);
        }

        $this->get('session')
            ->getFlashBag()->add(
                'error',
                $this->translator
                    ->trans('The form is not valid. The report has not been created !')
            );

        return $this->render('@ChillReport/Report/new.html.twig', [
            'entity' => $entity,
            'form' => $form->createView(),
            'person' => $person,
        ]);
    }

    /**
     * Display a form to edit an existing Report entity.
     *
     * @param int|string $person_id the id of the person
     * @param int|string $report_id the id of the report
     *
     * @return Response the web page
     */
    public function editAction(int|string $person_id, int|string $report_id)
    {
        $em = $this->managerRegistry->getManager();

        /** @var Report $report */
        $report = $em->getRepository('ChillReportBundle:Report')->find($report_id);

        if (!$report) {
            throw $this->createNotFoundException($this->translator->trans('Unable to find this report.'));
        }

        if ((int) $person_id !== (int) $report->getPerson()->getId()) {
            throw new \RuntimeException($this->translator->trans('This is not the report of the person.'), 1);
        }

        $this->denyAccessUnlessGranted('CHILL_REPORT_UPDATE', $report);

        $person = $report->getPerson();

        $editForm = $this->createEditForm($report);

        $event = new PrivacyEvent($person, [
            'element_class' => Report::class,
            'element_id' => $report->getId(),
            'action' => 'edit',
        ]);
        $this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);

        return $this->render('@ChillReport/Report/edit.html.twig', [
            'edit_form' => $editForm->createView(),
            'person' => $person,
        ]);
    }

    /**
     * Return a csv file with all the reports of a given type.
     *
     * @param int     $cf_group_id The id of the report type to export
     * @param Request $request     The request
     *
     * @return A csv file with all the reports of the selected type
     */
    public function exportAction($cf_group_id, Request $request)
    {
        $em = $this->managerRegistry->getManager();

        $cFGroup = $em->getRepository(\Chill\CustomFieldsBundle\Entity\CustomFieldsGroup::class)->find($cf_group_id);
        $reports = $em->getRepository('ChillReportBundle:Report')->findByCFGroup($cFGroup);

        $response = $this->render('ChillReportBundle:Report:export.csv.twig', [
            'reports' => $reports,
            'cf_group' => $cFGroup,
        ]);

        $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
        $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');

        return $response;
    }

    /**
     * List all the report entities for a given person.
     *
     * @param int     $person_id the id of the person
     * @param Request $request   The request
     *
     * @return Response the web page
     */
    public function listAction($person_id, Request $request)
    {
        $em = $this->managerRegistry->getManager();

        $person = $em->getRepository(Person::class)->find($person_id);

        $this->denyAccessUnlessGranted('CHILL_PERSON_SEE', $person);

        $reachableScopes = $this->authorizationHelper
            ->getReachableScopes(
                $this->getUser(),
                'CHILL_REPORT_SEE',
                $person->getCenter()
            );

        $total = $em
            ->createQuery('SELECT COUNT(r.id) FROM ChillReportBundle:Report r '
                .'WHERE r.person = :person AND r.scope IN (:scopes) ')
            ->setParameter('person', $person)
            ->setParameter('scopes', $reachableScopes)
            ->getSingleScalarResult();

        // get the PaginatorFactory
        $paginator = $this->paginator->create($total);

        $reports = $em->createQuery('SELECT r
                FROM ChillReportBundle:Report r
                WHERE r.person = :person AND r.scope IN (:scopes)
                ORDER BY r.date DESC')
            ->setParameter('person', $person)
            ->setParameter('scopes', $reachableScopes)
            ->setFirstResult($paginator->getCurrentPage()->getFirstItemNumber())
            ->setMaxResults($paginator->getItemsPerPage())
            ->getResult();

        $event = new PrivacyEvent($person, [
            'element_class' => Report::class,
            'action' => 'list',
        ]);
        $this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);

        return $this->render('@ChillReport/Report/list.html.twig', [
            'reports' => $reports,
            'person' => $person,
            'paginator' => $paginator,
        ]);
    }

    /**
     * Display a form for creating a new report for a given person and of a given type.
     *
     * @param int     $person_id   the id of the person
     * @param int     $cf_group_id the id of the report type
     * @param Request $request     The request
     *
     * @return Response the web page
     */
    public function newAction($person_id, $cf_group_id, Request $request)
    {
        $em = $this->managerRegistry->getManager();

        $person = $em->getRepository(Person::class)->find($person_id);
        $cFGroup = $em
            ->getRepository(\Chill\CustomFieldsBundle\Entity\CustomFieldsGroup::class)
            ->find($cf_group_id);

        if (null === $person) {
            throw $this->createNotFoundException('Person not found');
        }

        $this->denyAccessUnlessGranted('CHILL_PERSON_SEE', $person);
        // check access on report creation for a dummy report
        $this->denyAccessUnlessGranted(
            'CHILL_REPORT_CREATE',
            (new Report())->setPerson($person),
            'access denied for report creation'
        );

        if (null === $cFGroup) {
            throw $this->createNotFoundException('custom fields group not found');
        }

        $entity = new Report();
        $entity->setUser($this->get('security.token_storage')->getToken()->getUser());
        $entity->setDate(new \DateTime('now'));

        $entity->setCFGroup($cFGroup);

        $form = $this->createCreateForm($entity, $person, $cFGroup);

        return $this->render('@ChillReport/Report/new.html.twig', [
            'entity' => $entity,
            'form' => $form->createView(),
            'person' => $person,
        ]);
    }

    /**
     * Display a form for selecting which type of report to add for a given person.
     *
     * @param int     $person_id the id of the person
     * @param Request $request   The request
     *
     * @return Response the web page
     */
    public function selectReportTypeAction($person_id, Request $request)
    {
        $em = $this->managerRegistry->getManager();

        $person = $em->getRepository(Person::class)
            ->find($person_id);

        if (null === $person) {
            throw $this->createNotFoundException('Person not found!');
        }

        $this->denyAccessUnlessGranted('CHILL_PERSON_SEE', $person, 'access denied for person view');
        // check access on report creation for a dummy report
        $this->denyAccessUnlessGranted(
            'CHILL_REPORT_CREATE',
            (new Report())->setPerson($person),
            'access denied for report creation'
        );

        $cFGroupId = $request->query->get('cFGroup');

        if ($request->query->has('cFGroup')) {
            return $this->redirectToRoute('report_new', ['person_id' => $person_id, 'cf_group_id' => $cFGroupId]);
        }

        $cFGroups = $em->getRepository(\Chill\CustomFieldsBundle\Entity\CustomFieldsGroup::class)
            ->findByEntity(Report::class);

        if (1 === \count($cFGroups)) {
            return $this->redirectToRoute('report_new', ['person_id' => $person_id, 'cf_group_id' => $cFGroups[0]->getId()]);
        }

        $cFGroupsChoice = [];

        foreach ($cFGroups as $cFGroup) {
            $cFGroupsChoice[$cFGroup->getId()] = $cFGroup->getName($request->getLocale());
        }

        $form = $this->get('form.factory')
            ->createNamedBuilder(null, FormType::class, null, [
                'method' => 'GET',
                'csrf_protection' => false,
            ])
            ->add('cFGroup', ChoiceType::class, [
                'choices' => array_combine(array_values($cFGroupsChoice), array_keys($cFGroupsChoice)),
            ])
            ->getForm();

        $person = $em->getRepository(Person::class)->find($person_id);

        return $this->render('@ChillReport/Report/select_report_type.html.twig', [
            'form' => $form->createView(),
            'person' => $person,
        ]);
    }

    /**
     * Display a form for selecting which type of report to export
     * (a csv file with all the report of this type).
     *
     * @param Request $request The request
     *
     * @return Response the web page
     */
    public function selectReportTypeForExportAction(Request $request)
    {
        $cFGroupId = $request->query->get('cFGroup');

        if ($request->query->has('cFGroup')) {
            return $this->redirectToRoute('report_export_list', ['cf_group_id' => $cFGroupId]);
        }

        $em = $this->managerRegistry->getManager();

        $cFGroups = $em->getRepository(\Chill\CustomFieldsBundle\Entity\CustomFieldsGroup::class)
            ->findByEntity(Report::class);

        if (1 === \count($cFGroups)) {
            return $this->redirectToRoute('report_export_list', ['cf_group_id' => $cFGroups[0]->getId()]);
        }

        $cFGroupsChoice = [];

        foreach ($cFGroups as $cFGroup) {
            $cFGroupsChoice[$cFGroup->getId()] = $cFGroup->getName($request->getLocale());
        }

        $form = $this->get('form.factory')
            ->createNamedBuilder(null, FormType::class, null, [
                'method' => 'GET',
                'csrf_protection' => false,
            ])
            ->add('cFGroup', ChoiceType::class, [
                'choices' => array_combine(array_values($cFGroupsChoice), array_keys($cFGroupsChoice)),
            ])
            ->getForm();

        return $this->render('@ChillReport/Report/select_report_type_for_export.html.twig', [
            'form' => $form->createView(),
            'layout_name' => '@ChillMain/Export/layout.html.twig',
        ]);
    }

    /**
     * Web page for editing an existing report.
     *
     * @param int $person_id the id of the person
     * @param int $report_id the id of the report
     *
     * @return Response the web page
     */
    public function updateAction($person_id, $report_id, Request $request)
    {
        $em = $this->managerRegistry->getManager();

        $report = $em->getRepository('ChillReportBundle:Report')->find($report_id);

        if (!$report) {
            throw $this->createNotFoundException($this->translator->trans('Unable to find this report.'));
        }

        $this->denyAccessUnlessGranted('CHILL_REPORT_UPDATE', $report);

        $editForm = $this->createEditForm($report);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em->flush();

            $this->get('session')
                ->getFlashBag()
                ->add(
                    'success',
                    $this->translator
                        ->trans('Success : report updated!')
                );

            $person = $report->getPerson();

            $event = new PrivacyEvent($person, [
                'element_class' => Report::class,
                'element_id' => $report->getId(),
                'action' => 'update',
            ]);
            $this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);

            return $this->redirectToRoute('report_view', ['person_id' => $report->getPerson()->getId(), 'report_id' => $report_id]);
        }

        $this->get('session')
            ->getFlashBag()
            ->add(
                'error',
                $this->translator
                    ->trans('The form is not valid. The report has not been updated !')
            );

        return $this->render('@ChillReport/Report/edit.html.twig', [
            'edit_form' => $editForm->createView(),
            'person' => $report->getPerson(),
        ]);
    }

    /**
     * Find and display a report.
     *
     * @param int $report_id the id of the report
     * @param int $person_id the id of the person
     *
     * @return Response the web page
     */
    public function viewAction($report_id, $person_id)
    {
        $em = $this->managerRegistry->getManager();

        $person = $em->getRepository(Person::class)->find($person_id);

        $entity = $em->getRepository('ChillReportBundle:Report')->find($report_id);

        if (!$entity || !$person) {
            throw $this->createNotFoundException($this->translator->trans('Unable to find this report.'));
        }

        $this->denyAccessUnlessGranted('CHILL_REPORT_SEE', $entity);

        $event = new PrivacyEvent($person, [
            'element_class' => Report::class,
            'element_id' => $entity->getId(),
            'action' => 'view',
        ]);
        $this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);

        return $this->render('@ChillReport/Report/view.html.twig', [
            'entity' => $entity,
            'person' => $person,
        ]);
    }

    /**
     * Creates a form to create a Report entity.
     *
     * @param Report $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Report $entity, Person $person, mixed $cFGroup)
    {
        return $this->createForm(ReportType::class, $entity, [
            'action' => $this->generateUrl(
                'report_create',
                ['person_id' => $person->getId(),
                    'cf_group_id' => $cFGroup->getId(), ]
            ),
            'method' => 'POST',
            'cFGroup' => $cFGroup,
            'role' => 'CHILL_REPORT_CREATE',
            'center' => $person->getCenter(),
        ]);
    }

    /**
     * Creates a form to edit a Report entity.
     *
     * @param Report $entity the report to edit
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createEditForm(Report $entity)
    {
        return $this->createForm(ReportType::class, $entity, [
            'action' => $this->generateUrl(
                'report_update',
                ['person_id' => $entity->getPerson()->getId(),
                    'report_id' => $entity->getId(), ]
            ),
            'method' => 'PUT',
            'cFGroup' => $entity->getCFGroup(),
            'role' => 'CHILL_REPORT_UPDATE',
            'center' => $entity->getPerson()->getCenter(),
        ]);
    }
}
