<?php

namespace App\Controller;

use App\Entity\Buy;
use App\Entity\Cource;
use App\Entity\Institution;
use App\Entity\Panier;
use App\Entity\PhotoCource;
use App\Form\CourceType;
use App\Repository\CourceRepository;
use App\Repository\InstitutionRepository;
use Symfony\Component\Validator\Constraints\Date;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/cource")
 */
class CourceController extends AbstractController
{
    /**
     * @Route("/", name="cource_index", methods={"GET"})
     */
    public function index(CourceRepository $courceRepository,InstitutionRepository $institutionRepository): Response
    {
        $user=$this->getUser();
        $em = $this->getDoctrine();
        $institution= $em->getRepository(Institution::class)->findOneBy(array("user" => $user));
            $cources = $this->getDoctrine()
            ->getRepository(Cource::class)
            ->findAll();
        foreach($cources as $index => $cource)
            {
                 $date = new \DateTime('now');
                 $dateEnd = $cource->getCourseEnd();
                 $interval =  date_diff($dateEnd, $date);
                 if($interval->format('%R%a') > +3){
                    $photos = $this->getDoctrine()
                    ->getRepository(PhotoCource::class)
                    ->findBy(['Cource' => $cource]);
                foreach ($photos as $index => $photo) {
                    $entityManager = $this->getDoctrine()->getManager();
                    $entityManager->remove($photo);
                    $entityManager->flush();
                }
                $paniers= $this->getDoctrine()
                    ->getRepository(Panier::class)
                    ->findBy(['Cource' => $cource]);
                foreach ($paniers as $index => $panier) {
                    $entityManager = $this->getDoctrine()->getManager();
                    $entityManager->remove($panier);
                    $entityManager->flush();
                }

                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->remove($cource);
                $entityManager->flush();
            }
        }
        $cources = $this->getDoctrine()
            ->getRepository(Cource::class)
            ->findBy(['Institution' => $institution]);

        return $this->render('cource/index.html.twig', [
            'cources' => $cources,
            'institution' => $institution
        ]);

    }


    /**
     * @Route("/new", name="cource_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $cource = new Cource();
        $form = $this->createForm(CourceType::class, $cource);
        $form->handleRequest($request);
        $user=$this->getUser();
        $em = $this->getDoctrine();
        $inst= $em->getRepository(Institution::class)->findOneBy(array("user" => $user));
        if ($form->isSubmitted() && $form->isValid()) {
            $data = $request->request->all();
            $institution= $em->getRepository(Institution::class)->findOneBy(array("user" => $user));
            $entityManager = $this->getDoctrine()->getManager();
            $cource->setInstitution($institution);
            $cource->setDescription($data['description']);
            $cource->setDiscountVal($data['discountVal']);
            $entityManager->persist($cource);
            $entityManager->flush();

            $files = $request->files->get('image');
            foreach($files as $file)
            {
                if ($file) {
                    $originalFilenameFile=$file->getClientOriginalName();
                    $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                    // this is needed to safely include the file name as part of the URL
                    $safeFilename=time();
                    $newFilename = $safeFilename . '-' . uniqid() . '.' . $file->guessExtension();

                    // Move the file to the directory where brochures are stored
                    try {
                        $file->move(
                            $this->getParameter('files_directory'),
                            $newFilename
                        );
                    } catch (FileException $e) {
                        // ... handle exception if something happens during file upload
                    }
                    $files= new PhotoCource() ;
                    $files->setPath($newFilename);
                    $files->setCource($cource);
                    $files->setType('optional');
                    $entityManager = $this->getDoctrine()->getManager();
                    $entityManager->persist($files);
                    $entityManager->flush();
                }


            }
            $fileThumbil = $request->files->get('thumbail');
            if ($fileThumbil) {
                $originalFilenameFile=$fileThumbil->getClientOriginalName();
                $originalFilename = pathinfo($fileThumbil->getClientOriginalName(), PATHINFO_FILENAME);
                // this is needed to safely include the file name as part of the URL

                $safeFilename=time();

                $newFilename = $safeFilename . '-' . uniqid() . '.' . $fileThumbil->guessExtension();

                // Move the file to the directory where brochures are stored
                try {
                    $fileThumbil->move(
                        $this->getParameter('files_directory'),
                        $newFilename
                    );
                } catch (FileException $e) {
                    // ... handle exception if something happens during file upload
                }
                $files= new PhotoCource() ;
                $files->setPath($newFilename);
                $files->setCource($cource);
                $files->setType('thumbelnail');
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->persist($files);
                $entityManager->flush();
            }

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

        return $this->render('cource/new.html.twig', [
            'cource' => $cource,
            'form' => $form->createView(),
            'institution' => $inst
        ]);
    }

    /**
     * @Route("/{id}", name="cource_show", methods={"GET"})
     */
    public function show(Cource $cource): Response
    {
        return $this->render('cource/show.html.twig', [
            'cource' => $cource,
        ]);
    }

    /**
     * @Route("/edit/{id}", name="cource_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Cource $cource): Response
    {
        $form = $this->createForm(CourceType::class, $cource);
        $form->handleRequest($request);
        $inst= $this->getDoctrine()->getRepository(Institution::class)->findOneBy(array("user" => $this->getUser()));

        if ($form->isSubmitted() && $form->isValid()) {
            $data = $request->request->all();
            $cource->setDescription($data['description']);
            $cource->setDiscountVal($data['discountVal']);
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($cource);
            $entityManager->flush();

            $this->getDoctrine()->getManager()->flush();
            $Photos = $this->getDoctrine()
                ->getRepository(PhotoCource::class)
                ->findBy(['Cource' => $cource]);
            foreach ($Photos as $index => $file) {
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->remove($file);
                $entityManager->flush();
            }

            $files = $request->files->get('image');
            foreach($files as $file)
            {
                if ($file) {
                    $originalFilenameFile=$file->getClientOriginalName();
                    $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                    // this is needed to safely include the file name as part of the URL
                    $safeFilename=time();
                    $newFilename = $safeFilename . '-' . uniqid() . '.' . $file->guessExtension();

                    // Move the file to the directory where brochures are stored
                    try {
                        $file->move(
                            $this->getParameter('files_directory'),
                            $newFilename
                        );
                    } catch (FileException $e) {
                        // ... handle exception if something happens during file upload
                    }
                    $files= new PhotoCource() ;
                    $files->setPath($newFilename);
                    $files->setCource($cource);
                    $files->setType('optional');
                    $entityManager = $this->getDoctrine()->getManager();
                    $entityManager->persist($files);
                    $entityManager->flush();
                }


            }
            $fileThumbil = $request->files->get('thumbail');

            if ($fileThumbil) {
                $originalFilenameFile=$fileThumbil->getClientOriginalName();
                $originalFilename = pathinfo($fileThumbil->getClientOriginalName(), PATHINFO_FILENAME);
                // this is needed to safely include the file name as part of the URL
                $safeFilename=time();
                $newFilename = $safeFilename . '-' . uniqid() . '.' . $fileThumbil->guessExtension();

                // Move the file to the directory where brochures are stored
                try {
                    $fileThumbil->move(
                        $this->getParameter('files_directory'),
                        $newFilename
                    );
                } catch (FileException $e) {
                    // ... handle exception if something happens during file upload
                }
                $files= new PhotoCource() ;
                $files->setPath($newFilename);
                $files->setCource($cource);
                $files->setType('thumbelnail');
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->persist($files);
                $entityManager->flush();
            }


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

        return $this->render('cource/edit.html.twig', [
            'cource' => $cource,
            'form' => $form->createView(),
            'institution' => $inst
        ]);
    }

    /**
     * @Route("/{id}", name="cource_delete", methods={"DELETE"})
     */
    public function delete(Request $request, Cource $cource): Response
    {
        if ($this->isCsrfTokenValid('delete'.$cource->getId(), $request->request->get('_token'))) {
            $photos = $this->getDoctrine()
                ->getRepository(PhotoCource::class)
                ->findBy(['Cource' => $cource]);
            foreach ($photos as $index => $photo) {
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->remove($photo);
                $entityManager->flush();
            }
            $paniers= $this->getDoctrine()
                ->getRepository(Panier::class)
                ->findBy(['Cource' => $cource]);
            foreach ($paniers as $index => $panier) {
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->remove($panier);
                $entityManager->flush();
            }

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($cource);
            $entityManager->flush();
        }

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