<?php

namespace App\Mails;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Mail;
use App\Exceptions\SystemErrorException;
use App\Models\SMTPMails;

class SendMail
{
    public static function mail($to, $subject, $content, $headers, $attachment = null)
    {

        if(is_null(SMTPMails::defaultSmtpMail()->first())) {
            throw SystemErrorException::withMessages([
                'email' => ["SMTP server not found in the database. Please provide an SMTP server to enable email sending"],
            ]);

        }

        try {
            static::sendMail($to, $subject, $content, $headers, $attachment);

        } catch (\Exception $e) {
            throw SystemErrorException::withMessages([
                'email' => [$e->getMessage()],
            ]);
        }

    }

    // private static function sendMailNative($to, $subject, $content, $headers)
    // {
    //     mail($to, $subject, $content, $headers);
    // }

    private static function sendMail($to, $subject, $content, $headers, $attachment = null)
    {

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

            $message->to($to)
                ->subject($subject)
                ->html(nl2br($content));
        });


    }
}