<?php
/**
 * Mailer wrapper that prefers SMTP via .env using PHPMailer, with mail() fallback.
 * Does not throw; returns boolean.
 */

if (!class_exists('TonEnv')) {
    $envPath = __DIR__ . '/Env.php';
    if (is_file($envPath)) { require_once $envPath; }
}

// Load PHPMailer if available (vendor or legacy path)
if (!class_exists('PHPMailer\\PHPMailer\\PHPMailer')) {
    $vendorBase = dirname(__DIR__) . '/vendor/phpmailer/phpmailer/src';
    if (is_file($vendorBase . '/PHPMailer.php')) {
        require_once $vendorBase . '/PHPMailer.php';
        require_once $vendorBase . '/SMTP.php';
        require_once $vendorBase . '/Exception.php';
    } else {
        $legacyBase = dirname(__DIR__) . '/PHPMailer';
        if (is_file($legacyBase . '/PHPMailer.php')) {
            require_once $legacyBase . '/PHPMailer.php';
            require_once $legacyBase . '/SMTP.php';
            require_once $legacyBase . '/Exception.php';
        }
    }
}

class Mailer {
    /**
     * Send an email (HTML)
     * @param string $to
     * @param string $subject
     * @param string $htmlBody
     * @param string $textBody
     * @return bool
     */
    public function sendEmail($to, $subject, $htmlBody, $textBody = '') {
        $envHost = class_exists('TonEnv') ? TonEnv::get('MAILER_HOST', '') : '';
        $envUser = class_exists('TonEnv') ? TonEnv::get('MAILER_USERNAME', '') : '';
        $envPass = class_exists('TonEnv') ? TonEnv::get('MAILER_PASSWORD', '') : '';
        $envPort = (int)(class_exists('TonEnv') ? TonEnv::get('MAILER_PORT', '587') : 587);
        $envFrom = class_exists('TonEnv') ? TonEnv::get('MAILER_FROM', $envUser) : '';
        $envFromName = class_exists('TonEnv') ? TonEnv::get('MAILER_FROM_NAME', 'First De France Bank') : 'First De France Bank';
        $envEnc = strtolower((string)(class_exists('TonEnv') ? TonEnv::get('MAILER_ENCRYPTION', '') : ''));

        if ($envHost && $envUser && $envPass && class_exists('PHPMailer\\PHPMailer\\PHPMailer')) {
            try {
                $m = new PHPMailer\PHPMailer\PHPMailer(true);
                $m->isSMTP();
                $m->Host = $envHost;
                $m->SMTPAuth = true;
                $m->Username = $envUser;
                $m->Password = $envPass;
                if ($envEnc === 'ssl' || $envPort === 465) {
                    $m->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
                } else {
                    $m->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
                }
                $m->Port = $envPort ?: 587;
                $m->setFrom($envFrom ?: $envUser, $envFromName);
                $m->addAddress($to);
                $m->isHTML(true);
                $m->Subject = $subject;
                $m->Body = $htmlBody;
                $m->AltBody = $textBody !== '' ? $textBody : strip_tags($htmlBody);
                $m->send();
                return true;
            } catch (\Throwable $e) {
                // fallthrough to mail()
            }
        }

        $fromHost = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $from = ($envFrom ?: ('no-reply@' . preg_replace('/:\\d+$/', '', $fromHost)));
        $headers = [];
        $headers[] = 'MIME-Version: 1.0';
        $headers[] = 'Content-Type: text/html; charset=UTF-8';
        $headers[] = 'From: ' . $from;
        $headers[] = 'Reply-To: ' . $from;
        $headersStr = implode("\r\n", $headers);
        return @mail($to, $subject, $htmlBody, $headersStr);
    }
}
?>
