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


            $bookingService = App::make("App\Core\Service\BookingService");

            $bookingDetailParam = [
                'criteria' => [
                    ['field' => 'booking_code', 'condition' => '=', 'value' => $params['bookingCode']],
                ],
                'with' => ['property.propertyBrand', 'property.propertyExecutive', 'property.propertyUser.user','property.propertyBookingEngineToken'],
                'firstRow' => true
            ];

            $bookingDetail = $bookingService->select($bookingDetailParam);
            if ($bookingDetail['status'] != 'success') {
                throw new ApiErrorException($bookingDetail['message']);
            }

            $bookingDetail = $bookingDetail['status'] == 'success' && !empty($bookingDetail['data']) ? $bookingDetail['data'] : null;


            $property = $bookingDetail['property'];


            //Mail Contact Data
            $reservationExecutives = [];
            if (isset($property['property_executive'])) {
                $reservationExecutives = collect($property['property_executive'])
                    ->where('executive_type_id', '=', '7')
                    ->values()->all();
            }

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


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

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

            $mailData = [
                'to' => [
                    'name' => $firstUserData['user']['nameSurname'],
                    'email' => $firstUserData['user']['email'],
                ],
                'bcc' => $bcc

            ];

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


            $mailParams = [
                'propertyName' => $property['name'],
                'bookingCode' => $params['bookingCode'],
                'logo' => $property['property_brand']['logoUrl'],
                'btnUrl' => config('app.bookingEngineUrl') . '/' . $property['property_booking_engine_token']['token'] . '/' . $locale . '/booking-detail/' . $params['bookingCode'],
            ];

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

            return $this->from($mailSenderAddress, 'Extranetwork - ' . $mailParams['propertyName'])
                ->view('emails.bookingInvoiceUpdateMail', compact('mailParams'))
                ->to($mailData['to']["email"], $mailData['to']["name"])
                ->bcc($mailData['bcc'])
                ->subject(__('api-mailing-booking-invoice_update-title', ['bookingCode' => $mailParams['bookingCode']]))
                ->with(['message' => $this]);


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

}
