<?php
declare(strict_types=1);

/**
 * /functional/notifications/email.php
 *
 * Відповідає за:
 * - низькорівневу відправку email для модуля сповіщень
 * - спробу використати наявний includes/mailer.php
 * - fallback на стандартний mail(), якщо helper не знайдено
 *
 * Функції файла:
 * - notif_mailer_boot()
 * - notif_mailer_available()
 * - notif_send_email()
 * - notif_email_plain_text()
 */

if (!function_exists('notif_mailer_boot')) {
    function notif_mailer_boot(): void
    {
        static $booted = false;
        if ($booted) {
            return;
        }
        $booted = true;

        $mailerFile = dirname(__DIR__, 2) . '/includes/mailer.php';
        if (is_file($mailerFile)) {
            require_once $mailerFile;
        }
    }
}

if (!function_exists('notif_email_plain_text')) {
    function notif_email_plain_text(string $html): string
    {
        $text = preg_replace('~<br\s*/?>~i', "\n", $html);
        $text = preg_replace('~</p>~i', "\n\n", (string)$text);
        $text = strip_tags((string)$text);
        $text = html_entity_decode((string)$text, ENT_QUOTES, 'UTF-8');
        $text = preg_replace("/\r\n|\r/u", "\n", (string)$text);
        $text = preg_replace("/\n{3,}/u", "\n\n", (string)$text);
        return trim((string)$text);
    }
}

if (!function_exists('notif_mailer_try_function')) {
    function notif_mailer_try_function(string $func, string $to, string $subject, string $html, string $text): bool
    {
        if (!function_exists($func)) {
            return false;
        }

        try {
            $rf = new ReflectionFunction($func);
            $required = $rf->getNumberOfRequiredParameters();
            $total    = $rf->getNumberOfParameters();

            if ($required <= 4 && $total >= 4) {
                $res = $rf->invokeArgs([$to, $subject, $html, $text]);
                return $res !== false;
            }

            if ($required <= 3 && $total >= 3) {
                $res = $rf->invokeArgs([$to, $subject, $html]);
                return $res !== false;
            }
        } catch (Throwable $e) {
            error_log('notifications/email.php helper ' . $func . ' failed: ' . $e->getMessage());
        }

        return false;
    }
}

if (!function_exists('notif_mailer_available')) {
    function notif_mailer_available(): bool
    {
        notif_mailer_boot();

        $candidates = [
            'send_mail',
            'vm_send_mail',
            'app_send_mail',
            'mailer_send',
            'sendEmail',
        ];

        foreach ($candidates as $func) {
            if (function_exists($func)) {
                return true;
            }
        }

        return function_exists('mail');
    }
}

if (!function_exists('notif_send_email')) {
    function notif_send_email(string $to, string $subject, string $html, string $text = ''): bool
    {
        $to = trim($to);
        $subject = trim($subject);
        $html = trim($html);
        $text = trim($text);

        if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
            return false;
        }

        if ($subject === '' || $html === '') {
            return false;
        }

        notif_mailer_boot();

        if ($text === '') {
            $text = notif_email_plain_text($html);
        }

        $candidates = [
            'send_mail',
            'vm_send_mail',
            'app_send_mail',
            'mailer_send',
            'sendEmail',
        ];

        foreach ($candidates as $func) {
            if (notif_mailer_try_function($func, $to, $subject, $html, $text)) {
                return true;
            }
        }

        $headers = [];
        $headers[] = 'MIME-Version: 1.0';
        $headers[] = 'Content-type: text/html; charset=UTF-8';
        $headers[] = 'X-Mailer: VMEREGI Notifications';

        return @mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=', $html, implode("\r\n", $headers));
    }
}