<?php

namespace App\Core\Mail;

use App\Exceptions\ApiErrorException;
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 BookingCancellationRequestMail 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;
            $mailSenderAddress = Config::get('app.mailSenderAddress');
            $bookingService = App::make('App\Core\Service\BookingService');
            $userService = App::make('App\Core\Service\UserService');

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

            $bookingDetail = $bookingService->select($requestData);

            if ($bookingDetail['status'] != 'success' || empty($bookingDetail['data'])) {
                throw new ApiErrorException('Booking not found.');
            }

            $bookingDetail = $bookingDetail['data'];


            //Language
            $userData = $bookingDetail['booking_property']['property_user'];
            $firstUserData = reset($userData);
            $bookingLanguageCode = fillOnUndefined($firstUserData['user'], 'language', 'en');


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

            $reservationExecutives = [];
            if (isset($bookingDetail['booking_property']['property_executive'])) {
                $reservationExecutives = collect($bookingDetail['booking_property']['property_executive'])
                    ->where('executive_type_id', '=', '7')
                    ->values()->all();
            }

            foreach ($reservationExecutives as $reservationExecutive) {
                $bcc[] = $reservationExecutive['email'];
            }

            $mailData = [
                'to' => [
                    'name' => $bookingDetail['booking_property']['name'],
                    'email' => $firstUserData['user']['email']
                ]
            ];


            $mailParams = [
                'to' => $firstUserData['user']['email'],
                'bcc' => $bcc,
                'toNameSurname' => $bookingDetail['booking_property']['name'],
                'bookingContactNameSurname' => $bookingDetail['booking_contact']['nameSurname'],
                'bookingCode' => fillOnUndefined($bookingDetail, 'booking_code'),
                'locale' => $bookingLanguageCode,
            ];

            $mailParams['detailUrl'] = config('app.client_server').'/app/network/reservation/'.$bookingDetail['id'].'?propertyid='.$bookingDetail['property_id'];

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

            $mailParams['bcc'][] = 'channel@extranetwork.com';

            return $this->from($mailSenderAddress, 'Extranetwork')
                ->view('emails.bookingCancellationRequest', compact('mailParams'))
                ->to($mailParams['to'], $mailParams['toNameSurname'])
                ->bcc($mailParams['bcc'])
                ->subject(__('api-mailing-cancellation_request-subject', ['bookingCode' => $mailParams['bookingCode']], $mailParams['locale']));


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

}
