<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Admin;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\DepotType;
use CpCreation\VitiCore\Depot\Model\Category;
use CpCreation\VitiCore\Depot\Model\Depot;
use CpCreation\VitiCore\Depot\Model\Translation\CategoryTranslation;
use CpCreation\VitiCore\Depot\Repository\CategoryRepository;
use CpCreation\VitiCore\Depot\Repository\DepotRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[IsGranted(new Expression("is_granted('ROLE_ADMIN') or is_granted('ROLE_DEPOT')"))]
#[Route('/depots')]
class DepotController extends AbstractController
{
    public function __construct(
        private readonly DepotRepository $depotRepository,
        private readonly CategoryRepository $categoryRepository,
    ) {}

    #[Route('', name: 'admin_depot')]
    public function index(Request $request): Response
    {
        $allDepots = $this->depotRepository->findAllOrderByCountryOrderByCategoryOrderPositionAdmin();
        $filterOptions = $this->buildFilterOptions($allDepots);
        $filters = $this->buildFilters($request, $filterOptions);
        $depots = $this->depotRepository->findAdminFiltered(
            $filters['search'],
            $filters['category_id'],
            $filters['country'],
            $filters['status'],
        );

        return $this->render('@CpCreationVitiCore/admin/depot/index.html.twig', [
            'items' => $depots,
            'filters' => $filters,
            'filter_options' => $filterOptions,
            'move_permissions' => $this->buildMovePermissions($allDepots),
        ]);
    }

    #[Route('/new', name: 'admin_depot_new')]
    public function new(Request $request): Response
    {
        $form = $this->createForm(DepotType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var Depot $data */
            $data = $form->getData();
            $this->depotRepository->save($data);
            $this->addFlash('alert-success', 'Le dépôt ' . $data->getName() . ' a été ajouté avec succès');

            return $this->redirectToRoute('admin_depot', $this->buildFilterQuery($request));
        }

        return $this->render('@CpCreationVitiCore/admin/depot/new.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    #[Route('/{id}/edit', name: 'admin_depot_edit')]
    public function edit(Depot $depot, Request $request): Response
    {
        $form = $this->createForm(DepotType::class, $depot);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var Depot $data */
            $data = $form->getData();
            $this->depotRepository->save($data);
            $this->addFlash('alert-success', 'Le dépôt ' . $depot->getName() . ' a été modifié avec succès');

            return $this->redirectToRoute('admin_depot', $this->buildFilterQuery($request));
        }

        return $this->render('@CpCreationVitiCore/admin/depot/edit.html.twig', [
            'item' => $depot,
            'form' => $form->createView(),
        ]);
    }

    #[Route('/{id}/delete', name: 'admin_depot_delete')]
    public function delete(Depot $depot, Request $request): RedirectResponse
    {
        $this->depotRepository->delete($depot);
        $this->addFlash('alert-success', 'Le dépôt ' . $depot->getName() . ' a été supprimé avec succès.');

        return $this->redirectToRoute('admin_depot', $this->buildFilterQuery($request));
    }

    #[Route('/{id}/disable', name: 'admin_depot_disable')]
    public function disable(Depot $depot, Request $request): RedirectResponse
    {
        $depot->setDisabled(true);
        $this->depotRepository->save($depot);
        $this->addFlash('alert-success', 'Le dépôt ' . $depot->getName() . ' a été dépublié.');

        return $this->redirectToRoute('admin_depot', $this->buildFilterQuery($request));
    }

    #[Route('/{id}/enable', name: 'admin_depot_enable')]
    public function enable(Depot $depot, Request $request): RedirectResponse
    {
        $depot->setDisabled(false);
        $this->depotRepository->save($depot);
        $this->addFlash('alert-success', 'Le dépôt ' . $depot->getName() . ' a été publié.');

        return $this->redirectToRoute('admin_depot', $this->buildFilterQuery($request));
    }

    #[Route('/{id}/moveUp', name: 'admin_depot_move_up')]
    public function moveUp(Depot $depot, Request $request): RedirectResponse
    {
        if ($this->depotRepository->moveUpInCategory($depot)) {
            $this->addFlash('alert-success', 'Le dépôt ' . $depot->getName() . ' a été remonté.');
        }

        return $this->redirectToRoute('admin_depot', $this->buildFilterQuery($request));
    }

    #[Route('/{id}/moveDown', name: 'admin_depot_move_down')]
    public function moveDown(Depot $depot, Request $request): RedirectResponse
    {
        if ($this->depotRepository->moveDownInCategory($depot)) {
            $this->addFlash('alert-success', 'Le dépôt ' . $depot->getName() . ' a été descendu.');
        }

        return $this->redirectToRoute('admin_depot', $this->buildFilterQuery($request));
    }

    /**
     * @param array<int, Depot> $depots
     *
     * @return array{
     *     categories: array<string, string>,
     *     countries: array<string, string>
     * }
     */
    private function buildFilterOptions(array $depots): array
    {
        $categories = [];

        foreach ($this->categoryRepository->findByPositionOrderAdmin() as $category) {
            if (!$category instanceof Category) {
                continue;
            }

            $translation = $category->translate();

            if ($translation instanceof CategoryTranslation) {
                $categories[$category->getId()->toString()] = $translation->getName();
            }
        }

        $countries = [];

        foreach ($depots as $depot) {
            $country = $depot->getCountry();

            if (null !== $country && '' !== $country) {
                $countries[$country] = $country;
            }
        }

        ksort($countries, SORT_NATURAL | SORT_FLAG_CASE);

        return [
            'categories' => $categories,
            'countries' => $countries,
        ];
    }

    /**
     * @param array{
     *     categories: array<string, string>,
     *     countries: array<string, string>
     * } $filterOptions
     *
     * @return array{
     *     search: ?string,
     *     search_input: string,
     *     category_id: ?string,
     *     country: ?string,
     *     status: string,
     *     query_parameters: array<string, string>
     * }
     */
    private function buildFilters(Request $request, array $filterOptions): array
    {
        $search = self::trimToNull($request->query->get('search'));
        $categoryId = self::trimToNull($request->query->get('category'));
        $country = self::trimToNull($request->query->get('country'));
        $status = self::trimToNull($request->query->get('status')) ?? 'all';

        if (
            null !== $categoryId
            && '__none__' !== $categoryId
            && !array_key_exists($categoryId, $filterOptions['categories'])
        ) {
            $categoryId = null;
        }

        if (null !== $country) {
            $country = mb_strtoupper($country);

            if (!array_key_exists($country, $filterOptions['countries'])) {
                $country = null;
            }
        }

        if (!\in_array($status, ['all', 'published', 'unpublished'], true)) {
            $status = 'all';
        }

        $queryParameters = array_filter([
            'search' => $search,
            'category' => $categoryId,
            'country' => $country,
            'status' => 'all' !== $status ? $status : null,
        ], static fn(?string $value): bool => null !== $value);

        return [
            'search' => $search,
            'search_input' => $search ?? '',
            'category_id' => $categoryId,
            'country' => $country,
            'status' => $status,
            'query_parameters' => $queryParameters,
        ];
    }

    /**
     * @param array<int, Depot> $depots
     *
     * @return array<string, array{up: bool, down: bool}>
     */
    private function buildMovePermissions(array $depots): array
    {
        $groups = [];

        foreach ($depots as $depot) {
            $categoryId = $depot->getCategory()?->getId()->toString() ?? '__none__';
            $groups[$categoryId][] = $depot;
        }

        $permissions = [];

        foreach ($groups as $group) {
            $lastIndex = count($group) - 1;

            foreach ($group as $index => $depot) {
                $permissions[$depot->getId()->toString()] = [
                    'up' => $index > 0,
                    'down' => $index < $lastIndex,
                ];
            }
        }

        return $permissions;
    }

    /**
     * @return array<string, string>
     */
    private function buildFilterQuery(Request $request): array
    {
        $status = self::trimToNull($request->query->get('status'));

        if (!\in_array($status, ['published', 'unpublished'], true)) {
            $status = null;
        }

        return array_filter([
            'search' => self::trimToNull($request->query->get('search')),
            'category' => self::trimToNull($request->query->get('category')),
            'country' => self::trimToNull($request->query->get('country')),
            'status' => $status,
        ], static fn(?string $value): bool => null !== $value);
    }

    private static function trimToNull(mixed $value): ?string
    {
        if (!\is_string($value)) {
            return null;
        }

        $value = trim($value);

        return '' === $value ? null : $value;
    }
}
