<?php
/**
 * @author Ulrich Hecht <ulrich.hecht@hecht-software.de>
 * @date 12/08/2016
 */

namespace AppBundle\Controller;


use AppBundle\Entity\BookingRequest;
use AppBundle\Entity\BreadcrumbEntry;
use AppBundle\Entity\Page;
use AppBundle\Entity\TravelDate;
use AppBundle\Entity\Traveler;
use AppBundle\Entity\TravelPeriodPrice;
use AppBundle\Entity\TravelPeriodPriceType;
use AppBundle\Form\BookingRequestType;
use AppBundle\Util;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class BookingController extends Controller
{
    /** @var TravelPeriodPriceType[] $priceTypeById */
    private $priceTypeById;

    /**
     * The routing for this action is entirely controlled by KernelControllerListener!
     *
     * @param Page $travelProgramPage
     * @param Request $request
     * @param $action
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */

    private function getErrorMessages(\Symfony\Component\Form\Form $form) {
        $errors = array();

        foreach ($form->getErrors() as $key => $error) {
            if ($form->isRoot()) {
                $errors['#'][] = $error->getMessage();
            } else {
                $errors[] = $error->getMessage();
            }
        }

        foreach ($form->all() as $child) {
            if (!$child->isValid()) {
                $errors[$child->getName()] = $this->getErrorMessages($child);
            }
        }

        return $errors;
    }

    public function indexAction(Page $travelProgramPage, $action, Request $request)
    {
        $travelProgram = $travelProgramPage->getTravelProgram();
        if (!$request->query->has('nr'))
        {
            return $this->redirect($travelProgramPage->getUrlPath());
        }
        $this->getDoctrine()->getRepository('AppBundle:TravelPeriod')->getTrueTravelPeriods($travelProgram);

        $this->priceTypeById = $this->getDoctrine()->getRepository('AppBundle:TravelPeriodPriceType')->findAllIndexedById();

        // #TODO Consider changing key of travel dates
        foreach ($travelProgram->getTravelDates() as $curTravelDate)
        {
            if ($curTravelDate->getName() == $request->query->get('nr'))
            {
                $travelDate = $curTravelDate;
                break;
            }
        }
        if (!isset($travelDate))
        {
            throw $this->createNotFoundException();
        }

        /** @var BookingRequest $bookingRequest */
        $bookingRequest = new BookingRequest();
        if ($request->getMethod() != 'POST')
        {
            $bookingRequest->setRoomCount(0);
        }
        $form = $this->createForm(BookingRequestType::class, $bookingRequest, [
            'travel_date' => $travelDate,
            'travel_program' => $travelProgram
        ]);
        if ($request->getMethod() == 'POST')
        {
            $form->handleRequest($request);
            $bookingRequest = $form->getData();
        }
        $htmlSummary = [];
        $bookingPriceInfo = [];
        $totalPrice = $this->calculatePrice($travelDate, $bookingRequest, $travelProgram->getCategory()->getId(), $htmlSummary, $bookingPriceInfo);

        if ($action == '/buchen')
        {
            $breadcrumbEntries = Util::createBreadcrumb($travelProgramPage);
            $breadcrumbEntries[] = new BreadcrumbEntry('Buchen');

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

                $errors = array();
                foreach ($form as $fieldName => $formField) {
                    foreach ($formField->getErrors(true) as $error) {
                        $errors[$fieldName] = $error->getMessage();
                    }
                }


                $booking = $this->getDoctrine()->getRepository('AppBundle:TravelBooking')->createFromBookingRequest(
                    $bookingRequest, $travelDate, $bookingPriceInfo);

                $em = $this->getDoctrine()->getManager();
                $em->persist($booking);
                $em->flush();

                
                $crmBookingUrl = $this->get('app.booking_exporter')->process($bookingRequest, $travelDate, $bookingPriceInfo);
                
                if (!$crmBookingUrl)
                {
                    $crmBookingUrl = '[CRM-EXPORT FEHLGESCHLAGEN]';
                }
                else
                {
                    $crmBookingUrl = preg_replace('/\\/api/', '', $crmBookingUrl).'/edit';
                }

                $this->get('mailer')->send(\Swift_Message::newInstance()
                    ->setSubject('Ihr Buchungsauftrag bei STERN TOURS')
                    ->setFrom('stern@stern-tours.de', 'STERN TOURS')
                    ->setTo($bookingRequest->getEmail()) //
                    ->setBody(
                        $this->renderView('default/email/bookingConfirmationEmail.txt.twig', [
                            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
                            'booking_request' => $bookingRequest,
                            'booking_price_info' => $bookingPriceInfo,
                            'travel_date' => $travelDate,
                            'breadcrumb_entries' => $breadcrumbEntries,
                            'summary' => $htmlSummary,

                        ]),
                        'text/plain', 'utf-8'
                    )
                );

                $this->get('mailer')->send(\Swift_Message::newInstance()
                    ->setSubject('BUCHUNG: '. $travelProgram->getTitle() .'('. $travelDate->getName() .')')
                    ->setFrom('stern@stern-tours.de', 'STERN TOURS')
                    ->setTo("stern@stern-tours.de")
                    ->setBody(
                        $this->renderView('default/email/bookingServiceEmail.txt.twig', [
                            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
                            'crm_url' => $crmBookingUrl,
                            'travel_program_url' => Util::getBaseUrl() . $travelProgramPage->getUrlPath(),
                            'booking_request' => $bookingRequest,
                            'booking_price_info' => $bookingPriceInfo,
                            'travel_date' => $travelDate,
                            'breadcrumb_entries' => $breadcrumbEntries,
                            'summary' => $htmlSummary,

                        ]),
                        'text/plain', 'utf-8'
                    )
                );

                // #TODO This will lead to multiple bookings due to multiple form submission. Redirect instead!
                return $this->render('default/pages/bookingConfirmation.html.twig', [
                    'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
                    'page' => $travelProgramPage,
                    'breadcrumb_entries' => $breadcrumbEntries,
                    'show_nav_sidebar_widget' => false,
                    'show_travel_guide_sidebar_widget' => false,
                    'show_travel_magazine_sidebar_widget' => false,
                    'show_offers_sidebar_widget' => false,
                    'show_search_sidebar_widget' => false,
                    'show_feedbacks_sidebar_widget' => false,
                    'show_seal_of_approval' => true,
                    'booking' => $booking,
                    'travel_program' => $travelProgram,
                    'summary' => $htmlSummary,
                    'total_price' => $totalPrice,
                    'booking_price_info' => $bookingPriceInfo,

                ]);
            }
        /*     $string = (string) $form->getErrors(true, true);
            var_dump($string);
            var_dump( $form->isValid());
            var_dump($this->getErrorMessages($form));

            die();
*/
            return $this->render('default/pages/booking.html.twig', [
                'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
                'page' => $travelProgramPage,
                'breadcrumb_entries' => $breadcrumbEntries,
                'show_nav_sidebar_widget' => false,
                'show_travel_guide_sidebar_widget' => false,
                'show_travel_magazine_sidebar_widget' => false,
                'show_offers_sidebar_widget' => false,
                'show_search_sidebar_widget' => false,
                'show_feedbacks_sidebar_widget' => false,
                'show_seal_of_approval' => true,
                'travel_program' => $travelProgram,
                'travel_date' => $travelDate,
                'form' => $form->createView(),
                'price_type_by_id' => $this->priceTypeById,
                'summary' => $htmlSummary,
                'total_price' => $totalPrice,
                'booking_price_info' => $bookingPriceInfo,
                'mediator_terms_filename' => $travelProgram->getIsMediated()
                    ? $this->getDoctrine()->getRepository('AppBundle:TravelOrganizer')->find(1)->getFileName()
                    : null
            ]);
        }

        elseif ($action == '/berechne-gesamtpreis')
        {
            return $this->render('default/components/booking/summary.html.twig', [
                'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
                'summary' => $htmlSummary,
                'total_price' => $totalPrice,
                'booking_price_info' => $bookingPriceInfo,
                'show_detail' => true,

            ]);
        }
        throw new \Exception('Unknow BookingController action: '. $action);
    }

    private function calcNumTravelerLabel($number)
    {
        $ret = 0;
        if($number > 0)
            $ret = 1;

        return $ret;
    }

    public function calculatePrice(TravelDate $travelDate, BookingRequest $bookingRequest, $categoryId, &$outHtmlSummary = null, &$outPriceInfo = null)
    {
        $ret = 0;
        $insuranceAssessmentBasis = 0;
        $insuranceAssessmentChildBasis = 0;

        $travelerCount = $bookingRequest->getTravelerCount();

        $singleRoomCount = $bookingRequest->getSingleRoomCount();
        $doubleRoomCount = $bookingRequest->getDoubleRoomCount();
        $tripleRoomCount = $bookingRequest->getTripleRoomCount();

        $singleRoomChildCount = $bookingRequest->getSingleRoomChildCount();
        $doubleRoomChildCount = $bookingRequest->getDoubleRoomChildCount();
        $tripleRoomChildCount = $bookingRequest->getTripleRoomChildCount();

        $childrenCount = $bookingRequest->getChildrenCount();

        if (isset($outHtmlSummary))
        {
            $insuranceHtmlSummary = [];
        }

        if (isset($outPriceInfo))
        {
            $outPriceInfo['rooms'] = [];
            $outPriceInfo['insurances'] = [];
            $outPriceInfo['insurancesOut'] = [];
            $outPriceInfo['options'] = [];
            $outPriceInfo['classOptions'] = [];
            $outPriceInfo['departure'] = 0;
            $outPriceInfo['departure_extra'] = 0;
            $outPriceInfo['flight_price'] = 0;
            $outPriceInfo['final_payment_date'] = $travelDate->getFinalPaymentDate();
            $outPriceInfo['final_payment_date_str'] = $travelDate->getFinalPaymentDateStr();
            $outPriceInfo['discount'] = [];
        }

        $tempDepartureHTML = array();
        //ABFLUG
        if($bookingRequest->getDeparture() != null)
        {
            $departure = Util\DepartureUtil::limitIndividualArrivalPrice($bookingRequest->getDeparture(),
                $travelDate->getFlightPrice());
            if (isset($outPriceInfo))
            {
                $outPriceInfo['departure'] = $departure;
            }

            if ($departure->getExtraCharge() != 0)
            {
                $insuranceAssessmentBasis += $departure->getExtraCharge();
                $insuranceAssessmentChildBasis += $departure->getExtraCharge();
                $a = ($travelerCount + $childrenCount) * $departure->getExtraCharge();
                $ret += $a;
                $outPriceInfo['departure_extra'] += $a;

                if (isset($outHtmlSummary))
                {
                    $key = $departure->getExtraCharge();
                    if(!empty($tempDepartureHTML[$key])) {
                        $tempDepartureHTML[$key]['count'] = $tempDepartureHTML[$key]['count'] +  ($travelerCount + $childrenCount);
                        $tempDepartureHTML[$key]['value'] = $tempDepartureHTML[$key]['value'] + $a;
                    }else{
                        $tempDepartureHTML[$key] = array(
                            'value' => $a,
                            'label_first' => ($departure->getExtraCharge() > 0 ? 'Aufschlag' : 'Abzug') . ' für Abfahrts-/Abflugort "'. $departure->getName(),
                            'label_last' =>   Util::formatPrice($departure->getExtraCharge()) . ' pro Person',
                            'count' =>  ($travelerCount + $childrenCount),
                        );
                    }
                }
            }
        }

        //OPTIONEN
        $tempOptionHTML = array();
        foreach ($bookingRequest->getTravelOptions() as $travelOption)
        {
            $insuranceAssessmentBasis += $travelOption->getPrice();
            $insuranceAssessmentChildBasis += $travelOption->getPriceChildren();
            $a = $travelerCount * $travelOption->getPrice();
            $a += $childrenCount * $travelOption->getPriceChildren();
            $ret += $a;
            //OPTIONS
            if (isset($outHtmlSummary))
            {
                $key = $travelOption->getId();
                if(!empty($tempOptionHTML[$key])) {
                   // $tempOptionHTML[$key]['count'] = $tempOptionHTML[$key]['count'] + $travelerCount;
                    $tempOptionHTML[$key]['value'] = $tempOptionHTML[$key]['value'] + $a;
                }else{
                    $tempOptionHTML[$key] = array(
                        'value' => $a,
                        'label_first' => $travelOption->getName(),
                        'label_last' => Util::formatPrice($travelOption->getPrice()) . ' pro Person',
                        'count' => $travelerCount + $childrenCount,
                        'childCount' => $childrenCount,
                        'price_child' => Util::formatPrice($travelOption->getPriceChildren()) . ' pro Kind',
                    );
                }
            }
            if (isset($outPriceInfo))
            {
                $outPriceInfo['options'][] = $travelOption;
            }
        }

        $persons = [
            'total' => $travelerCount,
            'adults' => $travelerCount,
            'singleRoomPersons' => $singleRoomCount,
            'singleRoomChildPersons' => $singleRoomChildCount,
            'doubleRoomPersons' => $doubleRoomCount * 2,
            'doubleRoomChildPersons' => $doubleRoomChildCount * 2,
            'tripleRoomPersons' => $tripleRoomCount * 3,
            'tripleRoomChildPersons' => $tripleRoomChildCount * 3,
            'children' => 0 //TODO
        ];

        //Komfort
        $possibleRooms = $this->getRooms($travelDate->getPrices(), $persons);
        $tempComfortHTML = array();
        if ($bookingRequest->getComfort())
        {
            foreach ($possibleRooms as $room)
            {
                $insuranceAssessmentBasis += $room['price']->getEffectiveComfortPrice();
                $insuranceAssessmentChildBasis += $room['price']->getEffectiveComfortPrice();
                $a = $room['persons']['total'] * $room['price']->getEffectiveComfortPrice();
                $ret += $a;
                if (isset($outHtmlSummary))
                {
                    $key = intval($room['price']->getEffectiveComfortPrice());
                    if(!empty($tempComfortHTML[$key])) {
                        $tempComfortHTML[$key]['count'] = $tempComfortHTML[$key]['count'] + 1;
                        $tempComfortHTML[$key]['value'] = $tempComfortHTML[$key]['value'] + $a;
                    }else{
                        $tempComfortHTML[$key] = array(
                            'value' => $a,
                            'label_first' => 'Komfort-Kategorie',
                            'label_last' =>  Util::formatPrice($room['price']->getEffectiveComfortPrice()) . ' pro Person',
                            'count' => 1,
                        );
                    }
                }
                if (isset($outPriceInfo))
                {
                    $outPriceInfo['classOptions'][] = [
                        'count' => $room['persons']['total'],
                        'name' => 'zugebuchte Leistung: Komfort (4 Sterne)',
                        'price' => $room['price']->getEffectiveComfortPrice()
                    ];
                }
            }
        }

        $insuranceTotal = 0;
        $tempInsuranceHTML = array();
        $tempRoomHTML = array();
        $tempDiscountHTML = array();
        //ROOMS DISCOUNT Versicherungen
        foreach ($possibleRooms as $room)
        {
            $adultCount = $room['persons']['adults'];
            $childrenCount = $room['persons']['children'];

            $singleFullPrice = $room['price']->getEffectivePrice();
            $childPrice = $room['price']->getEffectiveChildPrice();

            $roomPrice = ($singleFullPrice * $adultCount) + ($childPrice * $room['persons']['children']);

            $singleDiscountPrice = $room['price']->getEffectiveDiscountPrice();
            $singleChildDiscountPrice = $room['price']->getEffectiveChildDiscountPrice();
            $discount = ($singleDiscountPrice === null) ? 0 : ($adultCount * ($singleDiscountPrice - $singleFullPrice));
            $childDiscount = ($singleChildDiscountPrice === null) ? 0 : ($childrenCount * ($singleChildDiscountPrice - $childPrice));
            $ret += $roomPrice + $discount + $childDiscount;

            $singel_flight_price = $travelDate->getFlightCalcPrice();
            $outPriceInfo['flight_price'] +=  (($singel_flight_price * $adultCount) + ($singel_flight_price * $room['persons']['children']));

            //Room price
            if (isset($outPriceInfo))
            {
                $price = $singleDiscountPrice ?? $singleFullPrice;
                $price += $singleChildDiscountPrice ?? $childPrice;

                $outPriceInfo['rooms'][] = [
                    'name' => $room['priceType']->getName(),
                    'adults' => $adultCount,
                    'children' => $childrenCount,
                    'price' => $singleDiscountPrice ?? $singleFullPrice,
                    'price_children' =>  $singleChildDiscountPrice ?? $childPrice,
                    'price_total' => $roomPrice + $discount + $childDiscount,
                ];
            }


            //Room html
            if (isset($outHtmlSummary))
            {
                //ROOMS
                $key = $room['priceType']->getId();
                if(!empty($tempRoomHTML[$key])) {
                    $tempRoomHTML[$key]['count'] = $tempRoomHTML[$key]['count'] + 1;
                    $tempRoomHTML[$key]['value'] = $tempRoomHTML[$key]['value'] + $roomPrice;
                }else{
                    $tempRoomHTML[$key] = array(
                        'value' => $roomPrice,
                        'label_first' => $room['priceType']->getName(),
                        'label_last' => Util::formatPrice($singleFullPrice) . ' pro Person',
                        'count' => 1,
                        'childCount' => $room['persons']['children'],
                        'price_child' => Util::formatPrice($room['price']->getEffectiveChildPrice()),
                    );
                }
                //DISCOUNT
                if ($singleDiscountPrice !== null)
                {
                    $key = intval(($singleFullPrice - $singleDiscountPrice)*100);
                    if(!empty($tempDiscountHTML[$key])) {
                        $tempDiscountHTML[$key]['count'] = $tempDiscountHTML[$key]['count'] + $adultCount;
                        $tempDiscountHTML[$key]['value'] = $tempDiscountHTML[$key]['value'] + $discount;
                    }else{
                        $tempDiscountHTML[$key] = array(
                            'value' => $discount,
                            'label_first' => 'Rabatt',
                            'label_last' => Util::formatPrice($singleFullPrice - $singleDiscountPrice) . ' pro Person',
                            'count' => $adultCount,
                        );
                    }
                    if($childDiscount > 0){
                        $key =  intval(($childPrice - $singleChildDiscountPrice)*100);
                        if(!empty($tempDiscountHTML[$key])) {
                            $tempDiscountHTML[$key]['count'] = $tempDiscountHTML[$key]['count'] + $childrenCount;
                            $tempDiscountHTML[$key]['value'] = $tempDiscountHTML[$key]['value'] + $childDiscount;
                        }else{
                            $tempDiscountHTML[$key] = array(
                                'value' => $childDiscount,
                                'label_first' => 'Rabatt',
                                'label_last' => Util::formatPrice($childPrice - $singleChildDiscountPrice) . ' pro Person',
                                'count' => $childrenCount,
                            );
                        }
                    }
                    if (isset($outPriceInfo))
                    {
                        $key = intval(($singleFullPrice - $singleDiscountPrice)*100);
                        if(!empty($outPriceInfo['discount'][$key])) {
                            $outPriceInfo['discount'][$key]['count'] = $outPriceInfo['discount'][$key]['count'] + $adultCount;
                            $outPriceInfo['discount'][$key]['value'] = $outPriceInfo['discount'][$key]['value'] + $discount;
                        }else{
                            $outPriceInfo['discount'][$key] = array(
                                'value' => $discount,
                                'label_first' => 'Rabatt',
                                'label_last' => Util::formatPrice($singleFullPrice - $singleDiscountPrice) . ' pro Person',
                                'count' => $adultCount,
                            );
                        }
                        if($childDiscount > 0){
                            $key =  intval(($childPrice - $singleChildDiscountPrice)*100);
                            if(!empty($outPriceInfo['discount'][$key])) {
                                $outPriceInfo['discount'][$key]['count'] = $outPriceInfo['discount'][$key]['count'] + $childrenCount;
                                $outPriceInfo['discount'][$key]['value'] = $outPriceInfo['discount'][$key]['value'] + $childDiscount;
                            }else{
                                $outPriceInfo['discount'][$key] = array(
                                    'value' => $childDiscount,
                                    'label_first' => 'Rabatt',
                                    'label_last' => Util::formatPrice($childPrice - $singleChildDiscountPrice) . ' pro Person',
                                    'count' => $childrenCount,
                                );
                            }
                        }
                    }

                }

                //Versicherung price + html
                if ($bookingRequest->getInsurance() && $adultCount > 0)
                {
                    $curAssessmentBasis = $insuranceAssessmentBasis + ($singleDiscountPrice ?? $singleFullPrice);
                    $curAssessmentChildBasis = $insuranceAssessmentChildBasis + ($singleChildDiscountPrice ?? $childPrice);
                    $insurancePrice = $this->getDoctrine()->getRepository('AppBundle:TravelInsurancePrice')
                        ->findOneByInsuranceIdAndAssessmentBasis($bookingRequest->getInsurance()->getId(), $curAssessmentBasis);
                    $insuranceChildPrice = $this->getDoctrine()->getRepository('AppBundle:TravelInsurancePrice')
                        ->findOneByInsuranceIdAndAssessmentBasis($bookingRequest->getInsurance()->getId(), $curAssessmentChildBasis);
                    $insurancePriceValue = $insurancePrice->getPrice() > 0 ? $insurancePrice->getPrice() : round($insurancePrice->getPercent() * $curAssessmentBasis / 100, 2);
                    $insuranceChildPriceValue = $insuranceChildPrice->getPrice() > 0 ? $insuranceChildPrice->getPrice() : round($insuranceChildPrice->getPercent() * $curAssessmentChildBasis / 100, 2);


                    $a = $adultCount * $insurancePriceValue;
                    $b = $childrenCount * $insuranceChildPriceValue;
                    $insuranceTotal += $a + $b;
                    $ret += $a + $b;

                    if (isset($insuranceHtmlSummary))
                    {
                        if(!empty($tempInsuranceHTML[$insurancePriceValue])){
                            $tempInsuranceHTML[$insurancePriceValue]['count'] = intval($tempInsuranceHTML[$insurancePriceValue]['count']) + $adultCount;
                            $tempInsuranceHTML[$insurancePriceValue]['value'] = $tempInsuranceHTML[$insurancePriceValue]['value'] + $a;
                        }else{
                            $tempInsuranceHTML[$insurancePriceValue] = array(
                                'value' => $a,
                                'label_first' => 'RV '. $bookingRequest->getInsurance()->getName() .' ('. $insurancePrice->getCode() .') ',
                                'label_last' => Util::formatPrice($insurancePriceValue) . ' pro Person',
                                'count' => $adultCount,

                            );
                        }
                        if($b > 0){
                            if(!empty($tempInsuranceHTML[$insuranceChildPriceValue])){
                                $tempInsuranceHTML[$insuranceChildPriceValue]['count'] = intval($tempInsuranceHTML[$insuranceChildPriceValue]['count']) + $childrenCount;
                                $tempInsuranceHTML[$insuranceChildPriceValue]['value'] = $tempInsuranceHTML[$insuranceChildPriceValue]['value'] + $b;
                            }else{
                                $tempInsuranceHTML[$insuranceChildPriceValue] = array(
                                    'value' => $b,
                                    'label_first' => 'RV '. $bookingRequest->getInsurance()->getName() .' ('. $insuranceChildPrice->getCode() .') ',
                                    'label_last' => Util::formatPrice($insuranceChildPriceValue) . ' pro Kind',
                                    'count' => $childrenCount,

                                );
                            }
                        }
                    }
                    if (isset($outPriceInfo))
                    {
                        if(!empty($outPriceInfo['insurancesOut'][$insurancePriceValue])){
                            $outPriceInfo['insurancesOut'][$insurancePriceValue]['count'] = intval($outPriceInfo['insurancesOut'][$insurancePriceValue]['count']) + $childrenCount;
                            $outPriceInfo['insurancesOut'][$insurancePriceValue]['value'] = $outPriceInfo['insurancesOut'][$insurancePriceValue]['value'] + $b;
                        }else{
                            $outPriceInfo['insurancesOut'][$insurancePriceValue] = [
                                'value' => $a,
                                'label_first' => 'RV '. $bookingRequest->getInsurance()->getName() .' ('. $insurancePrice->getCode() .') ',
                                'label_last' => Util::formatPrice($insurancePriceValue) . ' pro Person',
                                'count' => $adultCount,
                            ];
                        }
                        if($b > 0){
                            if(!empty($outPriceInfo['insurancesOut'][$insuranceChildPriceValue])){
                                $outPriceInfo['insurancesOut'][$insuranceChildPriceValue]['count'] = intval($outPriceInfo['insurancesOut'][$insuranceChildPriceValue]['count']) + $childrenCount;
                                $outPriceInfo['insurancesOut'][$insuranceChildPriceValue]['value'] = $outPriceInfo['insurancesOut'][$insuranceChildPriceValue]['value'] + $b;
                            }else{
                                $outPriceInfo['insurancesOut'][$insuranceChildPriceValue] = [
                                    'value' => $b,
                                    'label_first' => 'RV '. $bookingRequest->getInsurance()->getName() .' ('. $insuranceChildPrice->getCode() .') ',
                                    'label_last' => Util::formatPrice($insuranceChildPriceValue) . ' pro Kind',
                                    'count' => $childrenCount,
                                ];
                            }
                        }

                        $outPriceInfo['insurances'][] = [
                            'insurance' => $bookingRequest->getInsurance(),
                            'insurancePriceValue' => $insurancePriceValue,
                            'insurancePrice' => $insurancePrice,
                            'count' => $adultCount,
                            'insuranceChildPriceValue' => $insuranceChildPriceValue,
                            'insuranceChildPrice' => $insuranceChildPrice,
                            'countChild' => $childrenCount,
                        ];
                    }
                }
            }
        }


        //Departure
        if(count($tempDepartureHTML) > 0){
            foreach ($tempDepartureHTML as $item) {
                $outHtmlSummary[] =[
                    'value' => $item['value'],
                    'label' => '<strong>'.$item['count'].'</strong> x '.$item['label_first'].'<strong> ['.$item['label_last'].' ]</strong>',
                ];
            }
        }
        //Comfort
        if(count($tempComfortHTML) > 0){
            foreach ($tempComfortHTML as $item) {
                $outHtmlSummary[] =[
                    'value' => $item['value'],
                    'label' => '<strong>'.$item['count'].'</strong> x '.$item['label_first'].'<strong> ['.$item['label_last'].' ]</strong>',
                ];
            }
        }
        //ROOMS
        if(count($tempRoomHTML) > 0){
            foreach ($tempRoomHTML as $item) {
                $label = '<strong>'.$item['count'].'</strong> x '.$item['label_first'].'<strong> ['.$item['label_last'].']</strong>';
                if($item['childCount'] > 0){
                    $label .= ' <strong>[ + Kind: '.$item['price_child'];
                }
                $label .= ']</strong>';
                $outHtmlSummary[] =[
                    'value' => $item['value'],
                    'label' => $label,
                ];
            }
        }
        //DISCOUNT
        if(count($tempDiscountHTML) > 0){
            foreach ($tempDiscountHTML as $item) {
                $insuranceHtmlSummary[] =[
                    'value' => $item['value'],
                    'label' => '<strong>'.$item['count'].'</strong> x '.$item['label_first'].'<strong> ['.$item['label_last'].' ]</strong>',
                ];
            }
        }
        //options
        if(count($tempOptionHTML) > 0){
            foreach ($tempOptionHTML as $item) {
                $label = '<strong>'.$item['count'].'</strong> x '.$item['label_first'].'<strong> ['.$item['label_last'].']</strong>';
                if($item['childCount'] > 0){
                    $label .= ' <strong>['.$item['price_child'].']</strong>';
                }
                $outHtmlSummary[] =[
                    'value' => $item['value'],
                    'label' => $label,
                ];
            }
        }


        //Versicherungen
        if(count($tempInsuranceHTML) > 0 ){
            foreach ($tempInsuranceHTML as $item) {
                $insuranceHtmlSummary[] =[
                    'value' => $item['value'],
                    'label' => '<strong>'.$item['count'].'</strong> x '.$item['label_first'].'<strong> ['.$item['label_last'].' ]</strong>',
                ];
            }
        }




        if (isset($insuranceHtmlSummary))
        {
            $outHtmlSummary = array_merge($outHtmlSummary, $insuranceHtmlSummary);
        }
        if (isset($outPriceInfo))
        {
            $outPriceInfo['total'] = $ret;
            $outPriceInfo['totalWithoutInsurance'] = $ret - $insuranceTotal;

            if($outPriceInfo['departure_extra'] >= 0){
                $outPriceInfo['flight_price'] = $outPriceInfo['flight_price'] + $outPriceInfo['departure_extra'];
            }else{
                $outPriceInfo['flight_price'] = 0;
            }

            //Aeqypten (20% from price)
            if($categoryId == 1){
                $deposit = ($outPriceInfo['total'] / 100 * 20);
                $outPriceInfo['deposit_total'] = $deposit;
                $outPriceInfo['final_payment'] = ($outPriceInfo['total'] - $outPriceInfo['deposit_total']);
            }else{
                //all 100% vom Flugpreis und 20% von der Landleistung.
                $deposit = (($outPriceInfo['total'] - $outPriceInfo['flight_price']) / 100 * 20);
                $outPriceInfo['deposit_total'] = ($deposit + $outPriceInfo['flight_price']);
                $outPriceInfo['final_payment'] = ($outPriceInfo['total'] - $outPriceInfo['deposit_total']);
            }
        }

        return $ret;
    }

    /**
     * @param TravelPeriodPrice[] $prices
     * @param $persons
     *
     * @return array
     */
    private function getRooms($prices, $persons)
    {
        $ret = [];

        foreach($prices as $price)
        {
            $priceTypeId = $price->getPriceTypeId();
            //with children
            $priceType = $this->priceTypeById[$priceTypeId];

            if($priceTypeId == 1 && $persons['singleRoomPersons'] > 0)
            {
                for($i = 0; $i < $persons['singleRoomPersons']; $i++)
                {
                    $currentPersons = [
                        'total' => 1,
                        'adults' => 1,
                        'children' => 0 //TODO
                    ];

                    $ret[] = [
                        'priceType' => $priceType,
                        'persons' => $currentPersons,
                        'price' => $price
                    ];
                }
            }

            if($priceTypeId == 1 && $persons['singleRoomChildPersons'] > 0)
            {
                $priceTypeId = 2;
                $priceType = $this->priceTypeById[$priceTypeId];

                for($i = 0; $i < $persons['singleRoomChildPersons']; $i++)
                {
                    $currentPersons = [
                        'total' => 1,
                        'adults' => 1,
                        'children' => 1
                    ];

                    $ret[] = [
                        'priceType' => $priceType,
                        'persons' => $currentPersons,
                        'price' => $price
                    ];
                }
            }

            if($priceTypeId == 3 && $persons['doubleRoomPersons'] > 0)
            {
                for($j = 0; $j < ($persons['doubleRoomPersons'] / 2); $j++)
                {
                    $currentPersons = [
                        'total' => 2,
                        'adults' => 2,
                        'children' => 0
                    ];

                    $ret[] = [
                        'priceType' => $priceType,
                        'persons' => $currentPersons,
                        'price' => $price
                    ];
                }
            }

            if($priceTypeId == 3 && $persons['doubleRoomChildPersons'] > 0)
            {
                $priceTypeId = 4;
                $priceType = $this->priceTypeById[$priceTypeId];

                for($j = 0; $j < ($persons['doubleRoomChildPersons'] / 2); $j++)
                {
                    $currentPersons = [
                        'total' => 2,
                        'adults' => 2,
                        'children' => 1
                    ];

                    $ret[] = [
                        'priceType' => $priceType,
                        'persons' => $currentPersons,
                        'price' => $price
                    ];
                }
            }

            if($priceTypeId == 5 && $persons['tripleRoomPersons'] > 0)
            {
                for($k = 0; $k < ($persons['tripleRoomPersons'] / 3); $k++)
                {
                    $currentPersons = [
                        'total' => 3,
                        'adults' => 3,
                        'children' => 0
                    ];

                    $ret[] = [
                        'priceType' => $priceType,
                        'persons' => $currentPersons,
                        'price' => $price
                    ];
                }
            }

            if($priceTypeId == 5 && $persons['tripleRoomChildPersons'] > 0)
            {
                $priceTypeId = 7;
                $priceType = $this->priceTypeById[$priceTypeId];

                for($k = 0; $k < ($persons['tripleRoomChildPersons'] / 3); $k++)
                {
                    $currentPersons = [
                        'total' => 3,
                        'adults' => 3,
                        'children' => 1
                    ];

                    $ret[] = [
                        'priceType' => $priceType,
                        'persons' => $currentPersons,
                        'price' => $price
                    ];
                }
            }
        }

        return $ret;
    }
}