<?php

namespace App\Core\Mail;

use App\Exceptions\ApiErrorException;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;

class CancelBookingMail extends Mailable
{

    use Queueable, SerializesModels;

    public $tries = 5;
    public $timeout = 30;

    protected $param;


    public function __construct($param)
    {
        $this->param = $param;
    }

    public function build()
    {
        try {

            $params = $this->param;

            $propertyService = App::make("App\Core\Service\PropertyService");
            $bookingService = App::make("App\Core\Service\BookingService");
            $propertyBrandService = App::make("App\Core\Service\PropertyBrandService");

            $bookingDetailParam = [
                'criteria' => [
                    ['field' => 'id', 'condition' => '=', 'value' => $params['booking_id']]
                ],
                'with' => [
                    'bookingPayment', 'bookingRoom.roomRateMapping.propertyRoom','bookingRoom.roomRateMapping.propertyRoomRate',
                    'bookingContact','bookingProperty.propertyBrand', 'bookingProperty.propertyExecutive', 'bookingProperty.propertyUser.user',
                    'bookingPropertyWeb', 'propertyBookingEngine', 'propertyBookingChannel'
                ],
                'firstRow' => true
            ];

            $bookingData = $bookingService->select($bookingDetailParam);
            $bookingData = $bookingData['data'];


            $hostAddress = Config::get('app.bookingEngineUrl') . '/' . $bookingData['property_booking_engine']['token'] . '/' . $bookingData['booking_contact']['language_code'] . '/booking-detail/' . $bookingData['booking_code'];

            $brandRequestData = ['property_id' => $bookingData['property_id']];
            $getPropertyBrand = $propertyBrandService->getPropertyBrand($brandRequestData);
            if ($getPropertyBrand['status'] != "success") {
                throw new Exception($getPropertyBrand['message']);
            }

            $propertyBrand = $getPropertyBrand['data'];
            $propertyBrandLogo = isset($propertyBrand['name'])
                ? Config::get('app.fileSystemDriver') . '/property-photos/' . $propertyBrand['property_id'] . "/logo/" . $propertyBrand['name'] . '_250x250.' . $propertyBrand['logo_file_ext']
                : null;

            $roomOrder = 1;
            $bookingChannelRoom = [];
            foreach ($bookingData['booking_room'] as $bookingRoom) {

                if (!empty($bookingRoom['room_rate_mapping']['property_room'])) {
                    $bookingRoom['room_name'] = $bookingRoom['room_rate_mapping']['property_room']['name'];
                }
                if (!empty($bookingRoom['room_rate_mapping']['property_room_rate'])) {
                    $bookingRoom['room_rate_name'] = $bookingRoom['room_rate_mapping']['property_room_rate']['name'];
                }

                $extraParam = null;
                if (!empty($bookingRoom['extra_param'])) {
                    $extraParamDecode = json_decode($bookingRoom['extra_param'], 1);

                    foreach ($extraParamDecode as $extraParamKey => $extraParamValue) {

                        $extraParamTitle = explode('_', $extraParamKey);
                        foreach ($extraParamTitle as $extraParamTitleKey => $extraParamTitleValue) {
                            $extraParamTitle[$extraParamTitleKey] = ucwords($extraParamTitleValue);
                        }
                        $extraParamTitle = implode(' ', $extraParamTitle);

                        $extraParam[$extraParamKey] = [
                            'title' => $extraParamTitle,
                            'value' => $extraParamValue,
                        ];
                    }

                }

                $additionalFee = null;
                if (!empty($bookingRoom['rate_detail'])) {
                    $rateDetail = json_decode($bookingRoom['rate_detail'], 1);
                    if(isset($rateDetail['taxes']) && $bookingData['channel_manager_id'] == 2) {
                        $additionalFee = $rateDetail['taxes'];
                    }
                }

                $bookingChannelRoom[] = [
                    'roomOrder' => $roomOrder,
                    'roomName' => $bookingRoom['room_name'],
                    'roomRateName' => $bookingRoom['room_rate_name'],
                    'occupancyCode' => $bookingRoom['occupancy_code'],
                    'occupancyText' => occupancyCodeFormatted($bookingRoom['occupancy_code']),
                    'amount' => $bookingRoom['amount'],
                    'discount_amount' => $bookingRoom['discount_amount'],
                    'total' => $bookingRoom['total'],
                    'currencyCode' => $bookingRoom['currency_code'],
                    'dailyAmount' => !empty($bookingRoom['daily_amount']) ? json_decode($bookingRoom['daily_amount'],1) : null,
                    'extraParam' => $extraParam,
                    'occupancyFormatted' => occupancyCodeFormatted($bookingRoom['occupancy_code']),
                    'additionalFee' => $additionalFee
                ];

                //$bookingChannelRoom[] = $roomOrder . '. ' . $bookingRoom['room_name'] . ' - ' . $bookingRoom['room_rate_name'] . ' - ' . occupancyCodeFormatted($bookingRoom['occupancy_code']);
                $roomOrder++;
            }

            $userData = $bookingData['booking_property']['property_user'];
            $firstUserData = reset($userData);

            if (in_array($bookingData['property_booking_channel']['channel_category_id'], [2,3])) {
                $bookingLanguageCode = fillOnUndefined($bookingData['booking_contact'], 'language_code', 'en');
            }else {
                $bookingLanguageCode = fillOnUndefined($firstUserData['user'], 'language', 'en');
            }

            $bookingChannelPaymentType = __('property_booking_payment_type-pay_at_hotel',[],$bookingLanguageCode);
            $bookingChannelPaymentSource = null;
            if ($bookingData['booking_payment']['payment_type_code'] == 'CRD') {
                $bookingChannelPaymentType = __('property_booking_payment_type-credit_card',[],$bookingLanguageCode);
                if ($bookingData['booking_payment']['payment_source_code'] == 'OTA') {
                    $bookingChannelPaymentSource = __('enw-ota-credit_card',[],$bookingLanguageCode);
                }
                if ($bookingData['booking_payment']['payment_source_code'] == 'GST') {
                    $bookingChannelPaymentSource = __('enw-guest-credit_card',[],$bookingLanguageCode);
                }
            }

            $creditCardInformation = null;
            if (!is_null($bookingData['booking_payment']['extra_param'])) {
                $paymentData = json_decode($bookingData['booking_payment']['extra_param'], 1);

                if (isset($paymentData['attributes']['guarantee'])) {
                    $creditCardInformation['cardNumber'] = isset($paymentData['attributes']['guarantee']['card_number']) ? $paymentData['attributes']['guarantee']['card_number'] : null;
                    $creditCardInformation['cardHolderName'] = isset($paymentData['attributes']['guarantee']['cardholder_name']) ? $paymentData['attributes']['guarantee']['cardholder_name'] : null;
                    $creditCardInformation['expirationDate'] = isset($paymentData['attributes']['guarantee']['expiration_date']) ? $paymentData['attributes']['guarantee']['expiration_date'] : null;
                    $creditCardInformation['cvv'] = isset($paymentData['attributes']['guarantee']['cvv']) ? $paymentData['attributes']['guarantee']['cvv'] : null;
                }
            }

            //Genius Member
            $bookingContactExtraParam = null;
            if(!empty($bookingData['booking_contact']['extra_param'])) {
                $bookingContactExtraParam = json_decode($bookingData['booking_contact']['extra_param'],1);
            }
            $isBookingGenius = false;
            if(isset($bookingContactExtraParam['is_genius']) && $bookingContactExtraParam['is_genius']) {
                $isBookingGenius = true;
            }

            $mailParams = [
                'bookingId' => $bookingData['id'],
                'bookingCode' => $bookingData['booking_code'],
                'propertyId' => $bookingData['booking_property']['id'],
                'booking_code' => $bookingData['booking_code'],
                'search_key' => $bookingData['search_key'],
                'channel_token' => $bookingData['channel_token'],
                'booking_engine_token' => $bookingData['booking_engine_token'],
                'checkin_date' => Carbon::parse($bookingData['checkin_date'])->format('d.m.Y'),
                'checkout_date' => Carbon::parse($bookingData['checkout_date'])->format('d.m.Y'),
                'payment_type_code' => $bookingData['booking_payment']['payment_type_code'],
                'payment_source_code' => $bookingData['booking_payment']['payment_source_code'],
                'room_amount' => $bookingData['room_amount'],
                'addon_amount' => $bookingData['addon_amount'],
                'discount_amount' => $bookingData['discount_amount'],
                'total' => $bookingData['total'],
                'currency_code' => $bookingData['currency_code'],
                'name_surname' => $bookingData['booking_contact']['nameSurname'],
                'countryCode' => upperCase($bookingData['booking_contact']['country_code']),
                'email' => $bookingData['booking_contact']['email'],
                'property_name' => $bookingData['booking_property']['name'],
                'url' => $hostAddress,
                'logo' => $bookingData['booking_property']['property_brand']['logoUrl'],
                'language_code' => $bookingData['booking_contact']['language_code'],
                'bookingChannelId' => $bookingData['channel_id'],
                'bookingChannelName' => fillOnUndefined($bookingData['property_booking_channel'], 'name'),
                'bookingChannelCategoryId' => $bookingData['property_booking_channel']['channel_category_id'],
                'bookingChannelCode' => $bookingData['channel_booking_code'],
                'bookingChannelContactNameSurname' => $bookingData['booking_contact']['nameSurname'],
                'bookingChannelContactEmail' => $bookingData['booking_contact']['email'],
                'bookingChannelContactPhone' => $bookingData['booking_contact']['phone_number'],
                'bookingChannelNote' => $bookingData['booking_contact']['note'],
                'bookingChannelRoom' => $bookingChannelRoom,
                'bookingChannelPaymentType' => $bookingChannelPaymentType,
                'bookingChannelPaymentSource' => $bookingChannelPaymentSource,
                'creditCardInformation' => $creditCardInformation,
                'isBookingGenius' => $isBookingGenius
            ];

            //Mail Contact Data
            $reservationExecutives = [];
            if (isset($bookingData['booking_property']['property_executive'])) {
                $reservationExecutives = collect($bookingData['booking_property']['property_executive'])
                    ->where('executive_type_id', '=', '7') // sadece rezervasyon yetkisi olanlar ...
                    ->values()->all();
            }

            foreach ($reservationExecutives as $reservationExecutive) {
                $bcc[] = $reservationExecutive['email'];
            }
            $bcc[] = "channel@extranetwork.com";

            foreach ($userData as $user) {
                if ($user['user']['email'] != $firstUserData['user']['email']) {
                    $bcc[] = $user['user']['email'];
                }
            }

            //Booking Engine ve Offline Channel to Customer Info's
            if (in_array($bookingData['property_booking_channel']['channel_category_id'], [2,3])) {
                $mailData = [
                    'to' => [
                        'name' => $bookingData['booking_contact']['nameSurname'],
                        'email' => $bookingData['booking_contact']['email']
                    ]
                ];
            } else {
                $mailData = [
                    'to' => [
                        'name' => $bookingData['booking_property']['name'],
                        'email' => $firstUserData['user']['email']
                    ]
                ];
            }

            $mailData['bcc'] = $bcc;


            $mailSenderAddress = Config::get('app.mailSenderAddress');
            //app('translator')->setLocale(fillOnUndefined($firstUserData['user'], 'language', 'tr'));
            app('translator')->setLocale($bookingLanguageCode);

            $mailParams['showCreditCardUrl'] = null;
            if(!empty($mailParams['creditCardInformation'])) {
                $mailParams['showCreditCardUrl'] = Config::get('app.client_server').'/app/network/reservation/'.$mailParams['bookingId'].'?propertyid='.$mailParams['propertyId'];
            }

            /*echo view('emails.cancelBookingMail', compact('mailParams'));
            die();*/

            return $this->from($mailSenderAddress, 'Extranetwork - ' . $mailParams['property_name'])
                ->view('emails.cancelBookingMail', compact('mailParams'))
                ->to($mailData['to']["email"], $mailData['to']["name"])
                ->bcc($mailData['bcc'])
                ->subject(__('api-malling-booking-cancel_booking-title', ['channel' => $mailParams['bookingChannelName']]))
                ->with(['message' => $this]);


        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            return output(['status' => -1, 'message' => $e->getMessage()]);
        }
    }

}
