<?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 BookingPropertyAddonUpdateMail 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");

            $propertyParam = [
                'criteria' => [
                    ['field' => 'id', 'condition' => '=', 'value' => $params['propertyId']],
                ],
                'with' => ['propertyBrand', 'propertyExecutive', 'propertyUser.user','propertyBookingEngineToken'],
                'firstRow' => true
            ];

            $property = $propertyService->select($propertyParam);
            if ($property['status'] != 'success') {
                throw new ApiErrorException($property['message']);
            }

            $property = $property['data'];

            //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'],
                'addonLanguageKey' => $params['addonLanguageKey'],
                'logo' => $property['property_brand']['logoUrl'],
                'btnUrl' => config('app.bookingEngineUrl') . '/' . $property['property_booking_engine_token']['token'] . '/' . $locale . '/booking-detail/' . $params['bookingCode'],
            ];

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


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

}
