<?php

namespace App\Mails\ScheduledTaskMail;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use App\Exceptions\SystemErrorException;

class SendScheduledMail
{

    /**
     * Sends an email with the specified parameters.
     *
     * This method is a wrapper for the private `sendMail` method, and it is used to send an email with the
     * provided recipient, subject, content, and an optional attachment.
     *
     * @tag srm_schdular
     */
    public static function mail($to, $subject, $content, $attachment)
    {
        static::sendMail($to, $subject, $content, $attachment);
    }


    /**
     * Sends an email with the specified parameters and attachment.
     *
     * This method sends an email with the given recipient, subject, content, and attachment. If the attachment
     * file does not exist, it logs an error and throws an exception. If the attachment exists, it is included
     * in the email.
     *
     * @tag srm_schdular
     */
    private static function sendMail($to, $subject, $content, $attachment)
    {
        if(!file_exists($attachment)){

            Log::error("Pdf file not found: $attachment");

            throw new \Exception("Pdf file not found: $attachment");

        }

        Mail::send([], [], function ($message) use ($to, $subject, $content, $attachment) {

            $message->to($to)
                ->subject($subject)
                ->html(nl2br($content));
            if(file_exists($attachment)) {
                $message->attach($attachment);
            }

        });
    }
}
