<?php
namespace Peak;

class MailService {
    public static function send(string $to, string $subject, string $htmlBody): bool {
        $headers = "From: " . Config::$SMTP_FROM_NAME . " <" . Config::$SMTP_FROM . ">\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
        if (@mail($to, $subject, $htmlBody, $headers)) return true;

        $smtp = @fsockopen('tcp://' . Config::$SMTP_HOST, Config::$SMTP_PORT, $errno, $errstr, 10);
        if (!$smtp) return false;
        $read = function () use ($smtp) { return fgets($smtp, 512); };
        $send = function (string $cmd) use ($smtp, $read): void { fputs($smtp, "$cmd\r\n"); $read(); };
        $read(); $send('EHLO localhost'); $send('STARTTLS');
        @stream_socket_enable_crypto($smtp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
        $send('EHLO localhost'); $send('AUTH LOGIN');
        $send(base64_encode(Config::$SMTP_USER)); $send(base64_encode(Config::$SMTP_PASS));
        $send('MAIL FROM:<' . Config::$SMTP_FROM . '>'); $send('RCPT TO:<' . $to . '>');
        $send('DATA');
        fputs($smtp, "From: " . Config::$SMTP_FROM_NAME . " <" . Config::$SMTP_FROM . ">\r\nTo: <$to>\r\nSubject: $subject\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n$htmlBody\r\n.\r\n");
        $response = $read(); $send('QUIT'); fclose($smtp);
        return strpos(ltrim($response), '2') === 0;
    }
}
