<?php

namespace App\Utility;

use App\Jobs\SendEmailJob;
use App\Mail\SendEmail;
use Illuminate\Support\Facades\Mail;

class Email
{

    private bool $is_queue_enable = false;

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

    public function __construct()
    {
        $this->is_queue_enable = config('app.IS_QUEUE_ENABLE');
    }

    public function send($data, $email_subject, $from, $attachment, $template, $to)
    {
        if ($this->is_queue_enable == 1) {
            dispatch((new SendEmailJob($data, $email_subject, $from, $attachment, $template, $to)));
        } else {
            $this->sendEmailManually($data, $email_subject, $from, $attachment, $template, $to);
        }
    }

    private function sendEmailManually($data, $email_subject, $from, $attachment, $template, $to) : void
    {
        try{
            if(empty($to)){
                throw new \Exception("Recipient email is missing.");
            }

            Mail::to($to)->send(
                new SendEmail(
                    $data,
                    $email_subject,
                    $from,
                    $attachment,
                    $template
                )
            );
            $this->result['message'] = 'E-Mail has been send successfully.';
            $this->result['status'] = true;

            @unlink($attachment);

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

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

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