<?php 
 
declare(strict_types=1); 
 
namespace App\Controller\Home; 
 
use JsonException; 
use App\Controller\Front\SecurityTokenTrait; 
use App\Controller\PageController; 
use App\Entity\Block; 
use App\Entity\Content; 
use App\Entity\Newsletter; 
use App\Entity\Page; 
use App\Entity\PageBlock; 
use App\Form\ApplicationType; 
use App\Form\NewsLetterType; 
use App\Model\ApplicationDTO; 
use App\Repository\ContentRepository; 
use App\Repository\MenuRepository; 
use App\Service\LangService; 
use App\Service\Mail; 
use Doctrine\Persistence\ManagerRegistry; 
use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\Routing\Annotation\Route; 
use Symfony\Contracts\Translation\TranslatorInterface; 
 
class IndexController extends PageController 
{ 
    use SecurityTokenTrait; 
    private array $classe = [ 
        // 'contact' => \App\Form\ContactType::class, 
    ]; 
 
    /** 
     * page -> entity form. 
     * 
     * @var array 
     */ 
    public $page_form = [ 
        // 'contact' => ['contact'], 
    ]; 
 
    private LangService $langService; 
 
    private ContentRepository $contentRepository; 
 
    private TranslatorInterface $translator; 
 
    public function __construct(LangService $langService, ContentRepository $contentRepository, ManagerRegistry $doctrine, MenuRepository $menuRepository, TranslatorInterface $translator) 
    { 
        parent::__construct($doctrine, $menuRepository); 
        $this->langService = $langService; 
        $this->contentRepository = $contentRepository; 
        $this->translator = $translator; 
    } 
 
    /** 
     * @return RedirectResponse|Response 
     * 
     * @Route("/{slug}", name="front_index_page", defaults={"slug": "accueil"}, options={"expose"=true}) 
     * @throws JsonException 
     */ 
    public function page($slug, Request $request, Mail $mail): Response 
    { 
        $datas = []; 
 
        $this->_initDatas($request, $slug); 
 
        $page = $this->datas['page']; 
 
        /** @var Page|null $page */ 
        $locale = $request->getLocale(); 
 
        if ($page && $page->getSlugs()[$locale] === $slug) { 
            if ($page->getHasFormApplication()) { 
                $applicationDTO = new ApplicationDTO(); 
                $form = $this->createForm(ApplicationType::class, $applicationDTO)->handleRequest($request); 
                $datas['formApplication'] = $form->createView(); 
 
                if ($form->isSubmitted() && $form->isValid()) { 
                    $mail->sendApplicationMail($applicationDTO, $slug); 
 
                    $message = 'Merci pour ta candidature et l’intérêt que tu portes à CarFit. Nos équipes ont sorti les loupes et se posent sur ton profil. On revient vers toi très vite.'; 
                    if ('de' === $locale) { 
                        $message = 'Vielen Dank für deine Bewerbung und dein Interesse an CarFit. Unser Team hat die Lupen ausgepackt und prüft dein Profil. Wir melden uns zeitnah bei dir zurück.'; 
                    } 
 
                    $this->addFlash('success', $message); 
 
                    return $this->redirectToRoute('front_index_page', ['slug' => $slug]); 
                } 
            } 
 
            $array = []; 
 
            $datas['blocks'] = $this->_getDataPage($locale, $page->getId()); 
 
            if (empty($datas['blocks'])) { 
                return $this->render('bundles/TwigBundle/Exception/error404.html.twig'); 
            } 
 
            foreach ($datas['blocks'] as $key => $dt) { 
                if (isset($dt->datas) && array_key_exists('meta_title', $dt->datas)) { 
                    // $datas['metas'] = $dt->datas; 
                } else { 
                    $sub = []; 
                    if (true == $dt->getBlock()->getSubBlock()) { 
                        foreach ($dt->getBlockChildrens() as $children) { 
                            $templateChildren = $children->getBlock()->getPath(); 
                            $children->json['template'] = $templateChildren; 
                            $sub[] = $children->json; 
                        } 
 
                        $dt->datas['sub_blocks'] = $sub; 
                    } 
 
                    $template = $dt->getBlock()->getPath(); 
 
                    $module = null; 
                    if ($dt->getBlock()->getModule()) { 
                        if ($dt->getBlock()->getModule()->getIsActivated()) { 
                            $module = $dt->getBlock()->getModule(); 
                        } else { 
                            $template = false; 
                        } 
                    } 
 
                    if (isset($dt->datas['lang_block']) && $dt->datas['lang_block'] === $locale) { 
                        $array['blocks'][] = [ 
                            'data' => $dt->datas, 
                            'template' => $template, 
                            'module' => $module, 
                        ]; 
 
                        if ($dt->getBlock()->getFormType()) { 
                            $formType = $dt->getBlock()->getFormType(); 
                            $class = explode('Type', $formType); 
                            $class = $class[0]; 
                            $model = 'App\\Entity\\'.$class; 
                            $model = new $model(); 
                            $form = 'App\\Form\\'.$formType; 
 
                            $form = $this->createForm( 
                                ucfirst($form), 
                                $model, 
                                [ 
                                    'action' => $this->generateUrl('ajax_form'), 
                                ] 
                            ); 
 
                            $datas['form'] = $form->createView(); 
                        } 
                    } 
                } 
            } 
 
            unset($datas['blocks']); 
 
            $datas = array_merge($datas, $array); 
        } else { 
            // If !$page redirect to welcome_page 
            $pages = $this->getDoctrine()->getRepository(Page::class)->findAll(); 
 
            if (!empty($pages)) { 
                throw $this->createNotFoundException('Page Not exist'); 
            } 
 
            return $this->render('home/welcome_page.html.twig', [ 
                'header' => 'header_default', 
                'footer' => 'footer_default', 
            ]); 
        } 
 
        if (array_key_exists($slug, $this->page_form)) { 
            $classe = $this->page_form[$slug][0]; 
 
            $model = 'App\\Entity\\'.ucfirst($classe); 
            $model = new $model(); 
 
            $form = $this->createForm( 
                $this->classe[$slug], 
                $model, 
                [ 
                    'action' => $this->generateUrl('ajax_form'), 
                    'slug' => $slug ?? null, 
                ] 
            ); 
 
            $datas['form'] = $form->createView(); 
        } 
 
        // newsletter 
        if ($page) { 
            $newsLetter = new NewsLetter(); 
            $newsletter_form = $this->createForm( 
                NewsletterType::class, 
                $newsLetter, 
                [ 
                    'action' => $this->generateUrl('ajax_form'), 
                ] 
            ); 
 
            $datas['newsletter_form'] = $newsletter_form->createView(); 
            $datas['has_newsletter'] = $page->getHasNewsletter(); 
        } 
 
        return $this->render('home/page/_generic-page.html.twig', $this->getDatas($datas)); 
    } 
 
    /** 
     * @return array 
     */ 
    private function _getDataPage(string $locale, int $pageId) 
    { 
        $lang = $this->langService->getCodeLanguage($locale); 
        $contents = $this->contentRepository->getLangExist($lang, $pageId); 
 
        $arrayPageBlocks = []; 
        /** @var Content $content */ 
        foreach ($contents as $content) { 
            $json = $content->getJson(); 
            if ($content->getPageBlock()) { 
                $content->getPageBlock()->setJsonData($json); 
                $arrayPageBlocks[$content->getPageBlock()->getItemOrder()] = $content->getPageBlock(); 
            } else { 
                $content->getBlockChildren()->setJsonData($json); 
                $arrayPageBlocks[$content->getBlockChildren()->getPageBlock()->getItemOrder()] = $content->getBlockChildren()->getPageBlock(); 
            } 
        } 
 
        ksort($arrayPageBlocks); 
 
        return $this->_getData($arrayPageBlocks); 
    } 
 
    protected function _getDataSite(int $locale) 
    { 
        $page_blocks = $this->getDoctrine()->getRepository(PageBlock::class)->getByPageNameBy('site', $locale); 
 
        return $this->_getData($page_blocks); 
    } 
 
    protected function _getDayliMessage() 
    { 
        return $this->getDoctrine()->getRepository(Block::class)->findByType(6); 
    } 
 
    /** 
     * @Route("/send/newsletter", name="index_home_send_newsletter") 
     */ 
    public function sendNewsletter(Request $request, Mail $mail): Response 
    { 
        dd($request->request->all()); 
    } 
}