<?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\Repository\AnnonceRepository;

use App\Entity\Annonce;

use App\Form\BackendAdmin\AnnonceType;

use App\Service\UploaderService;


#[Route('/backend/admin/annonce')]
class AnnonceController extends AbstractController
{

    /**
     * @var AnnonceRepository $annonceRepository
     */
    private $annonceRepository;

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

    /**
     * @param AnnonceRepository $annonceRepository
     * @param EntityManagerInterface $em
     * @return $this
     */
    public function __construct(
        AnnonceRepository $annonceRepository,
        EntityManagerInterface $em
    ){
        $this->annonceRepository = $annonceRepository;
        $this->em = $em;
    }


    #[Route('/index', name: 'backend_admin_annonce_index')]
    public function index(): Response
    {
        return $this->render('backend_admin/annonce/index.html.twig', ['annonces'=> $this->annonceRepository->findBy([], ["id"=>'DESC'])]);
    }

    
    #[Route('/add', name: 'backend_admin_annonce_add')]
    public function add(Request $request): Response
    {
        $annonce = new Annonce();
		
		$form = $this->createForm(AnnonceType::class, $annonce);

        $form->handleRequest($request);
		if ($form->isSubmitted() && $form->isValid()) {
            
            $annonce->setCreateBy($this->getUser());
            $this->em->persist($annonce);
			$this->em->flush();

            $this->addFlash('info', ['title'=>'Info', 
                                        'message'=>"L'annonce a été bien créer. pour qu'il soit complet il faut ajouter <b>au moins l'image d'accueil, recherche et détail</b>"]);
        
            return $this->redirectToRoute('backend_admin_annonce_uploder', ['id' => $annonce->getId()]);

		}
        
        return $this->render('backend_admin/annonce/add_update.htm.twig',['form'=>$form]);
    }



    #[Route('/update/{id}', name: 'backend_admin_annonce_update')]
    public function update(Request $request, Annonce $annonce): Response
    {
        $form = $this->createForm(AnnonceType::class, $annonce);

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

            $annonce->setDateUpdate(new \DateTime());
            $this->em->persist($annonce);
			$this->em->flush();

            $this->addFlash('success', ['title'=>'Success', 'message'=>"L'annonce a été bien modifier."]);

		}
        
        return $this->render('backend_admin/annonce/add_update.htm.twig',['form'=>$form]);
    }


    #[Route('/delete/{id}', name: 'backend_admin_annonce_delete')]
    public function delete(Annonce $annonce, Request $request)
    {
        $delete = (boolean)$request->get('delete');
        
        $annonce->setActive($delete);
        $this->em->persist($annonce);
        $this->em->flush();
        
        if($delete  == true ){
            $this->addFlash('success', ['title'=>'Success', 'message'=>"L'annoce a été bien activer"]);
        }else{
            $this->addFlash('success', ['title'=>'Success', 'message'=>"L'annoce a été bien déactiver"]);
        }

        $referer = $request->headers->get('referer');
        return $this->redirect($referer);
    }



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


    #[Route('/uploder_image/{id}', name: 'backend_admin_annonce_uploder_add')]
    public function uploder_add(Annonce $annonce, Request $request)
    {
        $idSociete = $annonce->getSociete()->getId();
        $idAnnonce = $annonce->getId();

        $type = $request->request->get('type');
        
        $directory = $this->getParameter('annonces_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-$idAnnonce-$type-".md5(rand()).$extension;

        $image = base64_decode($base64_img);
       

        if($image){ 

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

            if($result){
                if($type == 'home'){
                    if($annonce->getImageHome() && file_exists($directory . $annonce->getImageHome()) ){ 
                        unlink($directory . $annonce->getImageHome());
                    }
                    $annonce->setImageHome($namefile);
                }elseif($type == 'search'){
                    if($annonce->getImageSearch() && file_exists($directory . $annonce->getImageSearch()) ){ 
                        unlink($directory . $annonce->getImageSearch());
                    }
                    $annonce->setImageSearch($namefile);
                }
                elseif($type == 'detail1'){
                    if($annonce->getImageDetail1() && file_exists($directory . $annonce->getImageDetail1()) ){ 
                        unlink($directory . $annonce->getImageDetail1());
                    }
                    $annonce->setImageDetail1($namefile);
                }
                elseif($type == 'detail2'){
                    if($annonce->getImageDetail2() && file_exists($directory . $annonce->getImageDetail2()) ){ 
                        unlink($directory . $annonce->getImageDetail2());
                    }
                    $annonce->setImageDetail2($namefile);
                }
                elseif($type == 'detail3'){
                    if($annonce->getImageDetail3() && file_exists($directory . $annonce->getImageDetail3()) ){ 
                        unlink($directory . $annonce->getImageDetail3());
                    }
                    $annonce->setImageDetail3($namefile);
                }
                elseif($type == 'detail4'){
                    if($annonce->getImageDetail4() && file_exists($directory . $annonce->getImageDetail4()) ){ 
                        unlink($directory . $annonce->getImageDetail4());
                    }
                    $annonce->setImageDetail4($namefile);
                }

                $annonce->checkComplet(); 

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


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


//datatable.html.twig