<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\BookingDraftItem;
use App\Models\Draft;
use App\Models\TravelProgram;
use Carbon\Carbon;
use HTMLHelper;


class DraftController extends Controller
{
    public $successStatus = 200;
    public $data = "";
    public $room_str = "";
    public $room_name = "";
    public $className = "";
    public $option = "";

    public function draft($action)
    {


        if ($action == "get_draft_list") {
            $drafts = Draft::where('active', true)->get()->sortByDesc("id");
            return response()->json(['success' => $drafts], $this->successStatus);
        }

        if ($action == "get_draft_list_for_table") {
            $ret = [];
            if (request('program_id') && request('program_id') > 0) {
                $travel_program = TravelProgram::find(request('program_id'));
                if ($travel_program && count($travel_program->travel_program_drafts)) {
                    foreach ($travel_program->travel_program_drafts as $travel_program_draft) {
                        $key = $travel_program_draft->id;
                        $ret[$key]['name'] = $travel_program_draft->draft->name;
                        if ($travel_program_draft->travel_class) {
                            $ret[$key]['travel_class'] = $travel_program_draft->travel_class->name;
                        } else {
                            $ret[$key]['travel_class'] = "alle Kategorien";
                        }
                        $ret[$key]['weekdays'] = HTMLHelper::getWeekdaysString($travel_program_draft->weekdays);
                    }
                }
            }
            return response()->json(['success' => $ret], $this->successStatus);


        }

        if ($action == "create_drafts_from_fewo") {
            $data = \Input::all();
            $start_date = Carbon::parse($data['startDateStr']);
            $end_date = Carbon::parse($data['endDateStr']);
            $pos = 0;
            if(isset($data['priceResult']) && is_array($data['priceResult'])){

                if(isset($data['priceResult']['season']) && is_array($data['priceResult']['season'])){
                    foreach ($data['priceResult']['season'] as $season => $values){

                        $service = '* Saison: '.$season."\n".
                            '* Mindestbelegung: '.$values['minimumStay'].' '.($values['minimumStay'] < 2 ? 'Nacht' : 'Nächte')."\n".
                            '* Preis: '.number_format($values['price'], 2, ',', '.').' €  / '. $values['numberDays'].' '.($values['numberDays'] < 2 ? 'Nacht' : 'Nächte').' x '.number_format($values['perNight'], 2, ',', '.')." € \n";



                        $from_date = Carbon::parse($values['fromDay']);
                        $to_date = Carbon::parse($values['toDay']);
                        $to_date->modify('+1 day');

                        BookingDraftItem::create([
                            'booking_id' => $data['booking_id'],
                            'fewo_lodging_id' => $data['fewo_lodging_id'],
                            'draft_type_id' => 38,
                            'request_date' => $data['request_date'],
                            'days_duration' =>  $values['numberDays'],
                            'start_date' => $from_date->format("Y-m-d"),
                            'end_date' => $to_date->format("Y-m-d"),
                            'service' => $service,
                            'price' => $values['perNight'],
                            'pos' => $pos,
                            'in_pdf' => true,
                        ]);
                        $pos++;

                    }
                }
                if(isset($data['priceResult']['flatPrice'])){
                    $service = '* Service-Gebühr: '.number_format($data['priceResult']['deposit'], 2, ',', '.');
                    BookingDraftItem::create([
                        'booking_id' => $data['booking_id'],
                        'fewo_lodging_id' => $data['fewo_lodging_id'],
                        'draft_type_id' => 39,
                        'request_date' => $data['request_date'],
                        'days_duration' =>  $data['priceResult']['days'],
                        'start_date' => $start_date->format("Y-m-d"),
                        'end_date' => $end_date->format("Y-m-d"),
                        'service' => $service,
                        'price' => $data['priceResult']['flatPrice'],
                        'pos' => $pos,
                        'in_pdf' => true,
                    ]);
                    $pos++;


                }
                if(isset($data['priceResult']['deposit'])){
                    $service = '* Kaution: '.number_format($data['priceResult']['deposit'], 2, ',', '.');
                    BookingDraftItem::create([
                        'booking_id' => $data['booking_id'],
                        'fewo_lodging_id' => $data['fewo_lodging_id'],
                        'draft_type_id' => 40,
                        'request_date' => $data['request_date'],
                        'days_duration' =>  $data['priceResult']['days'],
                        'start_date' => $start_date->format("Y-m-d"),
                        'end_date' => $end_date->format("Y-m-d"),
                        'service' => $service,
                        'price' => $data['priceResult']['flatPrice'],
                        'pos' => $pos,
                        'in_pdf' => true,
                    ]);
                }


             }

            return response()->json(['success' => $data['booking_id']], $this->successStatus);

        }



        if ($action == "create_drafts_from_booking") {
            $data = \Input::all();
            $this->data = $data;

            $weekday = date('w', strtotime($data['startDateStr']));
            $travel_program = TravelProgram::find($data['travel_program_id']);
            $draft = $this->getDraftByTravelProgramData($travel_program, $data, $weekday);

            $start_date = Carbon::parse($data['startDateStr']);
            $end_date = Carbon::parse($data['endDateStr']);


            if($draft){

                //------------------------------------------------------------------------------
                //prepare rooms
                //request('rooms'); //  //["rooms"]=> array(1) { [0]=> object(stdClass)#7284 (5) { ["name"]=> string(12) "Einzelzimmer" ["price_adult"]=> float(1682.16) ["adult"]=> int(1) ["children"]=> int(0) ["price_children"]=> int(0) }
                $price_info_rooms = [];
                $room_names = [];
                $room_adult = 0;
                $room_children = 0;
                $room_price_adult = 0;
                $room_price_children = 0;

                $data['rooms'] = array_reverse($data['rooms']);

                foreach ($data['rooms'] as $room){

                        $room_adult += $room['adult'];
                        $room_children += $room['children'];
                        $room_price_adult += ($room['price_adult'] * $room['adult']);
                        $room_price_children +=  ($room['price_children'] * $room['children']);

                    if(isset($room_names[$room['name']])){
                        $room_names[$room['name']] = $room_names[$room['name']]+1;
                    }else{
                        $room_names[$room['name']] = 1;
                    }

                    $service = trans('_vorlagen.grundpreis_reise');
                    $this->room_name =  $room['name'];
                    $service = $this->replaceService($service);

                    $price_info_rooms[] = [
                        'booking_id' => $data['booking_id'],
                        'travel_program_id' => $data['travel_program_id'],
                        'fewo_lodging_id' => null,
                        'travel_class_id' => null,
                        'draft_item_id' => null,
                        'draft_type_id' => 30,
                        'request_date' => $data['request_date'],
                        'days_start' => null,
                        'days_duration' =>  null,
                        'start_date' => $data['startDateStr'],
                        'end_date' => $data['endDateStr'],
                        'service' => $service,
                        'price_adult' => $room['price_adult'],
                        'adult' => $room['adult'],
                        'price_children' => $room['price_children'],
                        'children' => $room['children'],
                        'pos' => 0,
                        'in_pdf' => true,
                        'comfort' => $data['comfort']
                    ];
                }




                $this->room_str = "";
                foreach ($room_names as $name=>$count){
                    $this->room_str .= $count.' x '.$name.', ';
                }
                $this->room_str = rtrim($this->room_str, ', ');


                //before & after days

                $price_info_rooms_before = [];
                $price_info_rooms_after = [];

                if(isset($data['booking_before']) && is_array($data['booking_before'])){
                    foreach ($data['booking_before'] as $booking_before){
                        $start_date_before = clone $start_date;
                        if(isset($booking_before['days']) && $booking_before['days'] > 0){
                            $start_date_before->modify('-'.$booking_before['days'].' day');
                        }

                        $price_info_rooms_before[] = [
                            'booking_id' => $data['booking_id'],
                            'travel_program_id' => $data['travel_program_id'],
                            'fewo_lodging_id' => null,
                            'travel_class_id' => null,
                            'draft_item_id' => null,
                            'draft_type_id' => 36,
                            'request_date' => $data['request_date'],
                            'days_start' => null,
                            'days_duration' =>  $booking_before['days'],
                            'start_date' => $start_date_before->format("Y-m-d"),
                            'end_date' => $data['startDateStr'],
                            'service' => $booking_before['name'],
                            'price_adult' => $booking_before['price'],
                            'adult' => $booking_before['adults'],
                            'price_children' => $booking_before['price_children'],
                            'children' => $booking_before['children'],
                            'pos' => 0,
                            'in_pdf' => true,
                            'comfort' => $data['comfort']
                        ];
                    }
                }

                if(isset($data['booking_after']) && is_array($data['booking_after'])){
                    foreach ($data['booking_after'] as $booking_after){
                            $end_date_after = clone $end_date;
                        if(isset($booking_after['days']) && $booking_after['days'] > 0){
                            $end_date_after->modify('+'.$booking_after['days'].' day');
                        }

                        $price_info_rooms_after[] = [
                            'booking_id' => $data['booking_id'],
                            'travel_program_id' => $data['travel_program_id'],
                            'fewo_lodging_id' => null,
                            'travel_class_id' => null,
                            'draft_item_id' => null,
                            'draft_type_id' => 37,
                            'request_date' => $data['request_date'],
                            'days_start' => null,
                            'days_duration' =>  $booking_after['days'],
                            'start_date' => $data['endDateStr'],
                            'end_date' => $end_date_after->format("Y-m-d"),
                            'service' => $booking_after['name'],
                            'price_adult' => $booking_after['price'],
                            'adult' => $booking_after['adults'],
                            'price_children' => $booking_after['price_children'],
                            'children' => $booking_after['children'],
                            'pos' => 0,
                            'in_pdf' => true,
                            'comfort' => $data['comfort']
                        ];
                    }
                }


                //------------------------------------------------------------------------------
                //prepare extra_charge
                $price_info_extra_charge = [];
                if($data['departure_extra_charge'] > 0){

                    $service = trans('_vorlagen.aufpreis_flug');
                    $service = $this->replaceService($service);

                    $price_info_extra_charge[] = [
                        'booking_id' => $data['booking_id'],
                        'travel_program_id' => $data['travel_program_id'],
                        'fewo_lodging_id' => null,
                        'travel_class_id' => null,
                        'draft_item_id' => null,
                        'draft_type_id' => 33,
                        'request_date' => $data['request_date'],
                        'days_start' => null,
                        'days_duration' =>  null,
                        'start_date' => null,
                        'end_date' => null,
                        'service' => $service,
                        'price_adult' => $data['departure_extra_charge'] ,
                        'adult' => $data['traveler'] ,
                        'price_children' => 0,
                        'children' => 0,
                        'pos' => 0,
                        'in_pdf' => true,
                        'comfort' => $data['comfort']
                    ];
                }

                //------------------------------------------------------------------------------
                //prepare $class_options
                $price_info_class_options = [];
                foreach ($data['class_options'] as $class_option){

                    $service = trans('_vorlagen.aufpreis_kategorie');
                    $this->className = $class_option['name'];
                    $service = $this->replaceService($service);

                    $price_info_class_options[] = [
                        'booking_id' => $data['booking_id'],
                        'travel_program_id' => $data['travel_program_id'],
                        'fewo_lodging_id' => null,
                        'travel_class_id' => null,
                        'draft_item_id' => null,
                        'draft_type_id' => 32,
                        'request_date' => $data['request_date'],
                        'days_start' => null,
                        'days_duration' =>  null,
                        'start_date' => null,
                        'end_date' => null,
                        'service' => $service,
                        'price_adult' => $class_option['price'],
                        'adult' => $class_option['count'],
                        'price_children' => 0,
                        'children' => 0,
                        'pos' => 0,
                        'in_pdf' => true,
                        'comfort' => $data['comfort']
                    ];
                }

                //------------------------------------------------------------------------------
                //prepare $travel_options
                $price_info_travel_options = [];
                foreach ($data['travel_options'] as $travel_option){

                    $service = trans('_vorlagen.aufpreis_option');
                    $this->option = $travel_option['name'];
                    $service = $this->replaceService($service);

                    $price_info_travel_options[] = [
                        'booking_id' => $data['booking_id'],
                        'travel_program_id' => $data['travel_program_id'],
                        'fewo_lodging_id' => null,
                        'travel_class_id' => null,
                        'draft_item_id' => null,
                        'draft_type_id' => 34,
                        'request_date' => $data['request_date'],
                        'days_start' => null,
                        'days_duration' =>  null,
                        'start_date' => null,
                        'end_date' => null,
                        'service' =>  $service,
                        'price_adult' => $travel_option['price_adult'],
                        'adult' => $travel_option['adult'],
                        'price_children' => $travel_option['price_children'],
                        'children' => $travel_option['children'],
                        'pos' => 0,
                        'in_pdf' => true,
                        'comfort' => $data['comfort']
                    ];
                }
                $info_texts = [];
                $last_post = 0;
                foreach ($draft->draft_items as $draft_item){

                    $service = $draft_item->service;
                    $price_adult = 0;
                    $adult = 0;
                    $price_children = 0;
                    $children = 0;

                    switch ($draft_item->draft_type->id){
                        case 24: //rundreise
                            $price_adult = $room_price_adult;
                            $adult = $room_adult;
                            $price_children = $room_price_children;
                            $children = $room_children;
                            break;
                        case 4: //flug
                           // "Hinflug: Rückflug: Flugzeiten ?"
                            break;
                    }

                    $start_date_temp = null;
                    if($draft_item->days_start > 0){
                        $start_date_temp = clone $start_date;
                        $start_date_temp->addDay($draft_item->days_start-1);
                    }

                    $end_date_temp = null;
                    if($draft_item->days_duration > 0){
                        $end_date_temp = clone $start_date;
                        $end_date_temp->addDay($draft_item->days_duration-1);
                    }

                    $service = $this->replaceService($service);

                    if($draft_item->draft_type->id == 27){
                        //text -at last
                        $info_texts[] = [
                            'booking_id' => $data['booking_id'],
                            'travel_program_id' => $data['travel_program_id'],
                            'fewo_lodging_id' => null,
                            'travel_class_id' => null,
                            'draft_item_id' => $draft_item->id,
                            'draft_type_id' => $draft_item->draft_type->id,
                            'request_date' => $data['request_date'],
                            'days_start' => $draft_item->days_start,
                            'days_duration' =>  $draft_item->days_duration,
                            'start_date' => $start_date_temp ? $start_date_temp->format("Y-m-d") : null,
                            'end_date' => $end_date_temp ? $end_date_temp->format("Y-m-d") : null,
                            'service' => $service,
                            'price_adult' => $price_adult,
                            'adult' => $adult,
                            'price_children' => $price_children,
                            'children' => $children,
                            'pos' => $draft_item->pos,
                            'in_pdf' => $draft_item->in_pdf,
                            'comfort' => $data['comfort']
                        ];


                    }else{
                        //create new from draft items
                        BookingDraftItem::create([
                            'booking_id' => $data['booking_id'],
                            'travel_program_id' => $data['travel_program_id'],
                            'fewo_lodging_id' => null,
                            'travel_class_id' => null,
                            'draft_item_id' => $draft_item->id,
                            'draft_type_id' => $draft_item->draft_type->id,
                            'request_date' => $data['request_date'],
                            'days_start' => $draft_item->days_start,
                            'days_duration' =>  $draft_item->days_duration,
                            'start_date' => $start_date_temp ? $start_date_temp->format("Y-m-d") : null,
                            'end_date' => $end_date_temp ? $end_date_temp->format("Y-m-d") : null,
                            'service' => $service,
                            'price_adult' => $price_adult,
                            'adult' => $adult,
                            'price_children' => $price_children,
                            'children' => $children,
                            'pos' => $draft_item->pos,
                            'in_pdf' => $draft_item->in_pdf,
                            'comfort' => $data['comfort']
                        ]);
                    }



                    $last_post = $draft_item->pos;

                }

                //set room prices
                if(count($price_info_rooms)){
                    foreach ($price_info_rooms as $price_info_room){
                        $last_post ++;
                        $price_info_room['pos'] = $last_post;
                        BookingDraftItem::create($price_info_room);
                    }
                }

                //set room prices before
                if(count($price_info_rooms_before)){
                    foreach ($price_info_rooms_before as $price_info_room){
                        $last_post ++;
                        $price_info_room['pos'] = $last_post;
                        BookingDraftItem::create($price_info_room);
                    }
                }

                //set room prices after
                if(count($price_info_rooms_after)){
                    foreach ($price_info_rooms_after as $price_info_room){
                        $last_post ++;
                        $price_info_room['pos'] = $last_post;
                        BookingDraftItem::create($price_info_room);
                    }
                }



                //set extra charge price
                if(count($price_info_extra_charge)){
                    foreach ($price_info_extra_charge as $price_info_extra){
                        $last_post ++;
                        $price_info_extra['pos'] = $last_post;
                        BookingDraftItem::create($price_info_extra);
                    }
                }
                //set class options prices
                if(count($price_info_class_options)){
                    foreach ($price_info_class_options as $price_info_class_option){
                        $last_post ++;
                        $price_info_class_option['pos'] = $last_post;
                        BookingDraftItem::create($price_info_class_option);
                    }
                }

                //set travel options prices
                if(count($price_info_travel_options)){
                    foreach ($price_info_travel_options as $price_info_travel_option){
                        $last_post ++;
                        $price_info_travel_option['pos'] = $last_post;
                        BookingDraftItem::create($price_info_travel_option);
                    }
                }

                //set travel options prices
                if(count($info_texts)){
                    foreach ($info_texts as $info_text){
                        $last_post ++;
                        $info_text['pos'] = $last_post;
                        BookingDraftItem::create($info_text);
                    }
                }
            }




            $ret = [];
          /*
            $travel_program_id = request('travel_program_id');
            $comfort = request('comfort');
            $booking_id = request('booking_id');
            $startDateStr = request('startDateStr');
            $endDateStr = request('endDateStr');
            $departure = request('departure');
            $departure_extra_charge = request('departure_extra_charge');
            $traveler = request('traveler');
            $title = request('title');
            $number = request('number');
            $rooms = request('rooms'); //  //["rooms"]=> array(1) { [0]=> object(stdClass)#7284 (5) { ["name"]=> string(12) "Einzelzimmer" ["price_adult"]=> float(1682.16) ["adults"]=> int(1) ["children"]=> int(0) ["price_children"]=> int(0) }
            $class_options = request('class_options'); //["travel_options"]=> array(2) { [0]=> array(5) { ["name"]=> string(20) "Aufpreis Halbpension" ["price_adult"]=> float(75) ["adult"]=> int(5) ["children"]=> int(0) ["price_children"]=> int(0) }
            $travel_options = request('travel_options'); //["class_options"]=> array(1) { [0]=> array(3) { ["name"]=> string(39) "zugebuchte Leistung: Komfort (4 Sterne)" ["price"]=> float(152) ["count"]=> int(1)
         */

            return response()->json(['success' => $draft->id], $this->successStatus);


        }
    }

    protected function replaceService($service){

        $service = str_replace('#Name#', $this->data['title'], $service);
        $service = str_replace('#Nummer#', $this->data['number'], $service);
        $service = str_replace('#Zimmer#', $this->room_str, $service);
        $service = str_replace('#Raumname#', $this->room_name, $service);
        $service = str_replace('#Kategorie#', $this->className, $service);
        $service = str_replace('#Option#', $this->option, $service);
        $service = str_replace('#Flughafen#', $this->data['departure'], $service);

        return $service;

    }

    protected function getDraftByTravelProgramData($travel_program, $data, $weekday){
        if ($travel_program && count($travel_program->travel_program_drafts)) {

            foreach ($travel_program->travel_program_drafts as $travel_program_draft) {
                //this need an realation to travel class by booking and price
                if(in_array($weekday, $travel_program_draft->weekdays)){
                    if($data['comfort'] == false && strpos(strtolower($travel_program_draft->travel_class->name), 'standard') !== false){
                        return $travel_program_draft->draft;
                    }
                    if($data['comfort'] == true && strpos(strtolower($travel_program_draft->travel_class->name), 'komfort') !== false){
                        return $travel_program_draft->draft;
                    }
                }
            }
            //found non get first
            foreach ($travel_program->travel_program_drafts as $travel_program_draft) {
                return $travel_program_draft->draft;

            }


        }
        return null;
    }
}
/*
array(14) {
    ["travel_program_id"]=> int(197) ["comfort"]=> bool(true) ["booking_id"]=> string(4) "8435" ["request_date"]=> string(10) "2018-10-29" ["startDateStr"]=> string(10) "2018-11-03" ["endDateStr"]=> string(10) "2018-11-10" ["departure"]=> string(7) "Hamburg" ["departure_extra_charge"]=> float(55) ["traveler"]=> int(3) ["title"]=> string(35) "Höhepunkte Jordaniens ab Nov. 2018" ["number"]=> string(16) "JOR-HOE1920018B1" ["rooms"]=> array(2) {
        [0]=> array(5) {
            ["name"]=> string(12) "Doppelzimmer" ["price_adult"]=> float(1473.85) ["adults"]=> int(2) ["children"]=> int(0) ["price_children"]=> int(0) } [1]=> array(5) {
            ["name"]=> string(12) "Einzelzimmer" ["price_adult"]=> float(1682.16) ["adults"]=> int(1) ["children"]=> int(0) ["price_children"]=> int(0) } } ["class_options"]=> array(2) {
        [0]=> array(3) {
            ["name"]=> string(39) "zugebuchte Leistung: Komfort (4 Sterne)" ["price"]=> float(122) ["count"]=> int(2) } [1]=> array(3) {
            ["name"]=> string(39) "zugebuchte Leistung: Komfort (4 Sterne)" ["price"]=> float(171) ["count"]=> int(1) } } ["travel_options"]=> array(1) {
        [0]=> array(5) {
            ["name"]=> string(20) "Aufpreis Halbpension" ["price_adult"]=> float(75) ["adults"]=> int(3) ["children"]=> int(0) ["price_children"]=> int(0) } } }
*/