<?php

namespace AppBundle\Export;


use AppBundle\Entity\BookingRequest;
use AppBundle\Entity\FewoBookingRequest;
use AppBundle\Entity\FewoLodging;
use AppBundle\Entity\FewoPrice;
use AppBundle\Entity\TravelDate;
use AppBundle\Entity\Traveler;
use AppBundle\Util;
use Monolog\Logger;

class FewoBookingSternToursCrmExporter extends SternToursCrmExporter
{

    public function __construct(Logger $logger)
    {
        parent::__construct($logger);
    }

    public function process(FewoBookingRequest $fewoBookingRequest, FewoLodging $fewoLodging, FewoPrice $fewoPrice)
    {
        $lead = $this->createLead($fewoBookingRequest);
        if ($lead === null)
        {
            $this->warn('Failed creating lead in CRM', $fewoBookingRequest, Logger::ERROR);
            return false;
        }
        $bookingUrl = $this->createBooking($fewoBookingRequest, $fewoLodging, $fewoPrice, $lead['customer_id'], $lead['id']);
        if ($bookingUrl === false)
        {
            $this->warn('Failed creating booking in CRM', $fewoBookingRequest, Logger::ERROR);
            return false;
        }

        /*
        if(!$this->createTraveler($bookingUrl, $fewoBookingRequest))
        {
            $this->warn('Failed creating traveler in CRM.', $fewoBookingRequest);
        }
        */

        return $bookingUrl;
    }

    private function createLead(FewoBookingRequest $fewoBookingRequest)
    {
        $resp = $this->httpPost('lead', ['lead' => [
            'customerForm' => [
                'salutation_id' => $fewoBookingRequest->getSalutation(),
                'name' => $fewoBookingRequest->getLastName(), // required
                'firstname' => $fewoBookingRequest->getFirstName(),
                'street' => $fewoBookingRequest->getStreetAddress(),
                'zip' => $fewoBookingRequest->getZipCode(),
                'city' => $fewoBookingRequest->getCity(),
                'country_id' => $fewoBookingRequest->getNation(), // required
                'phone' => $fewoBookingRequest->getPhone(),
                'fax' => $fewoBookingRequest->getFax(),
                'email' => $fewoBookingRequest->getEmail()
            ],
            'request_date' => (new \DateTime())->format('Y-m-d'), // required
            'sf_guard_user_id' => self::API_USER_ID,
            'status_id' => 7, // 'gebucht'
            'travelperiod_start' => $fewoBookingRequest->getFromDate()->format('Y-m-d'),
            'travelperiod_end' => $fewoBookingRequest->getToDate()->format('Y-m-d'),
            //'travelcategory_id'
            'is_closed' => 1,
            'website_id' => self::WEBSITE_ID,
            'initialcontacttype_id' => 14,
            // 'travelperiod_length
            'remarks' => $fewoBookingRequest->getNotes()
        ]]);

        //Util::varDump($resp);
        //die();

        if ($resp['success'])
        {
            $ret = $this->httpGet($resp['location']);
            if ($ret == null)
            {
                $this->warn('Failed retrieving newly created lead object', $fewoBookingRequest);
            }
            return $ret;
        }
        return null;
    }

    private function createBooking(FewoBookingRequest $fewoBookingRequest, FewoLodging $lodging, FewoPrice $price, $customerId, $leadId)
    {
        $resp = $this->httpPost('booking', ['booking' => [
            'booking_date' => (new \DateTime())->format('Y-m-d'),
            'customer_id' => $customerId,
            'lead_id' => $leadId,
            //'travel_country_id' => $tp->getTravelCountry(),
            //'travel_category_id' => $tp->getTravelCategory(),
            //'travelagenda_id' => $tp->getTravelAgenda(),
            'sf_guard_user_id' => self::API_USER_ID,
            'branch_id' => 4,
            'website_id' => self::WEBSITE_ID,
            'title' => $lodging->getName(),
            'start_date' => $fewoBookingRequest->getFromDate()->format('Y-m-d'), // required
            'end_date' => $fewoBookingRequest->getToDate()->format('Y-m-d'), // required
            'pax' => $fewoBookingRequest->getTravelerCount(),
            'travel_number' => substr($lodging->getName()." - ".$price->getSeason()->getName(), 0, 30),
            'price' => $fewoBookingRequest->getTotalPrice(),

            'participant_salutation_id' => $fewoBookingRequest->getSalutation(),
            'participant_name' => $fewoBookingRequest->getLastName(),
            'participant_firstname' => $fewoBookingRequest->getFirstName(),
            //'participant_birthdate' => $bookingRequest->getTravelers()[0]->getBirthDate(),
        ]]);

        if (!$resp['success'])
        {
            return false;
        }
        return $resp['location'];
    }

    private function createTraveler($bookingUrl, FewoBookingRequest $fewoBookingRequest)
    {
        $resp = $this->httpPost($bookingUrl .'/participant.json', ['participant' => [
            'participant_salutation_id' => $fewoBookingRequest->getSalutation(),
            'participant_name' => $fewoBookingRequest->getLastName(),
            'participant_firstname' => $fewoBookingRequest->getFirstName(),
            //'participant_birthdate' => $traveler->getBirthDate(),
        ]], true);
        return $resp['success'];
    }

    private function warn($msg, FewoBookingRequest $fewoBookingRequest = null, $level = Logger::WARNING)
    {
        $this->logger->log($level, 'SternToursCrmBookingExporter: '. $msg);
        $this->logger->log($level, '*** Date: '. (new \DateTime())->format('d.m.Y'));

        if ($fewoBookingRequest !== null)
        {
            $this->logger->log($level, '*** Booking date: '. $fewoBookingRequest->getFromDate()->format('d.m.Y') .
                ' - '. $fewoBookingRequest->getToDate()->format('d.m.Y') .')');

            $this->logger->log($level, '*** User name: '. $fewoBookingRequest->getFirstName() .' '. $fewoBookingRequest->getLastName());
        }
    }
}