<?php
/**
 * Created by PhpStorm.
 * User: Valentin Wacker
 * Date: 18.08.2017
 * Time: 15:03
 */
namespace AppBundle\Controller;

use AppBundle\AppBundle;
use AppBundle\Entity\FewoBookingRequest;
use AppBundle\Entity\FewoLodging;
use AppBundle\Entity\FewoLodgingGroup;
use AppBundle\Entity\FewoPrice;
use AppBundle\Entity\FewoReservation;
use AppBundle\Entity\FewoSeason;
use AppBundle\Entity\FewoLodgingImage;
use AppBundle\Entity\FewoLodgingGroupImage;
use AppBundle\Form\FewoBookingRequestType;
use AppBundle\Form\FewoLodgingType;
use AppBundle\Form\FewoLodgingTypeGroup;
use AppBundle\Form\FewoPriceType;
use AppBundle\Form\FewoReservationType;
use AppBundle\Form\FewoSeasonType;
use AppBundle\Form\FewoLodgingImageType;
use AppBundle\Form\FewoLodgingGroupImageType;
use AppBundle\Service\FileManager;
use AppBundle\Util;
use Doctrine\Bundle\DoctrineCacheBundle\Tests\Functional\FileSystemCacheTest;
use Doctrine\ORM\EntityManager;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\HttpFoundation\File;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Routing\Annotation\Route;

use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class AdminController extends Controller
{
    public function getEntityManager()
    {
        return $this->getDoctrine()->getManager();
    }

    /**
     * @Route("/login", name="login")
     */
    public function adminAction(Request $request)
    {
        $authUtils = $this->get('security.authentication_utils');
        $error = $authUtils->getLastAuthenticationError();
        $lastUsername = $authUtils->getLastUsername();

        return $this->render('default/admin/loginAdmin.html.twig', [
            'last_username' => $lastUsername,
            'error' => $error,
        ]);

    }

    /**
     * @Route("/admin/fewo")
     */
    public function adminFewoAction()
    {
        return $this->render('admin.html.twig', [

        ]);
    }

    /**
     * @Route("/admin/fewo/lodgings", name="after_login")
     */
    public function adminFewoLodgingsAction(Request $request)
    {

        $fewoLodgingGroupRepo = $this->getEntityManager()->getRepository('AppBundle:FewoLodgingGroup');
        $lodgingGroups = $fewoLodgingGroupRepo->findAll();
    
        return $this->render('default/admin/lodgings.html.twig', [
            'lodgingGroups' => $lodgingGroups,
        ]);
    }

    /**
     * @Route("/admin/fewo/lodgings/new")
     */
    public function adminFewoNewLodgingAction(Request $request)
    {
        $lodging = null;
        if ($request->getMethod() != 'POST')
        {
            $lodging = new FewoLodging();
        }

        $form = $this->createForm(FewoLodgingType::class, $lodging, [

        ]);

        // todo if(form == null)...

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {
            $em = $this->getEntityManager();
            $em->persist($lodging);
            $em->flush();

            return $this->redirect('/admin/fewo/lodgings');
        }
        return $this->render('default/admin/lodgingsNew.html.twig', [
            'form' => $form->createView(),
        ]);
    }


     /**
     * @Route("/admin/fewo/lodgings/group/new")
     */
    public function adminFewoGroupNewLodgingAction(Request $request)
    {
        $lodgingGroup = null;
        if ($request->getMethod() != 'POST')
        {
            $lodgingGroup = new FewoLodgingGroup();
        }

        $form = $this->createForm(FewoLodgingTypeGroup::class, $lodgingGroup, [

        ]);


        // todo if(form == null)...

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {
            $em = $this->getEntityManager();
            $em->persist($lodgingGroup);
            $em->flush();

            return $this->redirect('/admin/fewo/lodgings');
        }
        return $this->render('default/admin/lodgingsGroupNew.html.twig', [
            'form' => $form->createView(),
        ]);
    }

      /**
     * @Route("/admin/fewo/lodging/group/{lodgingGroupId}", requirements={"lodgingGroupId": "\d+"})
     */
    public function adminFewoEditLodgingGroupAction(Request $request, $lodgingGroupId)
    {
        $em = $this->getEntityManager();
        $fewoLodgingGroupRepo = $em->getRepository('AppBundle:FewoLodgingGroup');

        $lodgingGroup = null;


        $lodgingGroup = $fewoLodgingGroupRepo->find($lodgingGroupId);


        $form = $this->createForm(FewoLodgingTypeGroup::class, $lodgingGroup, [
            //options
        ]);

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {
            $em->flush();

            return $this->redirect('/admin/fewo/lodgings');
        }


        return $this->render('default/admin/lodgingGroupEdit.html.twig', [
            'form' => $form->createView(),
            'lodgingGroup' => $lodgingGroup,
        ]);
    }

   

    private function getSeasons(FewoLodging $lodging)
    {
        $seasons = [];
        $lodgingPrices = $lodging->getPrices();
        foreach($lodgingPrices as $price)
        {
            $seasons[] = $price->getSeason();
        }

        return $seasons;
    }

    private function setChoosableSeasons(FewoLodging $lodging)
    {
        $em = $this->getEntityManager();
        $fewoSeasonRepo =  $em->getRepository('AppBundle:FewoSeason');
        $allSeasons = $fewoSeasonRepo->findAll();
        $lodgingSeasons = [];
        $lodgingSeasons = $this->getSeasons($lodging);
        $seasons = null;

        for($i = 0; $i < count($allSeasons); $i++)
        {
            if(!in_array($allSeasons[$i], $lodgingSeasons))
            {
                $seasons[] = $allSeasons[$i];
            }
        }

        $lodging->setChoosableSeasons($seasons);
    }

    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}", requirements={"lodgingId": "\d+"})
     */
    public function adminFewoEditLodgingAction(Request $request, $lodgingId)
    {
        $em = $this->getEntityManager();
        $fewoLodgingRepo = $em->getRepository('AppBundle:FewoLodging');

        $lodging = null;

        $calendarService = $this->container->get('app.lodging_calendar_util');

        $lodging = $fewoLodgingRepo->find($lodgingId);
        $reservations = $calendarService->getReservations($lodging);

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

        $form = $this->createForm(FewoLodgingType::class, $lodging, [
            //options
        ]);

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {
            $em->flush();

            return $this->redirect('/admin/fewo/lodgings');
        }


        return $this->render('default/admin/lodgingsEdit.html.twig', [
            'form' => $form->createView(),
            'lodging' => $lodging,
            'calendar'=> $calendar,
            'reservations' => $reservations
        ]);
    }

    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/delete", requirements={"lodgingId": "\d+"})
     */
    public function adminFewoDeleteLodgingAction(Request $request, $lodgingId)
    {
        $em = $this->getEntityManager();
        $fewoLodgingRepo = $em->getRepository('AppBundle:FewoLodging');

        $lodging = $fewoLodgingRepo->find($lodgingId);

        if($lodging != null)
        {
            $em->remove($lodging);
            $em->flush();
        }

        return $this->redirect('/admin/fewo/lodgings');
    }

     /**
     * @Route("/admin/fewo/lodging/group/{lodgingGroupId}/delete", requirements={"lodgingGroupId": "\d+"})
     */
    public function adminFewoDeleteLodgingGroupAction(Request $request, $lodgingGroupId)
    {
        $em = $this->getEntityManager();
        $fewoLodgingGroupRepo = $em->getRepository('AppBundle:FewoLodgingGroup');

        $lodgingGroup = $fewoLodgingGroupRepo->find($lodgingGroupId);

        if($lodgingGroup != null)
        {
            $em->remove($lodgingGroup);
            $em->flush();
        }

        return $this->redirect('/admin/fewo/lodgings');
    }


    // todo, WEG
    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/program", requirements={"lodgingId": "\d+"})
     */
    public function adminFewoLodgingProgramAction(Request $request, $lodgingId)
    {
        $fewoLodgingRepo = $this->getEntityManager()->getRepository('AppBundle:FewoLodging');

        $lodging = $fewoLodgingRepo->find($lodgingId);

        $calendarService = $this->container->get('app.lodging_calendar_util');

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


        return $this->render('default/pages/cms/fewoTravelProgram.html.twig', [
            'fewo_lodging' => $lodging,
            'calendar' => $calendar
        ]);
    }

    /**
     * @ Route("/admin/fewo/lodgings/{lodgingId}/prices/{priceId}/reservations/new/{fromDate}/booking", requirements={"lodgingId": "\d+", "priceId": "\d+", "fromDate": "\w+"})
     */
    public function adminFewoBookingAction(Request $request, $lodgingId, $priceId, $fromDate)
    {
        $em = $this->getEntityManager();
        $fewoLodgingRepo = $em->getRepository('AppBundle:FewoLodging');
        $fewoPriceRepo = $em->getRepository('AppBundle:FewoPrice');

        $lodging = $fewoLodgingRepo->find($lodgingId);
        $price = $fewoPriceRepo->find($priceId);

        /** @var FewoSeason $season */
        $season = $price->getSeason();
        $minimumStay = $season->getMinimumStay();
        $fromDate = $this->convertDate($fromDate);
        $toDate = '';

        $maxPersons = $lodging->getMaximumPersons();

        $fewoBookingRequest = new FewoBookingRequest();
        $reservation = new FewoReservation();

        if ($request->getMethod() != 'POST')
        {
            $dateAppendix = " + ".($minimumStay - 1)." day";
            if($minimumStay > 1)
            {
                $dateAppendix= $dateAppendix."s";
            }

            $toDate = date('d.m.Y', strtotime($fromDate.$dateAppendix));
            $fewoBookingRequest->setFromDate($fromDate);
            $fewoBookingRequest->setToDate($toDate);
        }

        $form = $this->createForm(FewoBookingRequestType::class, $fewoBookingRequest, [
            'lodging' => $lodging,
            'maxPersons' => $maxPersons,
            'toDate' => $toDate
        ]);

        if ($request->getMethod() == 'POST')
        {
            $form->handleRequest($request);
            $fewoBookingRequest = $form->getData();
            $fromDateTime = new \DateTime($fromDate);
            $fewoBookingRequest->setFromDate($fromDateTime);
            $fewoBookingRequest->setLodging($lodging);
        }


        if ($request->getMethod() == 'POST' && $form->isValid())
        {
            $reservation->setFromDate($fewoBookingRequest->getFromDate());
            $reservation->setToDate($fewoBookingRequest->getToDate());
            $reservation->setStatus(0); // 0 = belegt; 1 = nicht verfügbar
            $reservation->setType(0); // 0 = Buchung; 1 = Händisch

            $reservation->setLodging($lodging);
            $em->persist($reservation);
            $em->flush();


            $crmBookingUrl = $this->get('app.fewo_booking_exporter')->process($fewoBookingRequest, $lodging, $price);//, $travelDate, $bookingPriceInfo);
            $crmBookingUrl = preg_replace('/\\/api/', '', $crmBookingUrl) .'/edit';

            $this->get('mailer')->send(\Swift_Message::newInstance()
                ->setSubject('Ihr FeWo-Buchungsauftrag bei STERN TOURS')
                ->setFrom('stern@stern-tours.de', 'STERN TOURS')
                ->setTo($fewoBookingRequest->getEmail())
                ->setBody(
                    $this->renderView('default/email/fewoBookingConfirmationEmail.txt.twig', [
                        'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
                        'fewo_booking_request' => $fewoBookingRequest,
                        //'booking_price_info' => $bookingPriceInfo,
                        //'travel_date' => $travelDate,
                        //'breadcrumb_entries' => $breadcrumbEntries,
                    ]),
                    'text/plain', 'utf-8'
                )
            );

            $this->get('mailer')->send(\Swift_Message::newInstance()
                ->setSubject('FEWO-BUCHUNG: '. $lodging->getName())//$travelProgram->getTitle() .'('. $travelDate->getName() .')') //TODO !!! allein hierfür braucht man mehr infos in $fewoBookingRequest
                ->setFrom('stern@stern-tours.de', 'STERN TOURS')
                ->setTo('stern@stern-tours.de')
                ->setBody(
                    $this->renderView('default/email/fewoBookingServiceEmail.txt.twig', [
                        'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
                        'crm_url' => $crmBookingUrl,
                        //'travel_program_url' => Util::getBaseUrl() . $travelProgramPage->getUrlPath(),
                        'fewo_booking_request' => $fewoBookingRequest,
                        //'booking_price_info' => $bookingPriceInfo,
                        //'travel_date' => $travelDate,
                        //'breadcrumb_entries' => $breadcrumbEntries,
                    ]),
                    'text/plain', 'utf-8'
                )
            );


            return $this->redirect('/admin/fewo/lodgings/'.$lodgingId.'/program');
        }

        // -------------------------------------------------------------------------------------------


        return $this->render('default/admin/fewoBooking.html.twig', [
            'form' => $form->createView(),
            'lodging' => $lodging,
            'fromDate' => $fromDate,
            'toDate' => $toDate
        ]);

    }

    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/prices/new", requirements={"lodgingId": "\d+"})
     */
    public function adminFewoNewPriceAction(Request $request, $lodgingId)
    {
        $em = $this->getEntityManager();
        $fewoLodgingRepo = $em->getRepository('AppBundle:FewoLodging');
        $lodging = $fewoLodgingRepo->find($lodgingId);

        $price = null;
        if ($request->getMethod() != 'POST')
        {
            $price = new FewoPrice();
        }

        $this->setChoosableSeasons($lodging);
        $form = $this->createForm(FewoPriceType::class, $price, [
            'lodging' => $lodging
        ]);

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {

            if($price == null)
            {
                return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);
            }

            $price->setLodging($lodging);
            $em->persist($price);
            $em->flush();


            return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);
        }

        return $this->render('default/admin/pricesNew.html.twig', [
            'form' => $form->createView(),
            'lodging' => $lodging,
        ]);
    }

    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/prices/{priceId}", requirements={"lodgingId": "\d+", "priceId": "\d+"})
     */
    public function adminFewoEditPriceAction(Request $request, $lodgingId, $priceId)
    {
        $em = $this->getEntityManager();
        $fewoLodgingRepo = $em->getRepository('AppBundle:FewoLodging');
        $fewoPriceRepo = $em->getRepository('AppBundle:FewoPrice');
        $lodging = $fewoLodgingRepo->find($lodgingId);
        $price = $fewoPriceRepo->find($priceId);

        $choosableSeason[] = $price->getSeason();
        $lodging->setChoosableSeasons($choosableSeason);

        $form = $this->createForm(FewoPriceType::class, $price, [
            'lodging' => $lodging
        ]);

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {

            if($price == null)
            {
                return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);
            }
            $em->flush();


            return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);
        }

        return $this->render('default/admin/pricesEdit.html.twig', [
            'form' => $form->createView(),
            'lodging' => $lodging,
        ]);
    }

    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/prices/{priceId}/delete", requirements={"lodgingId": "\d+", "priceId": "\d+"})
     */
    public function adminFewoDeletePriceAction(Request $request, $lodgingId, $priceId)
    {
        $em = $this->getEntityManager();
        $fewoPriceRepo = $em->getRepository('AppBundle:FewoPrice');
        $fewoLodgingRepo = $em->getRepository('AppBundle:FewoLodging');
        $lodging = $fewoLodgingRepo->find($lodgingId);

        $price = $fewoPriceRepo->find($priceId);

        if($price != null)
        {
            $em->remove($price);
            $em->flush();
        }

        return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);
    }


    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/reservations/new", requirements={"lodgingId": "\d+"})
     */
    public function adminFewoNewReservationAction(Request $request, $lodgingId)
    {
        $em = $this->getEntityManager();
        $fewoLodgingRepo = $em->getRepository('AppBundle:FewoLodging');
        $lodging = $fewoLodgingRepo->find($lodgingId);

        $reservation = null;
        if ($request->getMethod() != 'POST')
        {
            $reservation = new FewoReservation();
        }

        $form = $this->createForm(FewoReservationType::class, $reservation, [
            'lodging' => $lodging
        ]);

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {

            if($reservation == null)
            {
                return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);
            }

            $reservation->setLodging($lodging);
            $em->persist($reservation);

            $em->flush();


            return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);
        }

        return $this->render('default/admin/reservationsNew.html.twig', [
            'form' => $form->createView(),
            'lodging' => $lodging,
        ]);

    }

    private function addDaysToDate($date, $days)
    {
        $result = date('dd-mm-yyyy', strtotime($date." + ".$days." days"));
        return $result;
    }

    private function convertDate($date)
    {
        $result = substr($date, 0, 2).'.'.substr($date, 2, 2).'.'.substr($date, 4, 4);
        return $result;
    }


    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/reservations/new/{fromDate}", requirements={"lodgingId": "\d+", "fromDate": "\w+"})
     */
    public function adminFewoNewReservationWithStartingDayAction(Request $request, $lodgingId, $fromDate)
    {
        $em = $this->getEntityManager();
        $fewoLodgingRepo = $em->getRepository('AppBundle:FewoLodging');
        $lodging = $fewoLodgingRepo->find($lodgingId);

        $fromDate = $this->convertDate($fromDate);

        $reservation = null;
        if ($request->getMethod() != 'POST')
        {
            $reservation = new FewoReservation();
        }

        $form = $this->createForm(FewoReservationType::class, $reservation, [
            'lodging' => $lodging,
            'fromDate' => $fromDate
        ]);

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {

            if($reservation == null)
            {
                return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);
            }

            $reservation->setLodging($lodging);
            $em->persist($reservation);
            $em->flush();


            return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);
        }

        return $this->render('default/admin/reservationsNew.html.twig', [
            'form' => $form->createView(),
            'lodging' => $lodging,
        ]);

    }


    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/reservations/{reservationId}", requirements={"lodgingId": "\d+", "reservationId": "\d+"})
     */
    public function adminFewoEditReservationAction(Request $request, $lodgingId, $reservationId)
    {
        $em = $this->getEntityManager();
        $fewoLodgingRepo = $em->getRepository('AppBundle:FewoLodging');
        $fewoReservationRepo = $em->getRepository('AppBundle:FewoReservation');
        $lodging = $fewoLodgingRepo->find($lodgingId);
        $reservation = $fewoReservationRepo->find($reservationId);
        $reservation->setType(1);
        $fromDate = $reservation->getFromDate()->format('d.m.Y');

        $form = $this->createForm(FewoReservationType::class, $reservation, [
            'lodging' => $lodging,
            'fromDate' => $fromDate,
        ]);

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {
            $reservation->setType(1); // 0 = Buchung; 1 = Händisch
            $em->flush();

            return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);
        }

        return $this->render('default/admin/reservationsEdit.html.twig', [
            'form' => $form->createView(),
            'lodging' => $lodging,
            'reservationId' => $reservationId
        ]);

    }

    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/reservations/{reservationId}/delete", requirements={"lodgingId": "\d+", "reservationId": "\d+"})
     */
    public function adminFewoDeleteReservationAction(Request $request, $lodgingId, $reservationId)
    {
        $em = $this->getEntityManager();
        $fewoLodgingRepo = $em->getRepository('AppBundle:FewoLodging');
        $fewoReservationRepo = $em->getRepository('AppBundle:FewoReservation');

        $lodging = $fewoLodgingRepo->find($lodgingId);
        $reservation = $fewoReservationRepo->find($reservationId);

        if($reservation != null)
        {
            $em->remove($reservation);
            $em->flush();
        }

        return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);

    }


    /**
     * @Route("/admin/fewo/seasons")
     */
    public function adminFewoSeasonsAction(Request $request)
    {
        $fewoSeasonRepo = $this->getEntityManager()->getRepository('AppBundle:FewoSeason');

        $seasons = $fewoSeasonRepo->findAll();

        return $this->render('default/admin/seasons.html.twig', [
            'seasons' => $seasons,
        ]);

    }

    /**
     * @Route("/admin/fewo/seasons/new")
     */
    public function adminFewoNewSeasonAction(Request $request)
    {
        $em = $this->getEntityManager();
        $season = null;

        if ($request->getMethod() != 'POST')
        {
            $season = new FewoSeason();
        }

        $form = $this->createForm(FewoSeasonType::class, $season, [

        ]);

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {
            if($season == null)
            {
                return $this->redirect('/admin/fewo/seasons');
            }

            $em->persist($season);
            $em->flush();

            return $this->redirect('/admin/fewo/seasons');
        }
        return $this->render('default/admin/seasonsNew.html.twig', [
            'form' => $form->createView(),
            'season' => $season,
        ]);

    }

    /**
     * @Route("/admin/fewo/seasons/{seasonId}", requirements={"seasonId": "\d+"})
     */
    public function adminFewoEditSeasonAction(Request $request, $seasonId)
    {
        $em = $this->getEntityManager();
        $fewoSeasonsRepo = $em->getRepository('AppBundle:FewoSeason');

        $season = null;
        $season = $fewoSeasonsRepo->find($seasonId);

        $form = $this->createForm(FewoSeasonType::class, $season, [
            //options
        ]);

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {
            $em->flush();

            return $this->redirect('/admin/fewo/seasons');
        }
        return $this->render('default/admin/seasonsEdit.html.twig', [
            'form' => $form->createView(),
            'season' => $season,
        ]);
    }

    /**
     * @Route("/admin/fewo/seasons/{seasonId}/delete", requirements={"seasonId": "\d+"})
     */
    public function adminFewoDeleteSeasonAction(Request $request, $seasonId)
    {
        $em = $this->getEntityManager();
        $fewoSeasonRepo = $em->getRepository('AppBundle:FewoSeason');

        $season = $fewoSeasonRepo->find($seasonId);

        if($season != null)
        {
            $em->remove($season);
            $em->flush();
        }

        return $this->redirect('/admin/fewo/seasons');
    }
    /* ---- FILES LODGING ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- */
    /* ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- */

    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/images/multi-upload", requirements={"lodgingId": "\d+"})
     */
    public function adminFewoImageMultiUploadAction(Request $request, $lodgingId)
    {
        $em = $this->getEntityManager();
        $lodging = $em->getRepository('AppBundle:FewoLodging')->find($lodgingId);
        if (!$lodging)
        {
            throw new HttpException(404, 'Unbekannte lodging-ID: '. $lodgingId);
        }

        $form = $this->createForm(FileType::class, null, [
            'multiple' => true
        ]);
        if ($request->getMethod() == 'POST')
        {
            $form->handleRequest($request);
            if ($form->isValid())
            {
                $uploader = $this->container->get('app.image_uploader');
                foreach ($form->getData() as $uploadedFile)
                {

                    $image = new FewoLodgingImage();
                    $image->setFile($uploadedFile);
                    $image->setLodging($lodging);
                    $image->setPos(0);
                    $image->setFileName('');
                    $image->setDescription('');
                    $em->persist($image);
                    $em->flush();
                }
                return $this->redirect('/admin/fewo/lodgings/'. $lodging->getId());
            }
        }

        return $this->render('default/admin/fewoImageMultiUpload.html.twig', [
            'form' => $form->createView(),
            'lodging' => $lodging,
        ]);
    }

    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/images/new", requirements={"lodgingId": "\d+"})
     */
    public function adminFewoNewImageAction(Request $request, $lodgingId)
    {
        $lodging = $this->getEntityManager()->getRepository('AppBundle:FewoLodging')->find($lodgingId);
        if (!$lodging)
        {
            throw new HttpException(404, 'Unbekannte lodging-ID: '. $lodgingId);
        }
        return $this->processImageForm($request, null, $lodging);
    }

    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/images/{imageId}", requirements={"lodgingId": "\d+", "imageId": "\d+"})
     */
    public function adminFewoEditImageAction(Request $request, $lodgingId, $imageId)
    {
        /** @var FewoLodgingImage $image */
        $image = $this->getEntityManager()->getRepository('AppBundle:FewoLodgingImage')->find($imageId);
        if (!$image || $image->getLodging()->getId() != $lodgingId)
        {
            throw new HttpException(404, 'Unbekannte FewoLodgingImage-ID oder lodging-ID passt nicht: '.
                $imageId .' / '. $lodgingId);
        }
        return $this->processImageForm($request, $image);
    }

    /**
     * @param Request $request
     * @param FewoLodgingImage $image
     * @param FewoLodging|null $lodging
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function processImageForm(Request $request, $image, $lodging = null)
    {
        $em = $this->getEntityManager();

        if ($image == null)
        {
            $isNew = true;
        }
        else
        {
            $isNew = false;
            $lodging = $image->getLodging();
            $imageFileName = $image->getFile();
        }

        if ($request->getMethod() != 'POST' && $image == null)
        {
            $image = new FewoLodgingImage();
            $image->setPos(0);
        }

        $form = $this->createForm(FewoLodgingImageType::class, $image);

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {
            $image = $form->getData();
            if ($isNew)
            {
                $image->setLodging($lodging);
            }
            else
            {
                $image->setFile($imageFileName);
            }
            $em->persist($image);
            $em->flush();

            return $this->redirect('/admin/fewo/lodgings/'. ($lodging->getId()));
        }

        return $this->render('default/admin/fewoImage.html.twig', [
            'form' => $form->createView(),
            'lodging' => $lodging,
            'is_new' => $isNew,
            'image_file_name' => $isNew ? null : $imageFileName,
            'image' => $image,
        ]);
    }

    /**
     * @Route("/admin/fewo/lodgings/{lodgingId}/images/{imageId}/delete", requirements={"lodgingId": "\d+", "imageId": "\d+"})
     */
    public function adminFewoDeleteImageAction(Request $request, $lodgingId, $imageId)
    {
        $em = $this->getEntityManager();
        $fewoLodgingImageRepo = $em->getRepository('AppBundle:FewoLodgingImage');

        $image = $fewoLodgingImageRepo->find($imageId);

        if($image != null)
        {
            $em->remove($image);
            $em->flush();
        }

        return $this->redirect('/admin/fewo/lodgings/'.$lodgingId);
    }

     /* ---- FILES GROUP ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- */
     /* ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- */

    /**
     * @Route("/admin/fewo/lodgings/group/{comp}/{lodgingGroupId}/images/multi-upload", requirements={"comp": "pre|post", "lodgingGroupId": "\d+"})
     */
    public function adminFewoGroupImageMultiUploadAction(Request $request, $comp, $lodgingGroupId)
    {
        $em = $this->getEntityManager();
        $lodgingGroup = $em->getRepository('AppBundle:FewoLodgingGroup')->find($lodgingGroupId);
        if (!$lodgingGroup)
        {
            throw new HttpException(404, 'Unbekannte lodgingGroup-ID: '. $lodgingGroupId);
        }

        $form = $this->createForm(FileType::class, null, [
            'multiple' => true
        ]);

        if ($request->getMethod() == 'POST')
        {
         
            $form->handleRequest($request);
            if ($form->isValid())
            {
                $uploader = $this->container->get('app.image_uploader');
                foreach ($form->getData() as $uploadedFile)
                {

                    $image = new FewoLodgingGroupImage();
                    $image->setFile($uploadedFile);
                    $image->setLodgingGroup($lodgingGroup);
                    $image->setComp($comp);
                    $image->setPos(0);
                    $image->setFileName('');
                    $image->setDescription('');
                    $em->persist($image);
                    $em->flush();
                }
                return $this->redirect('/admin/fewo/lodging/group/'. $lodgingGroup->getId());
            }
        }

        return $this->render('default/admin/fewoGroupImageMultiUpload.html.twig', [
            'form' => $form->createView(),
            'lodgingGroup' => $lodgingGroup,
            'comp' => $comp,
        ]);
        
    }

    /**
     * @Route("/admin/fewo/lodgings/group/{comp}/{lodgingGroupId}/images/new", requirements={"comp": "pre|post", "lodgingGroupId": "\d+"})
     */
    public function adminFewoGroupNewImageAction(Request $request, $comp, $lodgingGroupId)
    {
        $lodgingGroup = $this->getEntityManager()->getRepository('AppBundle:FewoLodgingGroup')->find($lodgingGroupId);
        if (!$lodgingGroup)
        {
            throw new HttpException(404, 'Unbekannte lodgingGroup-ID: '. $lodgingGroupId);
        }
        return $this->processGroupImageForm($request, null, $comp, $lodgingGroup);
        
    }

    /**
     * @Route("/admin/fewo/lodgings/group/{lodgingGroupId}/images/{imageId}", requirements={"lodgingGroupId": "\d+", "imageId": "\d+"})
     */
    public function adminFewoGroupEditImageAction(Request $request, $lodgingGroupId, $imageId)
    {

        /** @var FewoLodgingGroupImage $image */
        $image = $this->getEntityManager()->getRepository('AppBundle:FewoLodgingGroupImage')->find($imageId);
        if (!$image || $image->getLodgingGroup()->getId() != $lodgingGroupId)
        {
            throw new HttpException(404, 'Unbekannte FewoLodgingGroupImage-ID oder lodgingGroup-ID passt nicht: '.
                $imageId .' / '. $lodgingGroupId);
        }
        return $this->processGroupImageForm($request, $image);
    }

    /**
     * @param Request $request
     * @param FewoLodgingGroupImage $image
     * @param FewoLodgingGroup|null $lodgingGroup
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function processGroupImageForm(Request $request, $image, $comp = null, $lodgingGroup = null)
    {
        $em = $this->getEntityManager();

        if ($image == null)
        {
            $isNew = true;
        }
        else
        {
            $isNew = false;
            $lodgingGroup = $image->getLodgingGroup();
            $imageFileName = $image->getFile();
        }

        if ($request->getMethod() != 'POST' && $image == null)
        {
            $image = new FewoLodgingGroupImage();
            $image->setComp($comp);
            $image->setPos(0);
        }

        $form = $this->createForm(FewoLodgingGroupImageType::class, $image);

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


        if ($request->getMethod() == 'POST' && $form->isValid())
        {
            $image = $form->getData();
            if ($isNew)
            {
                $image->setLodgingGroup($lodgingGroup);
                $image->setComp($comp);
            }
            else
            {
                $image->setFile($imageFileName);
            }
            $em->persist($image);
            $em->flush();

            return $this->redirect('/admin/fewo/lodging/group/'. ($lodgingGroup->getId()));
        }

        return $this->render('default/admin/fewoGroupImage.html.twig', [
            'form' => $form->createView(),
            'lodgingGroup' => $lodgingGroup,
            'is_new' => $isNew,
            'image_file_name' => $isNew ? null : $imageFileName,
            'image' => $image,
        ]);
    }

    /**
     * @Route("/admin/fewo/lodgings/group/{lodgingGroupId}/images/{imageId}/delete", requirements={"lodgingGroupId": "\d+", "imageId": "\d+"})
     */
    public function adminFewoGroupDeleteImageAction(Request $request, $lodgingGroupId, $imageId)
    {
        $em = $this->getEntityManager();
        $fewoLodgingGroupImageRepo = $em->getRepository('AppBundle:FewoLodgingGroupImage');

        $image = $fewoLodgingGroupImageRepo->find($imageId);

        if($image != null)
        {
            $em->remove($image);
            $em->flush();
        }

        return $this->redirect('/admin/fewo/lodging/group/'.$lodgingGroupId);
    }

}