<?php

/**
 * Mail is never sent inline: routes queue it and bin/send_queue.php delivers it
 * from cron, so a slow SMTP server can never hang a ticket submission.
 */
final class Mailer
{
    public static function queue(string $to, string $subject, string $bodyHtml, ?int $ticketId = null): void
    {
        if (trim($to) === '') {
            return;
        }
        DB::run(
            'INSERT INTO email_queue (to_email, subject, body_html, ticket_id) VALUES (?,?,?,?)',
            [$to, $subject, $bodyHtml, $ticketId]
        );
    }

    public static function queueToSupport(string $subject, string $bodyHtml, ?int $ticketId = null): void
    {
        self::queue((string) Config::setting('support_email', ''), $subject, $bodyHtml, $ticketId);
    }

    /** Minimal RTL HTML wrapper for outgoing mail. */
    public static function template(string $heading, array $rows, ?string $footer = null): string
    {
        $html = '<div dir="rtl" style="font-family:Arial,Helvetica,sans-serif;font-size:15px;color:#1c1c1c">'
              . '<h2 style="margin:0 0 16px;font-size:19px;font-weight:600">' . htmlspecialchars($heading) . '</h2>'
              . '<table cellpadding="6" cellspacing="0" style="border-collapse:collapse">';
        foreach ($rows as $label => $value) {
            $html .= '<tr>'
                  . '<td style="color:#5a5a5a;vertical-align:top;white-space:nowrap">' . htmlspecialchars((string) $label) . '</td>'
                  . '<td style="font-weight:600">' . nl2br(htmlspecialchars((string) $value)) . '</td>'
                  . '</tr>';
        }
        $html .= '</table>';
        if ($footer) {
            $html .= '<p style="margin-top:20px;color:#5a5a5a;font-size:13px">' . htmlspecialchars($footer) . '</p>';
        }
        return $html . '</div>';
    }

    /** Delivers one message. Used by bin/send_queue.php only. */
    public static function send(string $to, string $subject, string $bodyHtml): void
    {
        $from     = Config::setting('mail_from', 'helpdesk@localhost');
        $fromName = Config::setting('mail_from_name', 'HelpDesk');
        $host     = trim((string) Config::setting('smtp_host', ''));

        if ($host === '') {
            $headers = "MIME-Version: 1.0\r\nContent-Type: text/html; charset=utf-8\r\n"
                     . 'From: =?UTF-8?B?' . base64_encode($fromName) . "?= <{$from}>\r\n";
            if (!mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=', $bodyHtml, $headers)) {
                throw new RuntimeException('mail() failed');
            }
            return;
        }
        self::smtpSend($host, $to, $subject, $bodyHtml, $from, $fromName);
    }

    private static function smtpSend(string $host, string $to, string $subject, string $body,
                                     string $from, string $fromName): void
    {
        $port = (int) Config::setting('smtp_port', '587');
        $user = (string) Config::setting('smtp_user', '');
        $pass = (string) Config::setting('smtp_pass', '');

        $fp = @stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, 15);
        if (!$fp) {
            throw new RuntimeException("SMTP connect failed: {$errstr}");
        }
        stream_set_timeout($fp, 15);

        $lastResponse = '';
        $read = function () use ($fp, &$lastResponse): string {
            $data = '';
            while (($line = fgets($fp, 1024)) !== false) {
                $data .= $line;
                if (strlen($line) < 4 || $line[3] === ' ') {
                    break;
                }
            }
            $lastResponse = $data;
            return $data;
        };
        $cmd = function (string $line, string $expect) use ($fp, $read): void {
            fwrite($fp, $line . "\r\n");
            $res = $read();
            if (strncmp($res, $expect, strlen($expect)) !== 0) {
                throw new RuntimeException('SMTP: ' . trim($res));
            }
        };

        $read();
        $cmd('EHLO ' . gethostname(), '250');

        // Upgrade whenever the server offers it, whatever the port. Microsoft 365
        // direct send on port 25 advertises STARTTLS and this keeps it encrypted.
        if (stripos($lastResponse, 'STARTTLS') !== false) {
            $cmd('STARTTLS', '220');
            if (!stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                throw new RuntimeException('STARTTLS failed');
            }
            $cmd('EHLO ' . gethostname(), '250');
        } elseif ($port !== 25) {
            throw new RuntimeException('Server did not offer STARTTLS on port ' . $port);
        }

        if ($user !== '') {
            $cmd('AUTH LOGIN', '334');
            $cmd(base64_encode($user), '334');
            $cmd(base64_encode($pass), '235');
        }
        $cmd("MAIL FROM:<{$from}>", '250');
        $cmd("RCPT TO:<{$to}>", '250');
        $cmd('DATA', '354');

        $headers = 'From: =?UTF-8?B?' . base64_encode($fromName) . "?= <{$from}>\r\n"
                 . "To: <{$to}>\r\n"
                 . 'Subject: =?UTF-8?B?' . base64_encode($subject) . "?=\r\n"
                 . 'Date: ' . date('r') . "\r\n"
                 . "MIME-Version: 1.0\r\n"
                 . "Content-Type: text/html; charset=utf-8\r\n"
                 . "Content-Transfer-Encoding: base64\r\n";
        $payload = $headers . "\r\n" . chunk_split(base64_encode($body));
        $cmd($payload . "\r\n.", '250');
        fwrite($fp, "QUIT\r\n");
        fclose($fp);
    }
}
