<?php

namespace AppBundle\Controller;

use AppBundle\Entity\BreadcrumbEntry;
use AppBundle\Entity\ContactRequest;
use AppBundle\Entity\Page;
use AppBundle\Form\ContactRequestType;
use AppBundle\Form\SearchRequestType;
use AppBundle\Form\TtSearchRequestType;
use AppBundle\Util;
use Doctrine\ORM\EntityManager;
use Gedmo\Tree\TreeListener;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class DefaultController extends Controller
{
    /**
     * @return EntityManager
     */
    public function getEntityManager()
    {
        return $this->getDoctrine()->getManager();
    }

    public function defaultAction(Request $request)
    {
        throw $this->createNotFoundException();
    }

    /**
     * @Route("/")
     */
    public function homeAction()
    {
        return $this->render('default/pages/home.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            'canonical_url' => Util::getBaseUrl(),
            'show_search_sidebar_widget' => false,
            'show_offers_sidebar_widget' => false,
            'search_form' => $this->createForm(SearchRequestType::class)->createView(),
            'tt_search_form' => $this->createForm(TtSearchRequestType::class)->createView(),
            'country_pages' => $this->getEntityManager()->getRepository('AppBundle:Page')->findCountryPages(),
        ]);
    }

    /**
     * @Route("/suche")
     */
    public function searchAction(Request $request)
    {
        $form = $this->createForm(SearchRequestType::class);
        if (empty($request->query->get('b')))
        {
            $request->query->set('b', (new \DateTime('+5 day'))->format('d.m.Y'));
        }
        if (empty($request->query->get('e')))
        {
            $request->query->set('e', (new \DateTime('+19 day'))->format('d.m.Y'));
        }
        $form->handleRequest($request);

        if ($form->isValid())
        {
            $data = $form->getData();

            $destinationIds = [];
            if (!empty($data['c']))
            {
                $destinationIds = [$data['c']->getId()];
            }
            if (!empty($destinationIds) && !empty($data['c2']))
            {
                $destinationIds[] = $data['c2']->getId();
            }

            $r = $this->getDoctrine()->getRepository('AppBundle:TravelPeriod')->getTravelProgramsWithTravelDatesForTimePeriod(
                $data['b'], $data['e'], $destinationIds, count($destinationIds) > 1);
        }
        else
        {
            $r = [];
        }

        return $this->render('default/pages/search.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            'breadcrumb_entries' => [new BreadcrumbEntry('Suchen')],
            'search_form' => $form->createView(),
            'travel_programs' => $r,
        ]);
    }

    /**
     * @Route("/tt-suche")
     */
    public function ttSearchAction(Request $request)
    {
        $form = $this->createForm(TtSearchRequestType::class);
        if (empty($request->query->get('termin')))
        {
            $request->query->set('termin', (new \DateTime('+5 day'))->format('d.m.Y'));
        }
        if (empty($request->query->get('ruecktermin')))
        {
            $request->query->set('ruecktermin', (new \DateTime('+19 day'))->format('d.m.Y'));
        }
        $form->handleRequest($request);

        if ($form->isValid())
        {
            $data = $form->getData();

            $ttUrl = "http://dtps-ibe.traveltainment.de/offer/?&taid=DRS32"; //ibe=package";

             /*$requests = "&ibe=package&aidgiata=49720&ddate=".date("Y-m-d", 1523397600)."&depap=TXL&rdate=".date("Y-m-d", 1524002400)."&dur=6,2&brand=FTI&oid=ASW318;PAUS;;DSQF&adult=2";*/

            $ttUrl .= '&ddate=' . $data['termin']->format('d.m.Y');
            $ttUrl .= '&rdate=' . $data['ruecktermin']->format('d.m.Y');
            if (!empty($data['dauer'])){
                $ttUrl .= '&dur='.str_replace("_", ",", $data['dauer']);
            }

            if (!empty($data['t']))
            {
                $ttUrl .= '&adult='. $data['t'];
                $count = 0;
                for ($i = 0; $i < 3; ++$i)
                {
                    if (!empty($data['child'.$i]))
                    {
                        $count++;
                    }
                }
                $ttUrl .= '&child='. $count;
            }
            $ttUrl .= '&ibe=';
            if (!empty($data['topRegion']))
            {   
                if(isset(TtSearchRequestType::$DESTINATION_CHOICES[$data['topRegion']])){
                    $ttUrl .= 'package&rgid='. TtSearchRequestType::$DESTINATION_CHOICES[$data['topRegion']];
                }else{
                    $ttUrl .= 'package&rgid='. $data['topRegion'];
                }
                
            }
            else
            {
                $ttUrl .= 'package';
            }
            if (!empty($data['abflughafen'])) $ttUrl .= '&depap='. $data['abflughafen'];
            if (!empty($data['shotel'])) $ttUrl .= '&accom='. urlencode($data['shotel']);
            if (!empty($data['kategorie'])) $ttUrl .= '&stars='. $data['kategorie'];
            if (!empty($data['zimmer'])) $ttUrl .= '&room='. $data['zimmer'];
            if (!empty($data['verpflegung'])) $ttUrl .= '&board='. $data['verpflegung'];
            if (!empty($data['hbfges'])) $ttUrl .= '&raavg='. $data['hbfges'];
            if (!empty($data['hbfanz'])) $ttUrl .= '&hbfanz='. $data['hbfanz'];
            if (!empty($data['hbfempf'])) $ttUrl .= '&racnt='. $data['hbfempf'];
            //if ($data['familie_kinder'] ?? false) $ttUrl .= '&familie_kinder=0';
            //if ($data['strand'] ?? false) $ttUrl .= '&beach=0';
            //if ($data['wellness'] ?? false) $ttUrl .= '&wellness=0';
            //if ($data['typ'] ?? false) $ttUrl .= '&typ=0';
            if (!empty($data['sportangebot'])) $ttUrl .= '&sports='. $data['sportangebot'];

            /*$ttUrl = 'http://www.vidado.com/booking/ibe_bp2/index.php?CID=8ce65750ce5af9d9a6b22c9b04772ea7&formular=4&engine=pauschal&showresult=1';
            $ttUrl .= '&termin=' . $data['termin']->format('d.m.Y');
            $ttUrl .= '&ruecktermin=' . $data['ruecktermin']->format('d.m.Y');
            if (!empty($data['dauer'])) $ttUrl .= '&dauer='. $data['dauer'];
            if (!empty($data['t']))
            {
                $ttUrl .= '&personen=25'. str_repeat(';25', $data['t'] - 1);
                for ($i = 0; $i < 3; ++$i)
                {
                    if (!empty($data['child'.$i]))
                    {
                        $ttUrl .= ';'. $data['child'. $i];
                    }
                }
            }
            $ttUrl .= '&detail=';
            if (!empty($data['topRegion']) && isset(TtSearchRequestType::$DESTINATION_CHOICES[$data['topRegion']]))
            {
                $ttUrl .= 'hotel&topRegion='. TtSearchRequestType::$DESTINATION_CHOICES[$data['topRegion']];
            }
            else
            {
                $ttUrl .= 'zielgebiet';
            }
            if (!empty($data['abflughafen'])) $ttUrl .= '&abflughafen='. $data['abflughafen'];
            if (!empty($data['shotel'])) $ttUrl .= '&shotel='. urlencode($data['shotel']);
            if (!empty($data['kategorie'])) $ttUrl .= '&kategorie='. $data['kategorie'];
            if (!empty($data['zimmer'])) $ttUrl .= '&zimmer='. $data['zimmer'];
            if (!empty($data['verpflegung'])) $ttUrl .= '&verpflegung='. $data['verpflegung'];
            if (!empty($data['hbfges'])) $ttUrl .= '&hbfges='. $data['hbfges'];
            if (!empty($data['hbfanz'])) $ttUrl .= '&hbfanz='. $data['hbfanz'];
            if (!empty($data['hbfempf'])) $ttUrl .= '&hbfempf='. $data['hbfempf'];
            if ($data['familie_kinder'] ?? false) $ttUrl .= '&familie_kinder=0';
            if ($data['strand'] ?? false) $ttUrl .= '&strand=0';
            if ($data['wellness'] ?? false) $ttUrl .= '&wellness=0';
            if ($data['typ'] ?? false) $ttUrl .= '&typ=0';
            if (!empty($data['sportangebot'])) $ttUrl .= '&sportangebot='. $data['sportangebot'];
            */

        }else{
            if(strpos($_SERVER['QUERY_STRING'], 'ttexpedient')){
                
                $get_array = array();
                parse_str($_SERVER['QUERY_STRING'], $get_array);

                if(!empty($get_array['detail'])) { $det=$get_array['detail']; }
                else { $det=""; }

                if(!empty($get_array['IFF'])) { $iff=$get_array['IFF']; }
                else { $iff=""; }

                if(!empty($get_array['abflughafen'])) { $airp=$get_array['abflughafen']; }
                else { $airp=""; }

                if(!empty($get_array['sleistung'])) { $sleist=$get_array['sleistung']; }
                else { $sleist=""; }

                if(!empty($get_array['showresult'])) { $show=$get_array['showresult']; }
                else { $show=""; }

                if(!empty($get_array['personen'])) { $pers=$get_array['personen']; }
                else { $pers=""; }

                if(!empty($get_array['marke'])) { $va=$get_array['marke']; }
                else { $va=""; }

                if(!empty($get_array['termin'])) { $hin=$get_array['termin']; }
                else { $hin=""; }

                if(!empty($get_array['ruecktermin'])) { $rueck=$get_array['ruecktermin']; }
                else { $rueck=""; }

                if(!empty($get_array['dauer'])) { $dau=$get_array['dauer']; }
                else { $dau=""; }

                if(!empty($get_array['bplink'])) { $bli=$get_array['bplink']; }
                else { $bli=""; }

                if(!empty($get_array['ttexpedient'])) { $exp=$get_array['ttexpedient']; }


                else { $exp=""; }
                if($dau != "" && strpos($dau, "_")){
                    $dau = explode("_", $dau);
                    asort($dau);
                    $dau = implode(",", $dau);
                }
                $adult = substr_count($pers, '25');
                $child = "";
                $ps = explode(';', $pers);
               
                foreach ($ps as $p) {
                    if($p < 25){
                        $child .= $p.",";
                    }
                }
                $child = rtrim($child, ',');
                $url = "http://dtps-ibe.traveltainment.de/offer?taid=DRS32"; 
                $url .= '&ibe=package&adult='.$adult.'&ddate='.date("Y-m-d", $hin).'&rdate='.date("Y-m-d", $rueck).'&depap='.$airp.'&aid='.$iff.'&brand='.$va.'&dur='.$dau.'&child='.$child;
            
                $ttUrl = urldecode($url);
             }

        }

        return $this->render('default/pages/ttSearch.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            'breadcrumb_entries' => [new BreadcrumbEntry('Suchen')],
            'tt_search_form' => $form->createView(),
            'tt_url' => $ttUrl ?? null,
        ]);
    }

    /**
     * @Route("/kontakt")
     */
    public function contactAction(Request $request)
    {
        $form = $this->createForm(ContactRequestType::class);
        $breadcrumbEntries = [new BreadcrumbEntry('Kontaktformular')];

        if ($request->getMethod() == 'POST')
        {
            $form->handleRequest($request);

            if ($form->isValid())
            {
                /** @var ContactRequest $contactRequest */
                $contactRequest = $form->getData();

                $crmLeadUrl = $this->get('app.contact_exporter')->process($contactRequest);
                if ($crmLeadUrl)
                {
                    $crmLeadUrl = preg_replace('/\\/api\\/lead/', '/leads', $crmLeadUrl) .'/edit';
                }
                else
                {
                    $crmLeadUrl = '[Übertragung zum CRM fehlgeschlagung]';
                }

                $this->get('mailer')->send(\Swift_Message::newInstance()
                    ->setSubject('Kontaktformular (stern-tours.de)')
                    ->setFrom('stern@stern-tours.de', 'STERN TOURS')
                    ->setTo('stern@stern-tours.de')
                    ->setBody(
                        $this->renderView('default/email/contactServiceEmail.txt.twig', [
                            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
                            'crm_url' => $crmLeadUrl,
                            'contact_request' => $contactRequest,
                        ]),
                        'text/plain', 'utf-8'
                    )
                );

                // #TODO This will lead to multiple submissions. Redirect instead!
                return $this->render('default/pages/contactConfirmation.html.twig', [
                    'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
                    'breadcrumb_entries' => $breadcrumbEntries,
                ]);
            }
        }

        return $this->render('default/pages/contact.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            'breadcrumb_entries' => $breadcrumbEntries,
            'contact_form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/sitemap")
     */
    public function sitemapAction()
    {
        $repo = $this->getDoctrine()->getRepository('AppBundle:Page');
        $rootNodes = $repo->getRootNodesQueryBuilder()
            ->andWhere('node.status = 1')
            ->andWhere('node.lvl = 0')
            ->getQuery()
            ->execute()
        ;
        /** @var Page[] $pageNodes Actually no entity objects but associative arrays representing page entities */
        $pageNodes = [];
        foreach ($rootNodes as $rootNode)
        {
            $pageNodes[] = $repo->buildTree($repo->getNodesHierarchyQueryBuilder($rootNode, false, [], true)
                ->leftJoin('node.travelProgram', 'tp')
                ->andWhere('(tp.id IS NULL OR tp.status = 1)')
                ->andWhere('node.status = 1')
                ->getQuery()
                ->getArrayResult()
            )[0];
        }
        return $this->render('default/pages/sitemap.html.twig', [
            'breadcrumb_entries' => [new BreadcrumbEntry('Sitemap')],
            'page_nodes' => $pageNodes
        ]);
    }

    /*
    Suche Kindknoten
    Für jeden Kindknoten
        ++LFT
        Setze LFT
        f()
        ++LFT
        RGT = LFT
        Setze RGT
    */

    /**
     * @Route("/create-tree")
     */
    public function createTreeAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '2048M');

        $em = $this->getEntityManager();

        $em->getConnection()->executeUpdate(
            'UPDATE page SET lvl = NULL, lft = NULL, rgt = NULL, parent_id = NULL, tree_root = NULL');

        foreach ($em->getEventManager()->getListeners() as $event => $listeners) {
            foreach ($listeners as $hash => $listener) {
                if ($listener instanceof TreeListener)
                {
                    $em->getEventManager()->removeEventListener($event, $listener);
                }
            }
        }

        $em->beginTransaction();

        // Add missing owner relation for catalog root pages (e.g. children of 'aegypten-reisen')
        $em->getConnection()->executeUpdate('UPDATE page SET owner = 47 WHERE catalog_id = 3 AND owner = 0');
        $em->getConnection()->executeUpdate('UPDATE page SET owner = 66 WHERE catalog_id = 6 AND owner = 0');
        $em->getConnection()->executeUpdate('UPDATE page SET owner = 2803 WHERE catalog_id = 14 AND owner = 0');
        // Add missing owner relation
        $em->getConnection()->executeUpdate('UPDATE page SET owner = 13 WHERE id in (1314,1426,1472,1548)');

        $lft = 0;
        $this->createTree(0, $lft, 0);
        $em->flush();

        // Reset the owner field to avoid problems in the old website
        $em->getConnection()->executeUpdate('UPDATE page SET owner = 0 WHERE parent_id = 47 AND catalog_id = 3');
        $em->getConnection()->executeUpdate('UPDATE page SET owner = 0 WHERE parent_id = 66 AND catalog_id = 6');
        $em->getConnection()->executeUpdate('UPDATE page SET owner = 0 WHERE parent_id = 2803 AND catalog_id = 14');
        $em->getConnection()->executeUpdate('UPDATE page SET owner = 0 WHERE id in (1314,1426,1472,1548)');

        $em->commit();

        die("DONE.");
    }

    private function createTree($owner, &$lft, $lvl, $root = null)
    {
        $em = $this->getEntityManager();

        $qb = $em->createQueryBuilder()->from('AppBundle:Page', 'p')->select('p');
        $qb->where($qb->expr()->eq('p.owner', $owner));
        if ($owner == 0)
        {
            $qb->orWhere('p.owner IS NULL');
        }
        $qb->orderBy('p.order');
        $qb->addOrderBy('p.title');
        $pages = $qb->getQuery()->execute();
        foreach ($pages as $page)
        {
            /** @var Page $page */

            if ($owner == 0)
            {
                $root = $page->getId();
            }

            ++$lft;
            $page->setLft($lft);
            $page->setLvl($lvl);
            $page->setRoot($em->getReference('AppBundle:Page', $root));
            if ($owner != 0)
            {
                $page->setParent($em->getReference('AppBundle:Page', $owner));
            }

            $this->createTree($page->getId(), $lft, $lvl + 1, $root);

            ++$lft;
            $page->setRgt($lft);

            $em->persist($page);
        }
    }
}