<?php

namespace App\Core\Service;


use App;
use App\Core\Mail\ContactFormMail;
use App\Core\Mail\EnwContactFormMail;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;
use Illuminate\Mail\Mailer;
use App\Core\Validator\EnwContactForm\EnwContactFormCreateValidator;

class EnwContactFormService
{

    private $mailer;
    private $enwContactFormCreateValidator;


    public function __construct(
        Mailer $mailer,
        EnwContactFormCreateValidator $enwContactFormCreateValidator
    ){
        $this->mailer = $mailer;
        $this->enwContactFormCreateValidator = $enwContactFormCreateValidator;
    }

    public function sendEmail($params){

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {


            $validationResult = $this->enwContactFormCreateValidator->validate($params);

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }

            $bcc[] = "bd@extranetwork.com";
            $mailData = [
                'to' => [
                    'name' => Config::get('app.name'),
                    'email' => Config::get('app.enwContactFormMailTo')
                ],
                'bcc' => $bcc
            ];

            $mailViewParams = $params ;
            $mailViewParams['logo'] = 'https://www.extranetwork.com/assets/img/logo/logo.png';

            $mailParams = [
                'mailData' => $mailData,
                'mailViewParams' => $mailViewParams
            ];


            $this->mailer->onQueue(
                'enwContactFormMail',
                new EnwContactFormMail($mailParams)
            );

            $response = [
                'status' => true,
                'data' => null,
                'message' => 'myweb-contact_form-success_message',
            ];

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

        return output($response);
    }


}
