<?php
declare(strict_types=1);

namespace App\Helpers;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class MailHelper
{
    /**
     * Send an email using PHPMailer
     */
    public static function send(string $to, string $subject, string $body, bool $isHtml = true): bool
    {
        $mail = new PHPMailer(true);

        try {
            // Server settings
            $mail->isSMTP();
            $mail->Host = $_SERVER['MAIL_HOST'] ?? getenv('MAIL_HOST') ?: 'smtpout.secureserver.net';
            $mail->SMTPAuth = true;
            $mail->Username = $_SERVER['MAIL_USER'] ?? getenv('MAIL_USER') ?: 'noreply@lomcos.com';
            $mail->Password = $_SERVER['MAIL_PASS'] ?? getenv('MAIL_PASS') ?: 'Krishna@8';

            $port = $_SERVER['MAIL_PORT'] ?? getenv('MAIL_PORT') ?: 465;
            $mail->SMTPSecure = ($port == 465) ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = (int) $port;

            // Recipients
            $from = $_SERVER['MAIL_FROM'] ?? getenv('MAIL_FROM') ?: 'noreply@lomcos.com';
            $appName = $_SERVER['APP_NAME'] ?? getenv('APP_NAME') ?: 'BillFlow Pro';
            $mail->setFrom($from, $appName);
            $mail->addAddress($to);

            // Content
            $mail->isHTML($isHtml);
            $mail->Subject = $subject;
            $mail->Body = $body;
            $mail->AltBody = strip_tags($body);

            $mail->send();
            return true;
        } catch (Exception $e) {
            error_log("Mail Error: {$mail->ErrorInfo}");
            return false;
        }
    }
}
