<?php
// Depto de Engenharia e Automação - Master Automação - Autor: Derlivon Silva
// Cliente SMTP minimalista via streams nativos do PHP. Sem PHPMailer.
// Suporta STARTTLS (Gmail, Outlook, etc).

namespace App\Services\Backup;

class SmtpClient
{
    public static function enviar(array $cfg, string $assunto, string $corpoHtml): array
    {
        $host = $cfg['smtp_host'] ?? '';
        $port = (int)($cfg['smtp_port'] ?? 587);
        $user = $cfg['smtp_user'] ?? '';
        $pass = $cfg['smtp_pass'] ?? '';
        $de   = $cfg['de']   ?? $user;
        $para = $cfg['para'] ?? '';
        if ($host === '' || $user === '' || $pass === '' || $para === '') {
            return ['ok'=>false, 'erro'=>'SMTP não configurado'];
        }

        $sock = @stream_socket_client('tcp://' . $host . ':' . $port, $errno, $errstr, 15);
        if (!$sock) return ['ok'=>false, 'erro'=>"connect $host:$port falhou: $errstr"];
        stream_set_timeout($sock, 15);

        $read = function() use ($sock) {
            $r = ''; while (!feof($sock)) { $l = fgets($sock, 512); if ($l === false) break; $r .= $l; if (substr($l, 3, 1) === ' ') break; } return $r;
        };
        $send = function($cmd) use ($sock, $read) { fwrite($sock, $cmd . "\r\n"); return $read(); };

        $log = $read();
        $log .= $send('EHLO ' . gethostname());
        // STARTTLS
        $log .= $send('STARTTLS');
        if (!stream_socket_enable_crypto($sock, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
            fclose($sock); return ['ok'=>false, 'erro'=>'TLS falhou'];
        }
        $log .= $send('EHLO ' . gethostname());
        $log .= $send('AUTH LOGIN');
        $log .= $send(base64_encode($user));
        $log .= $send(base64_encode($pass));
        if (strpos($log, '235') === false) { fclose($sock); return ['ok'=>false, 'erro'=>'AUTH falhou: ' . substr($log, -200)]; }
        $log .= $send('MAIL FROM:<' . $de . '>');
        $log .= $send('RCPT TO:<' . $para . '>');
        $log .= $send('DATA');

        $headers = "From: Premium Express BI <" . $de . ">\r\n"
                 . "To: <" . $para . ">\r\n"
                 . "Subject: " . self::utf8Header($assunto) . "\r\n"
                 . "MIME-Version: 1.0\r\n"
                 . "Content-Type: text/html; charset=UTF-8\r\n"
                 . "Content-Transfer-Encoding: 8bit\r\n";
        fwrite($sock, $headers . "\r\n" . $corpoHtml . "\r\n.\r\n");
        $log .= $read();
        $send('QUIT');
        fclose($sock);
        $ok = strpos($log, '250') !== false;
        return ['ok'=>$ok, 'erro'=>$ok ? null : substr($log, -300)];
    }

    private static function utf8Header(string $s): string
    {
        return '=?UTF-8?B?' . base64_encode($s) . '?=';
    }
}
