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

use Chill\MainBundle\Entity\SavedExport;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Export\ExportInterface;
use Chill\MainBundle\Export\ExportManager;
use Chill\MainBundle\Export\GroupedExportInterface;
use Chill\MainBundle\Form\SavedExportType;
use Chill\MainBundle\Repository\SavedExportRepositoryInterface;
use Chill\MainBundle\Security\Authorization\SavedExportVoter;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Contracts\Translation\TranslatorInterface;

class SavedExportController
{
    public function __construct(private readonly \Twig\Environment $templating, private readonly EntityManagerInterface $entityManager, private readonly ExportManager $exportManager, private readonly FormFactoryInterface $formFactory, private readonly SavedExportRepositoryInterface $savedExportRepository, private readonly Security $security, private readonly RequestStack $requestStack, private readonly TranslatorInterface $translator, private readonly UrlGeneratorInterface $urlGenerator) {}

    #[\Symfony\Component\Routing\Attribute\Route(path: '/{_locale}/exports/saved/{id}/delete', name: 'chill_main_export_saved_delete')]
    public function delete(#[MapEntity(id: 'id')] SavedExport $savedExport, Request $request): Response
    {
        if (!$this->security->isGranted(SavedExportVoter::DELETE, $savedExport)) {
            throw new AccessDeniedHttpException();
        }

        $form = $this->formFactory->create();
        $form->add('submit', SubmitType::class, ['label' => 'Delete']);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->entityManager->remove($savedExport);
            $this->entityManager->flush();

            $this->requestStack->getSession()->getFlashBag()->add('success', $this->translator->trans('saved_export.Export is deleted'));

            return new RedirectResponse(
                $this->urlGenerator->generate('chill_main_export_saved_list_my')
            );
        }

        return new Response(
            $this->templating->render(
                '@ChillMain/SavedExport/delete.html.twig',
                [
                    'saved_export' => $savedExport,
                    'delete_form' => $form->createView(),
                ]
            )
        );
    }

    #[\Symfony\Component\Routing\Attribute\Route(path: '/{_locale}/exports/saved/{id}/edit', name: 'chill_main_export_saved_edit')]
    public function edit(#[MapEntity(id: 'id')] SavedExport $savedExport, Request $request): Response
    {
        if (!$this->security->isGranted(SavedExportVoter::EDIT, $savedExport)) {
            throw new AccessDeniedHttpException();
        }

        $form = $this->formFactory->create(SavedExportType::class, $savedExport);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->entityManager->flush();

            $this->requestStack->getSession()->getFlashBag()->add('success', $this->translator->trans('saved_export.Saved export is saved!'));

            return new RedirectResponse(
                $this->urlGenerator->generate('chill_main_export_saved_list_my')
            );
        }

        return new Response(
            $this->templating->render(
                '@ChillMain/SavedExport/edit.html.twig',
                [
                    'form' => $form->createView(),
                ]
            )
        );
    }

    #[\Symfony\Component\Routing\Attribute\Route(path: '/{_locale}/exports/saved/my', name: 'chill_main_export_saved_list_my')]
    public function list(): Response
    {
        $user = $this->security->getUser();

        if (!$this->security->isGranted('ROLE_USER') || !$user instanceof User) {
            throw new AccessDeniedHttpException();
        }

        $exports = $this->savedExportRepository->findByUser($user, ['title' => 'ASC']);

        // group by center
        /** @var array<string, array{saved: SavedExport, export: ExportInterface}> $exportsGrouped */
        $exportsGrouped = [];

        foreach ($exports as $savedExport) {
            $export = $this->exportManager->getExport($savedExport->getExportAlias());

            $exportsGrouped[
                $export instanceof GroupedExportInterface
                    ? $this->translator->trans($export->getGroup()) : '_'
            ][] = ['saved' => $savedExport, 'export' => $export];
        }

        ksort($exportsGrouped);

        return new Response(
            $this->templating->render(
                '@ChillMain/SavedExport/index.html.twig',
                [
                    'grouped_exports' => $exportsGrouped,
                    'total' => \count($exports),
                ]
            )
        );
    }
}
