<?php

namespace App\Controller;

use App\Entity\TourRequest;
use App\Entity\User;
use App\Form\TourRequestType;
use App\Repository\TourRequestRepository;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;

/**
 * @Route("/tourrequest")
 */
class TourRequestController extends AbstractController
{
    /**
     * @Route("/{page<[1-9]\d*>}", defaults={"page"=1}, name="tour_request_index")
     */
    public function index(Request $request, int $page): Response
    {
        $data = $request->request->get('form');
        if(isset($data['search']))
        {
            $filter = $data['search'];
        }
        else
        {
            $filter = '';
        }

        $tourRequests = $this->getDoctrine()
                         ->getRepository(TourRequest::class)
                         ->getAllTourRequest($page, $filter);

        return $this->render('tour_request/index.html.twig', [
            'tour_requests' => $tourRequests,
        ]);
    }

    /**
     * @Route("/new", name="tour_request_new", methods={"GET","POST"})
     */
    public function new(Request $request , MailerInterface $mailer): Response
    {
        $tourRequest = new TourRequest();
        $form = $this->createForm(TourRequestType::class, $tourRequest)
                     ->add('createNew', SubmitType::class); 
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $tourRequest->setSubmitionDate(new \DateTime("now", new \DateTimeZone("Asia/Dhaka")));
            $tourRequest->setUser($this->getUser());
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($tourRequest);
            $entityManager->flush();
 
            $tourRequestId = $tourRequest->getId();

             //Email Send to Functional Head Start
             if($this->getUser()->getFunctionalHead() !== null)
             {
                 $functionalHeadObj = $entityManager->getRepository(User::class)->find($this->getUser()->getFunctionalHead());
                 $tokenVal = 'UOpyIH2IRbtJi3NWE3gokFKUATPuQplhge6BEc92WDw';
                 
                 $email = (new TemplatedEmail())
                     ->from('hr@cross-world.com')
                     ->to($functionalHeadObj->getOfficeEmail())
                     //->cc('mhn.khan@gmail.com', 'mdaasad89@gmail.com', 'info@famousmartbd.com')
                    // ->bcc('malaya@cross-world.com')
                     //->replyTo('fabien@example.com')
                     //->priority(Email::PRIORITY_HIGH)
                     ->subject('Tour Request of '.$this->getUser()->getfullName())           
                     // path of the Twig template to render
                     ->htmlTemplate('tour_request/tourRequest.html.twig')
                     // pass variables (name => value) to the template
                     ->context([                         
                         'tour_request' => $entityManager->getRepository(TourRequest::class)->find($tourRequestId),
                         'approvalStep' => 1,
                         'recommendedUrl' => 'http://45.64.134.180:8081/cwlms/public/index.php/tourrequest/functionalApproval/'.$tourRequestId.'/1/'.$tokenVal,
                         'notRecommendedUrl' => 'http://45.64.134.180:8081/cwlms/public/index.php/tourrequest/functionalApproval/'.$tourRequestId.'/0/'.$tokenVal,
                     ])
                     ;
                 
                 try {
                     $mailer->send($email);
                 } catch (TransportExceptionInterface $e) {
                     // some error prevented the email sending; display an
                     // error message or try to resend the message
                     dd($e);
                 }
             }//Email Send to Functional Head End
             else if($this->getUser()->getDepartmentHead() !== null) //Email Send to Department Head Start
             {
                 $departmentHeadObj = $userRepository->find($this->getUser()->getDepartmentHead());                
                 $tokenVal = 'UOpyIH2IRbtJi3NWE3gokFKUATPuQplhge6BEc92WDw';
                     
                 $email = (new TemplatedEmail())
                     ->from('hr@cross-world.com')
                     ->to($departmentHeadObj->getOfficeEmail())
                     //->cc('mhn.khan@gmail.com', 'mdaasad89@gmail.com', 'info@famousmartbd.com')
                    // ->bcc('malaya@cross-world.com')
                     //->replyTo('fabien@example.com')
                     //->priority(Email::PRIORITY_HIGH)
                     ->subject('Tour Request of '.$this->getUser()->getfullName())           
                     // path of the Twig template to render
                     ->htmlTemplate('leave_application/leaveApproval.html.twig')
                     // pass variables (name => value) to the template
                     ->context([
                         'leaveInfos' => $leaveInfo,
                         'leaveApplication' => $leaveApplicationRepository->find($leaveApplicationId),
                         'approvalStep' => 2,
                         'approvalUrl' => 'http://45.64.134.180:8081/cwlms/public/index.php/leaveapplication/departmentHeadApproval/'.$leaveApplicationId.'/1/'.$tokenVal,
                         'notApprovalUrl' => 'http://45.64.134.180:8081/cwlms/public/index.php/leaveapplication/departmentHeadApproval/'.$leaveApplicationId.'/0/'.$tokenVal,
                         'functionalHeadObj' => null,
                     ])
                     ;
                 
                 try {
                     $mailer->send($email);
                 } catch (TransportExceptionInterface $e) {
                     // some error prevented the email sending; display an
                     // error message or try to resend the message
                     dd($e);
                 }
             } //Email Send to Department Head End
 

            $this->addFlash('notice', 'Tour Request Created successfully!');

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

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

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

    /**
     * @Route("/{id}/edit", name="tour_request_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, TourRequest $tourRequest): Response
    {
        $form = $this->createForm(TourRequestType::class, $tourRequest);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            $this->addFlash('notice', 'Tour Request Updated successfully!');

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

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

    /**
     * @Route("/{id}/delete", name="tour_request_delete", methods={"DELETE"})
     */
    public function delete(Request $request, TourRequest $tourRequest): Response
    {
        if ($this->isCsrfTokenValid('delete'.$tourRequest->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($tourRequest);
            $entityManager->flush();
        }

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

    /**
     * @Route("/{id}/tour-request", name="tour_request_tourRequest", methods={"GET"})
     */
    public function tourRequest(TourRequest $tourRequest): Response 
    {
        
        return $this->render('tour_request/tourRequest.html.twig', [
            'tour_request' => $tourRequest,
        ]);
    }

    /**
     * @Route("/functionalApproval/{id}/{approvalStatus}/{tokenVal}", name="app_tour_request_functionalHeadApproval")
     */
    public function functionalHeadApproval($id, $approvalStatus, $tokenVal, Request $request, TourRequestRepository $tourRequestRepository, UserRepository $userRepository, MailerInterface $mailer)
    {        
        $tourRequestObj = $tourRequestRepository->find($id);

        // if($tourRequestObj->getFhApproval() !== null)
        // {
        //     return $this->render('tour_request/functionalHeadApproval.html.twig', [
        //         'taskTag' => 1,
        //     ]);
        // }

        $tourRequestObj->setFhApproval($approvalStatus);
        $tourRequestObj->setFhApprovalBy(1);
        $tourRequestObj->setFhApprovalDate(new \DateTime("now", new \DateTimeZone("Asia/Dhaka")));

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($tourRequestObj);
        $entityManager->flush();
 
        if($approvalStatus == 1)
        {
            $applicantUserObj = $userRepository->find($tourRequestObj->getUser()->getId());

            $departmentHeadObj = $userRepository->find($applicantUserObj->getDepartmentHead());
            $functionalHeadObj = $userRepository->find($applicantUserObj->getFunctionalHead());
            $tokenVal = 'UOpyIH2IRbtJi3NWE3gokFKUATPuQplhge6BEc92WDw';
                
            $email = (new TemplatedEmail())
                ->from('hr@cross-world.com')
                ->to($departmentHeadObj->getOfficeEmail())
                //->cc('mhn.khan@gmail.com', 'mdaasad89@gmail.com', 'info@famousmartbd.com')
                //->bcc('malaya@cross-world.com')
                //->replyTo('fabien@example.com')
                //->priority(Email::PRIORITY_HIGH)
                ->subject('Tour Request of '.$applicantUserObj->getfullName())           
                // path of the Twig template to render
                ->htmlTemplate('tour_request/tourRequest.html.twig')
                // pass variables (name => value) to the template
                ->context([                   
                    'tour_request' => $tourRequestObj,
                    'approvalStep' => 2,
                    'approvalUrl' => 'http://45.64.134.180:8081/cwlms/public/index.php/tourrequest/departmentHeadApproval/'.$id.'/1/'.$tokenVal,
                    'notApprovalUrl' => 'http://45.64.134.180:8081/cwlms/public/index.php/tourrequest/departmentHeadApproval/'.$id.'/0/'.$tokenVal,
                    'functionalHeadObj' => $functionalHeadObj,
                ])
                ;
            
            try {
                $mailer->send($email);
            } catch (TransportExceptionInterface $e) {
                // some error prevented the email sending; display an
                // error message or try to resend the message
                dd($e);
            }
        }

        return $this->render('tour_request/functionalHeadApproval.html.twig', [
            'taskTag' => $approvalStatus == 1 ? 0 : 2,
        ]);

       // return $this->redirectToRoute('app_leave_application_index', [], Response::HTTP_SEE_OTHER);
    }

    /**
     * @Route("/departmentHeadApproval/{id}/{approvalStatus}/{tokenVal}", name="app_leave_application_departmentHeadApproval")
     */
    public function departmentHeadApproval($id, $approvalStatus, $tokenVal, TourRequestRepository $tourRequestRepository, UserRepository $userRepository, MailerInterface $mailer)
    {        
        $tourRequestObj = $tourRequestRepository->find($id); 

        // if($tourRequestObj->getDhApproval() !== null)
        // {
        //     return $this->render('leave_application/departmentHeadApproval.html.twig', [
        //         'taskTag' => 1,
        //     ]);
        // }

        $tourRequestObj->setDhApproval($approvalStatus);
        $tourRequestObj->setDhApprovalBy(1);
        $tourRequestObj->setDhApprovalDate(new \DateTime("now", new \DateTimeZone("Asia/Dhaka")));

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($tourRequestObj);
        $entityManager->flush();

        if($approvalStatus == 1)
        {
          
            $applicantUserObj = $userRepository->find($tourRequestObj->getUser()->getId());

            $departmentHeadObj = $userRepository->find($applicantUserObj->getDepartmentHead());
            $functionalHeadObj = $userRepository->find($applicantUserObj->getFunctionalHead());

            $tokenVal = 'UOpyIH2IRbtJi3NWE3gokFKUATPuQplhge6BEc92WDw';
                
            $email = (new TemplatedEmail())
                ->from('hr@cross-world.com')
                ->to('malaya@cross-world.com')
                //->to('mortuja@cross-world.com')
                //->cc('mhn.khan@gmail.com', 'mdaasad89@gmail.com', 'info@famousmartbd.com')
                //->bcc('malaya@cross-world.com')
                //->replyTo('fabien@example.com')
                //->priority(Email::PRIORITY_HIGH)
                ->subject('Tour Request of '.$applicantUserObj->getfullName())           
                // path of the Twig template to render
                ->htmlTemplate('tour_request/tourRequest.html.twig')
                // pass variables (name => value) to the template
                ->context([                   
                    'tour_request' => $tourRequestObj,
                    'approvalStep' => 3,
                    'approvalUrl' => 'http://45.64.134.180:8081/cwlms/public/index.php/tourrequest/ceoApproval/'.$id.'/1/'.$tokenVal,
                    'notApprovalUrl' => 'http://45.64.134.180:8081/cwlms/public/index.php/tourrequest/ceoApproval/'.$id.'/0/'.$tokenVal,
                    'functionalHeadObj' => $functionalHeadObj,
                    'departmentHeadObj' => $departmentHeadObj,
                ])
                ;
            
            try {
                $mailer->send($email);
            } catch (TransportExceptionInterface $e) {
                // some error prevented the email sending; display an
                // error message or try to resend the message
                dd($e);
            }

        }


        return $this->render('leave_application/departmentHeadApproval.html.twig', [
            'taskTag' => $approvalStatus == 1 ? 0 : 2,
        ]);
    }


     /**
     * @Route("/ceoApproval/{id}/{approvalStatus}/{tokenVal}", name="app_leave_application_ceoApproval")
     */
    public function ceoApproval($id, $approvalStatus, $tokenVal, TourRequestRepository $tourRequestRepository)
    {        
        $tourRequestObj = $tourRequestRepository->find($id); 

        // if($tourRequestObj->getDhApproval() !== null)
        // {
        //     return $this->render('leave_application/departmentHeadApproval.html.twig', [
        //         'taskTag' => 1,
        //     ]);
        // }

        $tourRequestObj->setCeoApproval($approvalStatus);
        $tourRequestObj->setCeoApprovalBy(1);
        $tourRequestObj->setCeoApprovalDate(new \DateTime("now", new \DateTimeZone("Asia/Dhaka")));

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($tourRequestObj);
        $entityManager->flush();

        // if($approvalStatus == 1)
        // {
           

        // }

        return $this->render('leave_application/departmentHeadApproval.html.twig', [
            'taskTag' => $approvalStatus == 1 ? 0 : 2,
        ]);
    }


}
