<?php
/**
 * @author Ulrich Hecht <ulrich.hecht@hecht-software.de>
 * @date 02/22/2017
 */

namespace AppBundle\Controller;


use AppBundle\Entity\Page;
use AppBundle\Entity\SunstarTravelProgram;
use AppBundle\Entity\FewoLodgingGroup;
use AppBundle\Form\TtSearchRequestType;
use AppBundle\Listener\KernelControllerListener;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use AppBundle\Util;
use Symfony\Component\HttpFoundation\Response;

/**
 * Controller for CMS pages. CMS pages are represented by Page instances (i.e. entries of the page database table).
 * The template property of a Page object defines the action method below. If a travel program is assigned then the
 * travelProgramAction is used. If no template is specified, then the defaultAction is used.
 * If there is no action method, the defaultAction is called and the template name is passed as an argument. A twig
 * file with this template will be rendered in this case.
 *
 * The view templates can be found pages/cms.
 *
 * Also see {@link KernelControllerListener}, which handles routing.
 *
 * @package AppBundle\Controller
 */
class CmsController extends Controller
{
    /**
     * @return EntityManager
     */
    private function getEntityManager()
    {
        return $this->getDoctrine()->getManager();
    }

    public function defaultAction(Page $page, $template = 'default')
    {
        return $this->render('default/pages/cms/'. $template .'.html.twig', [
          'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
          'page' => $page,
        ]);
    }

    public function overviewAction(Page $page)
    {
        $settings = $page->getCmsSettings();
        if (!is_array($settings))
        {
            $settings = [];
        }

        $fewoLodgingGroupRepo = $this->getEntityManager()->getRepository('AppBundle:FewoLodgingGroup');
        $lodgingGroups = $fewoLodgingGroupRepo->findAll();


        return $this->render('default/pages/cms/overview.html.twig', array_merge($settings, [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            'page' => $page,
            'lodgingGroups' => $lodgingGroups,
        ]));
    }

    public function travelProgramOverviewAction(Page $page)
    {
        $childPages =
          $this->getEntityManager()->getRepository('AppBundle:Page')->getChildrenWithTravelProgramsAndDates($page);

        $nonMediated = [];
        $mediated = [];
        foreach ($childPages as $childPage)
        {
            if ($childPage->getStatus() == 1 && $childPage->getTravelProgram() &&
                $childPage->getTravelProgram()->getIsMediated())
            {
                $mediated[] = $childPage;
            }
            else
            {
                $nonMediated[] = $childPage;
            }
        }
        // We only need a separation if there are mediated AND non mediated travel programs
        if (empty($nonMediated) && !empty($mediated))
        {
            $childPages = $mediated;
            $mediated = null;
        }
        else
        {
            $childPages = $nonMediated;
        }

        return $this->render('default/pages/cms/travelProgramOverview.html.twig', [
            'base_dir'    => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            'page'        => $page,
            'child_pages' => $childPages,
            'mediated_child_pages' => $mediated,
        ]);
    }

    public function traveltainmentAction(Page $page)
    {
        $destination = array_search($page->getBumaDestination(), TtSearchRequestType::$DESTINATION_CHOICES);
        $form = $this->createForm(TtSearchRequestType::class, [
            'topRegion' => $destination ? $destination : null,
        ], [
            'country' => $page->getCountry(),
        ]);

        return $this->render('default/pages/cms/traveltainment.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            'page' => $page,
            'show_search_sidebar_widget' => false,
            'tt_search_form' => $form->createView(),
        ]);
    }

    public function travelProgramAction(Page $page)
    {
        $this->getDoctrine()->getRepository('AppBundle:TravelPeriod')->getTrueTravelPeriods($page->getTravelProgram());

        // replace this example code with whatever you need
        return $this->render('default/pages/cms/travelProgram.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            'page' => $page,
            'show_offers_sidebar_widget' => false,
            'travel_program' => $page->getTravelProgram(),
        ]);
    }

    public function fewoLodgingAction(Page $page)
    {
        $calendarService = $this->container->get('app.lodging_calendar_util');
        $lodging = $page->getFewoLodging();

        $paddedCalendar = $calendarService->getCalendarWithPadding($calendarService->getMinCalendarEntriesByLodging($lodging));
        if (count($lodging->getPrices()->toArray()) != 0)
        {
            $calendar = $calendarService->createCalendarAndFillDayStates($lodging);
            $calendar = $calendarService->mergeWithPaddedCalendar($calendar, $paddedCalendar);
        } else {
            $calendar = $paddedCalendar;
        }

        $imgs = array();
        $imgs_pre = array();
        $imgs_post = array();

        $lodgingGroup = $lodging->getGroup();
        foreach ($lodgingGroup->getImages() as $image) {
            if($image->getComp() == 'pre'){
                $imgs_pre[] = $image;
            }
            if($image->getComp() == 'post'){
                $imgs_post[] = $image;
            }
        }
        foreach ($lodging->getImages() as $image) {
            $imgs[] = $image;
        }


        return $this->render('default/pages/cms/fewoTravelProgram.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            'page' => $page,
            'fewo_lodging' => $lodging,
            'slider_imgs' => array_merge ($imgs_pre, $imgs, $imgs_post),
            //'lodging' => $lodging, //so wurde es im AdminController aufgerufen
            'calendar' => $calendar,
            'show_search_sidebar_widget' => false,

        ]);
    }

    public function pdfAction(Page $page)
    {
        $travelProgram = $page->getTravelProgram();
        $program_id = $travelProgram->getId();

        if($program_id != NULL)
        {

            $url =  Util::getBaseUrl().$page->getUrlPath();

            // Initialisierung
            $pdfObj = $this->container->get('app.pdf');
            $pdfObj->SetMargins(PDF_MARGIN_LEFT, 40, PDF_MARGIN_RIGHT);
            $pdfObj->SetAutoPageBreak(true, 65);
            $pdfObj->AddPage();

            // Erzeugen des HTML über das Twig-Template
            $pageHTML = $this->render('default/pages/cms/travelProgramPDF.html.twig', [
                'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
                'page' => $page,
                'show_offers_sidebar_widget' => false,
                'travel_program' => $page->getTravelProgram()
            ]);

            // Filtern von Hyper-Links
            $filteredContent = preg_replace('#<p><a(.*)>(.*)</a></p>#Uis', '', $pageHTML->getContent());
            $filteredContent = preg_replace('#<a(.*)>#Uis', '', $filteredContent);
            $filteredContent = preg_replace('#</a>#Uis', '', $filteredContent);
            $filteredContent = str_replace('*', '<img src="https://www.stern-tours.de/images/icons/star-mini.png" />', $filteredContent);

            // Schreiben des HTML
            $pdfObj->writeHTML('<strong>Reiseangebot zu finden unter:</strong><br /><a href="'.$url.'"style="text-decoration: none!; font-size: 10px; color: black;">'.$url.'</a><br />');
            $pdfObj->writeHTML($filteredContent);

            // Ersetzen der Umlaute
            $germanLetters = array("/ä/","/ö/","/ü/","/Ä/","/Ö/","/Ü/","/ß/");
            $replace = array("ae","oe","ue","Ae","Oe","Ue","ss");
            $filename = preg_replace($germanLetters, $replace, $travelProgram->getTitle());

            header('Link: <'.$travelProgram->getUrl().'>; rel="canonical"');

            $pdfObj->Output($filename.'.pdf', 'D');
        }
    }



    /**
     * @param Page $page
     *
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @todo This is actually the same as overview, but with different sidebar. Utilize cmsSettings field of page entity for such requirements
     */
    public function jugendreisenAction(Page $page)
    {
        return $this->render('default/pages/cms/overview.html.twig', [
            'page' => $page,
            'show_search_sidebar_widget' => false,
            'show_offers_sidebar_widget' => false,
        ]);
    }

    public function sunstarAction(Page $page)
    {
        /** @var SunstarTravelProgram[] $sunstarTravelPrograms */
        $sunstarTravelPrograms = $this->getDoctrine()->getRepository('AppBundle:SunstarTravelProgram')
            ->findBy(['destination' => $page->getCmsSettings()]);

        return $this->render('default/pages/cms/sunstar.html.twig', [
            'page' => $page,
            'show_search_sidebar_widget' => false,
            'show_offers_sidebar_widget' => false,
            'sunstar_travel_programs' => $sunstarTravelPrograms,
        ]);
    }
}