<?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;

use Exception;

class BookingTicketMail 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');

            $requestData = [
                'criteria' => [
                    ['field' => 'id', 'condition' => '=', 'value' => $params['booking_id']]
                ],
                'with' => ['bookingProperty.propertyExecutive', 'bookingProperty.propertyBookingEngineToken', 'bookingProperty.propertyBrand', 'bookingContact', 'bookingChannel', 'bookingPayment', 'bookingPaymentType', 'bookingStatus'],
                'firstRow' => true
            ];

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

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

            $booking = $booking['data'];

            $locale = fillOnUndefined($params, 'locale', 'en');
            if (!is_null($params['user'])) {
                $locale = $booking['booking_contact']['language_code'];
            }
            app('translator')->setLocale($locale);

            $propertyLogo = 'https://www.extranetwork.com/assets/img/logo/mini-logo.png';
            if (isset($booking['booking_property']['property_brand']['logo_name'])) {
                $propertyLogo = Config::get('app.imageUrl') . '/property-photos/' . $booking['booking_property']['id'] . "/logo/" . $booking['booking_property']['property_brand']['logo_name'] . '_250x250.' . $booking['booking_property']['property_brand']['logo_file_ext'];
            }

            $bookingContact = [
                'mail' => $booking['booking_contact']['email'],
                'nameSurname' => $booking['booking_contact']['nameSurname'],
            ];

            if (!isset($booking['booking_property']['property_executive'])) {
                throw new ApiErrorException(lang('Property Executive not found'));
            }

            $propertyExecutives = collect($booking['booking_property']['property_executive'])->where('status', 1)->where('executive_type_id', 7)->pluck('email')->toArray();

            $params['subject'] = __('api-mailing-booking_ticket-subject', ['booking_code' => $booking['booking_code']]);//'Booking Ticket Message: ' . $booking['booking_code'];
            $params['mailSenderName'] = 'Extranetwork - ' . $booking['booking_property']['name'];

            if (!is_null($params['user'])) {

                $mailParams = [
                    'to' => $bookingContact['mail'],
                    'toNameSurname' => $bookingContact['mail'],
                    'bcc' => [],
                    'title' => __('general-hi') . ', ' . $bookingContact['nameSurname'],
                    'logo' => $propertyLogo,
                    'message' => __('api-mailing-booking_ticket-message-user', ['booking_code' => $booking['booking_code']]),
                    'btnTitle' => __('api-mailing-booking_ticket-btn-message'),
                    'btnUrl' => config('app.bookingEngineUrl') . '/' . $booking['booking_property']['property_booking_engine_token']['token'] . '/' . $locale . '/booking-detail/' . $booking['booking_code'],
                ];

            } else {

                if (empty($propertyExecutives)) {
                    throw new ApiErrorException(lang('Property Executive not found'));
                }

                $mailParams = [
                    'to' => $propertyExecutives[0],
                    'toNameSurname' => null,
                    'bcc' => $propertyExecutives,
                    'title' => __('general-hi') . ',',
                    'logo' => $propertyLogo,
                    'message' => __('api-mailing-booking_ticket-message-enw-user', ['booking_code' => $booking['booking_code'], 'property_name' => $booking['booking_property']['name']]),
                    'btnTitle' => __('api-mailing-booking_ticket-btn-message'),
                    'btnUrl' => config('app.client_server') . '/app/network/reservation/' . $booking['id'].'?propertyid='.$booking['property_id'],
                ];

            }

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

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

            return $this->from($mailSenderAddress, $params['mailSenderName'])
                ->view('emails.bookingTicketMail', compact('mailParams'))
                ->to($mailParams['to'], $mailParams['toNameSurname'])
                ->bcc($bcc)
                ->subject($params['subject']);


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

    }

}
