<?php

namespace Myvetshop\Module\Clinique\Controller;

use Doctrine\ORM\EntityManagerInterface;
use Myvetshop\Module\Clinique\Form\Admin\Product\BlockProductDataProvider;
use Myvetshop\Module\Clinique\Repository\MyvetshopCliniqueRepository;
use PrestaShop\PrestaShop\Core\Form\FormHandlerInterface;
use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use PrestaShopBundle\Security\Annotation\AdminSecurity;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\TranslatorInterface;

class ProductController extends FrameworkBundleAdminController
{
    protected BlockProductDataProvider $blockProductDataProvider;
    protected EntityManagerInterface $entityManager;
    protected FormFactoryInterface $formFactory;
    protected FormHandlerInterface $blockProductFormHandler;
    protected MyvetshopCliniqueRepository $cliniqueRepository;
    protected TranslatorInterface $translator;

    public function __construct(
        BlockProductDataProvider $blockProductDataProvider,
        EntityManagerInterface $entityManager,
        FormFactoryInterface $formFactory,
        FormHandlerInterface $blockProductFormHandler,
        MyvetshopCliniqueRepository $cliniqueRepository,
        TranslatorInterface $translator
    ) {
        $this->blockProductDataProvider = $blockProductDataProvider;
        $this->entityManager = $entityManager;
        $this->blockProductFormHandler = $blockProductFormHandler;
        $this->formFactory = $formFactory;
        $this->cliniqueRepository = $cliniqueRepository;
        $this->translator = $translator;

        parent::__construct();
    }

    /**
     * @AdminSecurity("is_granted(['update'], 'ADMINPRODUCTS')", message="You do not have permission to block products.")
     */
    public function blockAction(Request $request): Response
    {
        $form = $this->blockProductFormHandler->getForm();
        $form->handleRequest($request);

        $message = null;

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var array{product_id: int, code_privileges: string} $data */
            $data = $form->getData();

            $errors = $this->blockProductDataProvider->setData($data);
            if (\count($errors)) {
                foreach ($errors as $error) {
                    $this->addFlash(
                        'error',
                        $this->translator->trans($error['key'], $error['parameters'], $error['domain'])
                    );
                }
            } else {
                $codePrivileges = \array_filter(
                    \array_unique(
                        \array_map(
                            'trim',
                            \explode("\n", $data['code_privileges'] ?? '')
                        )
                    )
                );

                $cliniques = $this->cliniqueRepository->findAllByPrivilegedCode($codePrivileges);

                foreach ($cliniques as $clinique) {
                    $blockedProducts = \array_filter(
                        \array_map(
                            'trim',
                            \explode(',', $clinique->blockedProducts ?? '')
                        )
                    );

                    if (!\in_array($data['product_id'], $blockedProducts)) {
                        $blockedProducts[] = $data['product_id'];
                        $clinique->blockedProducts = \implode(',', $blockedProducts);
                    }
                }

                $this->entityManager->flush();

                $this->addFlash('success', 'Produit bloqué avec succès');
            }

            return $this->redirectToRoute('product_block');
        }

        return $this->render(
            '@Modules/myvetshopclinique/templates/admin/product/block.html.twig',
            [
                'form' => $form->createView(),
                'message' => $message,
            ]
        );
    }
}
