<?php

namespace App\Jobs;

use App\Mail\SendEmail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

class SendEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private  array $result = [];
    private array $logData = [];

    private $data, $email_subject,$from_email, $attachment, $template,$to;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data, $email_subject,$from, $attachment, $template,$to)
    {
        $this->data = $data;
        $this->email_subject = $email_subject;
        $this->from_email = $from;
        $this->attachment = $attachment;
        $this->template = $template;
        $this->to = $to;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{
            if(empty($this->to)){
                throw new \Exception("Recipient email is missing.");
            }
                Mail::to($this->to)->send(
                    new SendEmail(
                        $this->data,
                        $this->email_subject,
                        $this->from_email,
                        $this->attachment,
                        $this->template
                    )
                );
                $this->result['message'] = 'E-Mail has been send successfully.';
                $this->result['status'] = true;

                @unlink($this->attachment);

        }catch (\Throwable $ex){
           $this->result['message'] = $ex->getMessage();
           $this->result['status'] = false;
        }

        $this->logData['SEND_EMAIL'] = $this->prepareLogData();
        appLog($this->logData);
    }

    private function prepareLogData(){
        return [
            'sending_info' => [
                'from' => $this->from_email,
                'to' => $this->to,
                'subject' => $this->email_subject
            ],
            'response' => $this->result
        ];
    }
}
