<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\Controller\Fragment;

use Ferienpass\CmsBundle\View\ApplicationList;
use Ferienpass\CoreBundle\ApplicationSystem\ApplicationSystems;
use Ferienpass\CoreBundle\Controller\AbstractPrivateFragmentController;
use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Payments\PaymentSystem;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Ferienpass\CoreBundle\Repository\EditionTaskRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;

class ApplicationListController extends AbstractPrivateFragmentController
{
    public function __construct(private readonly ApplicationSystems $applicationSystems, private readonly AttendanceRepository $attendances, private readonly EditionTaskRepository $periods, private readonly PaymentSystem $paymentSystem, private readonly TranslatorInterface $translator)
    {
    }

    public function __invoke(Request $request): Response
    {
        $user = $this->getUser();
        if (!$user instanceof User) {
            return new Response('', Response::HTTP_NO_CONTENT);
        }

        /** @var array<int, Attendance> $result */
        $result = $this->attendances->createQueryBuilder('a')
            ->innerJoin('a.participant', 'p')
            ->innerJoin('a.offer', 'o')
            ->leftJoin('o.dates', 'd')
            ->orderBy('d.begin')
            ->where('p.user = :member')
            ->setParameter('member', $user->getId())
            ->getQuery()
            ->getResult()
        ;

        $applicationSystems = [];
        foreach ($result as $attendance) {
            $applicationSystems[$attendance->getId() ?? 0] = $this->applicationSystems->findApplicationSystem($attendance->getOffer());
        }

        $filter = $request->query->get('nur', 'zukuenftige');

        if ($request->query->has('nur') && 'zukuenftige' === $request->query->get('nur')) {
            return $this->redirectToRoute($request->attributes->get('_route'), array_merge($request->attributes->get('_route_params')));
        }

        $applicationList = ApplicationList::fromDatabaseResult($result);

        return $this->render('@Contao/fragment/application_list.html.twig', [
            'attendances' => $applicationList->getFilteredAttendances($filter),
            'applicationSystems' => $applicationSystems,
            'filter' => $filter,
            'items' => $this->getTabNavigation($request, $filter),
            'paymentsEnabled' => $this->paymentSystem->isEnabled(),
            'isPaymentConfigured' => $this->paymentSystem->hasOnlineProvider(),
        ]);
    }

    public function getTabNavigation(Request $request, float|bool|int|string|null $filter): array
    {
        $icons = [
            'zukuenftige' => 'lucide:calendar-clock',
            'vergangene' => 'lucide:history',
            'abgemeldet' => 'lucide:circle-x',
            'unbezahlte' => 'lucide:credit-card',
        ];

        $items = [];
        foreach (['zukuenftige', 'vergangene', 'abgemeldet'] as $tab) {
            $queryParams = $request->query->all();
            $queryParams['nur'] = $tab;

            if ('zukuenftige' === $tab) {
                unset($queryParams['nur']);
            }

            $items[] = [
                'name' => $this->translator->trans('applicationList.tabs.'.$tab, [], 'cms'),
                'url' => $this->generateUrl($request->attributes->get('_route'), array_merge($request->attributes->get('_route_params'), $queryParams)),
                'active' => ('zukuenftige' === $tab && ('zukuenftige' === $filter || !\in_array($filter, ['vergangene', 'abgemeldet', 'unbezahlte'], true))) || ($filter === $tab),
                'icon' => $icons[$tab],
            ];
        }

        if ('unbezahlte' === $filter) {
            $items[] = [
                'name' => $this->translator->trans('applicationList.tabs.unbezahlte', [], 'cms'),
                'url' => $this->generateUrl($request->attributes->get('_route'), array_merge($request->attributes->get('_route_params'), $request->query->all(), ['nur' => 'unbezahlte'])),
                'active' => true,
                'icon' => $icons['unbezahlte'],
            ];
        }

        return $items;
    }
}
