<?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 Fina
{

    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 = [
            790 => 'http://92.51.115.18/api/hotel/saveReservation'
        ];

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

        $this->channelManagerId = 8;
        $this->channelManagerName = 'Fina';
        $this->channelManagerPropertyMappingService = $channelManagerPropertyMappingService;
        $this->channelManagerMappingService = $channelManagerMappingService;

    }

    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'];


        $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) {

            if ($roomDetail['status'] != 1) {
                continue;
            }

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

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

            //Additional Fee
            $additionalFees = null;
            if (!empty($roomDetail['rate_detail'])) {
                $rateDetail = json_decode($roomDetail['rate_detail'], 1);
                if (isset($rateDetail['taxes']) && $bookingDetail['channel_manager_id'] == 2) {
                    $additionalFees = $rateDetail['taxes'];
                }
            }

            $additionalFeeTotal = null;
            if (!empty($additionalFees)) {
                foreach ($additionalFees as $additionalFee) {

                    if (!$additionalFee['is_inclusive']) {
                        $additionalFeeTotal += $additionalFee['total_price'];
                    }
                }
            }

            $additionalFeePerDay = 0;
            if (!empty($additionalFeeTotal)) {
                $additionalFeePerDay = moneyDoubleFormatDecimal($additionalFeeTotal / $diffInDays);
            }
            //Additional Fee


            $roomDailyAmount = [];
            if (!empty($roomDetail['daily_amount'])) {
                $roomDetailDailyAmount = json_decode($roomDetail['daily_amount'], 1);
                if (!empty($roomDetailDailyAmount) && isset($roomDetailDailyAmount)) {
                    foreach ($roomDetailDailyAmount as $roomRateAmount) {
                        $calculatedAmount = $roomRateAmount['amount'] + $additionalFeePerDay;
                        $roomDailyAmount[] = [
                            'date' => $roomRateAmount['date'],
                            'amount' => moneyDoubleFormatDecimal($calculatedAmount),
                            'currency_code' => $roomRateAmount['currency_code'],
                        ];
                    }
                }

                $totalFromRoomDaily = collect($roomDailyAmount)->sum('amount');
                if ($totalFromRoomDaily != $roomDetail['total']) {
                    $totalFromDifference = moneyDoubleFormatDecimal($roomDetail['total'] - $totalFromRoomDaily);
                    $roomDailyAmount[count($roomDailyAmount) - 1]['amount'] += $totalFromDifference;
                }

            }

            $baseRateDaily = moneyDoubleFormatDecimal($roomDetail['total'] / $diffInDays);
            if (empty($roomDailyAmount)) {
                $currentDate = $roomDetail['checkin_date'];
                for ($i = 0; $i < $diffInDays; $i++) {
                    $roomDailyAmount[] = [
                        'date' => $currentDate,
                        'amount' => $baseRateDaily,
                        'currency_code' => $roomDetail['currency_code'],
                    ];
                    $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] = [
                'id' => $roomDetail['id'],
                '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'],
                ],
                'total' => $roomDetail['total'],
                //'totalFromDaily' => collect($roomDailyAmount)->sum('amount'),
                'daily' => $roomDailyAmount,
                'pax' => $roomPax

            ];


        }

        $jsonResponse['reservation']['channel'] = [
            'id' => $bookingDetail['booking_channel']['id'],
            'name' => $bookingDetail['booking_channel']['id'] == 1 ? 'Extranetwork' : $bookingDetail['booking_channel']['name'],
            'booking_code' => !empty($bookingDetail['channel_booking_code']) ? $bookingDetail['channel_booking_code'] : $bookingDetail['booking_code']
        ];

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

        return json_encode($jsonResponse);

    }

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


        $jsonData = json_decode($jsonPayload, 1);

        $getResponse = [];

        try {

            /*if(!isset($this->reservationPushUrl[$jsonData['hotel_id']])) {
                throw new ApiErrorException('Fina live reservation no push url');
            }

            $this->restClient = new Client(['http_errors' => false, 'timeout' => 30]);
            $res = $this->restClient->post($this->reservationPushUrl[$jsonData['hotel_id']],
                [
                    '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['errorReason']);
            }*/

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

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


        return $response;

    }


}
