<?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 BookingCancellationConfirmCodeMail 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' => ['bookingProperty.propertyBrand', 'bookingContact'],
                'firstRow' => true
            ];

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

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

            $bookingDetail = $bookingDetail['data'];

            $mailParams = [
                'to' => $bookingDetail['booking_contact']['email'],
                'toNameSurname' => $bookingDetail['booking_contact']['nameSurname'],
                'bcc' => [],
                'confirmCode' => $params['confirmCode'],
                'bookingId' => fillOnUndefined($bookingDetail, 'id'),
                'propertyId' => fillOnUndefined($bookingDetail, 'property_id'),
                'bookingCode' => fillOnUndefined($bookingDetail, 'booking_code'),
                'locale' => fillOnUndefined($bookingDetail['booking_contact'], 'language_code', 'en'),
            ];

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

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

            return $this->from($mailSenderAddress, 'Extranetwork')
                ->view('emails.bookingCancellationConfirmCode', compact('mailParams'))
                ->to($mailParams['to'], $mailParams['toNameSurname'])
                ->bcc($mailParams['bcc'])
                ->subject(__('api-mailing-cancellation_confirm_code-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()]);
        }
    }

}
