<?php


namespace App\Core\Service\ChannelManager;


use App\Core\Mail\LogMail;
use App\Core\Service\ChannelManagerMappingService;
use App\Core\Service\ChannelManagerPropertyMappingService;
use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;


class ElektraWeb
{

    private $statusMapping;
    private $paymentTypeMapping;
    private $channelManagerId;
    private $channelManagerName;
    private $mailer;

    public function __construct(
        Client $restClient,
        Mailer $mailer,
        ChannelManagerPropertyMappingService $channelManagerPropertyMappingService,
        ChannelManagerMappingService $channelManagerMappingService
    )
    {
        $this->restClient = $restClient;
        $this->mailer = $mailer;
        $this->reservationPushUrl = 'https://channelmanager.elektraweb.com/extranetwork?action=push';


        $this->typeMapping = [
            'Booking' => 'Book',
            'Modify' => 'Modify',
            'Cancel' => 'Cancel'
        ];

        $this->channelManagerId = 4;
        $this->channelManagerName = 'ElektraWeb';
        $this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
        $this->channelManagerMappingService = $channelManagerMappingService;

    }

    public function requestPost($method, $xmlPayload)
    {
        $response = ['status' => false, 'message' => ''];

        try {
            $this->restClient = new Client(['http_errors' => false]);
            $res = $this->restClient->post($this->url . $method,
                [
                    'headers' => [
                        'Content-Type' => 'text/xml; charset=UTF8',
                        'Accept' => 'text/xml'
                    ],
                    'body' => $xmlPayload,
                ]
            );

            $getResponseBody = $res->getBody();
            $getResponse = $getResponseBody->getContents();
            $getResponseXml = new \SimpleXMLElement($getResponse, LIBXML_NOCDATA);
            $getResponse = json_decode(json_encode($getResponseXml), 1);

            $response = ["status" => true, 'message' => '', "data" => $getResponse];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return $response;

    }

    public function requestPostReservationPushParam($propertyId, $bookingId, $type, $param = [])
    {

        $type = $this->typeMapping[$type];
        $bookingDetail = $param['booking_detail'];


        $jsonResponse = [];
        $jsonResponse['hotel_id'] = $propertyId;


        $jsonResponse['reservation']['code'] = $bookingDetail['booking_code'];
        $jsonResponse['reservation']['status'] = $type;

        $jsonResponse['reservation']['time'] = Carbon::createFromTimestamp($param['booking_detail']['created_at'])->toDateTimeString();

        $jsonResponse['reservation']['checkin_date'] = $bookingDetail['checkin_date'];
        $jsonResponse['reservation']['checkout_date'] = $bookingDetail['checkout_date'];
        $jsonResponse['reservation']['currency'] = $bookingDetail['currency_code'];
        $jsonResponse['reservation']['total'] = ($bookingDetail['total'] - $bookingDetail['addon_amount']);

        $jsonResponse['reservation']['contact'] = [
            'name' => $bookingDetail['booking_contact']['name'],
            'surname' => $bookingDetail['booking_contact']['surname'],
            'email' => $bookingDetail['booking_contact']['email'],
            'phone' => $bookingDetail['booking_contact']['phoneFormatted'],
            'note' => $bookingDetail['booking_contact']['note'],
        ];


        $jsonResponse['reservation']['rooms'] = [];


        $roomKey = 0;
        foreach ($bookingDetail['booking_room'] as $roomKey => $roomDetail) {

            $occupancy = occupancyCodeParser($roomDetail['occupancy_code']);

            $diffInDays = Carbon::parse($roomDetail['checkin_date'])->diffInDays(Carbon::parse($roomDetail['checkout_date']));
            $baseRateDaily = moneyDoubleFormatDecimal($roomDetail['total'] / $diffInDays);

            $dailyPrices = [];
            $currentDate = $roomDetail['checkin_date'];
            for ($i = 0; $i < $diffInDays; $i++) {
                $dailyPrices[] = [
                    'date' => $currentDate,
                    'amount' => $baseRateDaily
                ];
                $currentDate = Carbon::parse($currentDate)->addDay()->toDateString();
            }

            $roomPax = [];
            foreach ($roomDetail['room_pax'] as $pax) {
                $roomPax[] = [
                    'type' => $pax['type'],
                    'name' => $pax['name'],
                    'surname' => $pax['surname'],
                    'gender' => $pax['gender'],
                    'citizen' => $pax['citizen'],
                    'birth_date' => $pax['birth_date'],
                ];
            }

            $jsonResponse['reservation']['rooms'][$roomKey] = [
                'room_id' => $roomDetail['room_id'],
                'room_name' => $roomDetail['room_name'],
                'rate_id' => $roomDetail['room_rate_mapping_id'],
                'rate_name' => $roomDetail['room_rate_name'],
                'occupancy' => [
                    'adults' => $occupancy['ADT'],
                    'children' => $occupancy['CHD'],
                    'age' => $occupancy['AGE'],
                ],
                'daily' => $dailyPrices,
                'pax' => $roomPax

            ];


        }

        $jsonResponse['reservation']['channel'] = [
            'id' => $bookingDetail['booking_channel']['id'],
            'name' => $bookingDetail['booking_channel']['id'] == 1 ? 'Extranetwork' : $bookingDetail['booking_channel']['name'],
        ];

        $jsonResponse['reservation']['payment'] = [
            'code' => $bookingDetail['booking_payment_type']['code'],
            'name' => $bookingDetail['booking_payment_type']['name'],
        ];

        return json_encode($jsonResponse);

    }

    public function requestPostReservationPush($jsonPayload)
    {
        $response = ['status' => false, 'message' => ''];


        try {
            $this->restClient = new Client(['http_errors' => false]);
            $res = $this->restClient->post($this->reservationPushUrl,
                [
                    'headers' => [
                        'Content-Type' => 'application/json'
                    ],
                    'body' => $jsonPayload,
                ]
            );

            $getResponseBody = $res->getBody();
            $getResponseJsonBase = $getResponseBody->getContents();

            $getResponse = json_decode($getResponseJsonBase, 1);

            if (!$getResponse['Success']) {
                throw new ApiErrorException($getResponse['Message']);
            }

            $response = ['status' => true, 'message' => '', 'response' => json_encode($getResponse)];

        } catch (ApiErrorException $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }


        return $response;

    }


}
