<?php

namespace App\Controller\BackendAdmin;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

use Doctrine\ORM\EntityManagerInterface;

use App\Entity\Article;

use App\Repository\ArticleRepository;

use App\Form\BackendAdmin\ArticleType;


#[Route('/backend/admin/article')]
class ArticleController extends AbstractController
{

    /**
     * @var ArticleRepository $articleRepository
     */
    private $articleRepository;

    /**
     * @var EntityManagerInterface $em
     */
    private $em;

    /**
     * @param AnnonceRepository $articleRepository
     * @param EntityManagerInterface $em
     * @return $this
     */
    public function __construct(
        ArticleRepository $articleRepository,
        EntityManagerInterface $em
    ){
        $this->articleRepository = $articleRepository;
        $this->em = $em;
    }
    
    
    #[Route('/index', name: 'backend_admin_article_index')]
    public function index(): Response
    {
        return $this->render('backend_admin/article/index.html.twig', ['articles'=> $this->articleRepository->findBy([], ["id"=>'DESC'])]);
    }

    #[Route('/add', name: 'backend_admin_article_add')]
    public function add(Request $request): Response
    {
        $article = new Article();
		
		$form = $this->createForm(ArticleType::class, $article);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
			$article = $form->getData();

            if( ($article->getLimitType() == 0) && ($article->getLimitDate() == null) ){
                $this->addFlash('danger', ['title'=>'Erreur', 'message'=>"<b>Limitation Par Date vide</b>"]);
                return $this->redirectToRoute('backend_admin_article_add', ['form'=>$form]);
            }

            if( ($article->getLimitType() == 1) && ($article->getLimitQuantite() <= 0) ){
                $this->addFlash('danger', ['title'=>'Erreur', 'message'=>"<b>Limitation Par Quantité vide</b>"]);
                return $this->redirectToRoute('backend_admin_article_add', ['form'=>$form]);
            }

            $article->setCreateBy($this->getUser());
			$this->em->persist($article);
			$this->em->flush();

            $this->addFlash('info', ['title'=>'Info', 
                                    'message'=>"Le produit a été bien créer. pour qu'il soit active il faut ajouter <b>au moins l'image d'accueil</b>"]);
        
            return $this->redirectToRoute('backend_admin_article_uploder', ['id' => $article->getId()]);
		}

        return $this->render('backend_admin/article/add.html.twig', ['form'=>$form->createView()] );
    }

    #[Route('/activation/{id}', name: 'backend_admin_article_activation')]
    public function activation(Article $article, Request $request)
    {
        $activation = $request->get('activation');

        if($activation == 'true'){
            $article->setActive(true);
        }else if($activation == 'false'){
            $article->setActive(false);
        }

        $this->em->persist($article);
		$this->em->flush();

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


    #[Route('/update/{id}', name: 'backend_admin_article_update')]
    public function update(Article $article, Request $request): Response
    {
        $form = $this->createForm(ArticleType::class, $article);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            
            $article = $form->getData();
            
            if( ($article->getLimitType() == 0) && ($article->getLimitDate() == null) ){
                $this->addFlash('danger', ['title'=>'Erreur', 'message'=>"<b>Limitation Par Date vide</b>"]);
                return $this->redirectToRoute('backend_admin_article_add', ['form'=>$form]);
            }

            if( ($article->getLimitType() == 1) && ($article->getLimitQuantite() <= 0) ){
                $this->addFlash('danger', ['title'=>'Erreur', 'message'=>"<b>Limitation Par Quantité vide</b>"]);
                return $this->redirectToRoute('backend_admin_article_add', ['form'=>$form]);
            }
			
			$this->em->persist($article);
			$this->em->flush();
            
		}

        return $this->render('backend_admin/article/detail.html.twig', ['form'=>$form->createView(), 'article'=>$article] );
    }
    

    #[Route('/uploder/{id}', name: 'backend_admin_article_uploder')]
    public function uploder(Article $article)
    {
        return $this->render('backend_admin/article/uploder.htm.twig', ['article'=>$article]);
    }


    #[Route('/uploder_image/{id}', name: 'backend_admin_article_uploder_add')]
    public function uploder_add(Article $article, Request $request)
    {
        $idSociete = $article->getSociete()->getId();
        $idArticle = $article->getId();

        $type = $request->request->get('type');
        
        $directory = $this->getParameter('articles_directory');
        
        $base64_image = $request->request->get('image64');
                          
        $posJpeg = strpos($base64_image, 'data:image/jpeg;base64,');
        if ($posJpeg !== false){
            $base64_img = str_replace('data:image/jpeg;base64,', '', $base64_image);
            $extension = ".jpeg";
        }
        
        $posPng = strpos($base64_image,'data:image/png;base64,');
        if ($posPng !== false){
            $base64_img = str_replace('data:image/png;base64,', '', $base64_image);
            $extension = ".png";
        }

        $posJpg = strpos($base64_image, 'data:image/jpg;base64,');
        if ($posJpg !== false){
            $base64_img = str_replace('data:image/jpg;base64,', '', $base64_image);
            $extension = ".jpg";
        }

        $posGif = strpos($base64_image,'data:image/gif;base64,');
        if ($posGif !== false){
            $base64_img = str_replace('data:image/gif;base64,', '', $base64_image);
            $extension = ".gif";
        }

        $namefile = "$idSociete-$idArticle-$type-".md5(rand()).$extension;

        $image = base64_decode($base64_img);
       

        if($image){ 

            $result = file_put_contents($directory . $namefile, $image);

            if($result){
                if($type == 'default'){
                    if($article->getImageDefault() && file_exists($directory . $article->getImageDefault()) ){ 
                        unlink($directory . $article->getImageDefault());
                    }
                    $article->setImageDefault($namefile);
                    $article->setActive(true);
                }elseif($type == 'detail1'){
                    if($article->getImageDetail1() && file_exists($directory . $article->getImageDetail1()) ){ 
                        unlink($directory . $article->getImageDetail1());
                    }
                    $article->setImageDetail1($namefile);
                }
                elseif($type == 'detail2'){
                    if($article->getImageDetail2() && file_exists($directory . $article->getImageDetail2()) ){ 
                        unlink($directory . $article->getImageDetail2());
                    }
                    $article->setImageDetail2($namefile);
                }
                elseif($type == 'detail3'){
                    if($article->getImageDetail3() && file_exists($directory . $article->getImageDetail3()) ){ 
                        unlink($directory . $article->getImageDetail3());
                    }
                    $article->setImageDetail3($namefile);
                }
                elseif($type == 'detail4'){
                    if($article->getImageDetail4() && file_exists($directory . $article->getImageDetail4()) ){ 
                        unlink($directory . $article->getImageDetail4());
                    }
                    $article->setImageDetail4($namefile);
                }

                $this->em->persist($article);
            }
        }
         
        $this->em->flush();
        return new Response();
    }


    #[Route('/uploder_image_delete', name: 'backend_admin_article_uploder_delete')]
    public function uploder_delete(Request $request)
    {
        die();
    }

}