<?php
/**
 * Envio de e-mail via SMTP (STARTTLS + AUTH LOGIN), sem dependências.
 * Sem SMTP_HOST configurado, enviar_email() devolve false e o chamador decide
 * o fallback (ex.: modo demonstração da recuperação de senha).
 */

require_once __DIR__ . '/config.php';

function smtp_configurado(): bool {
    return SMTP_HOST !== '' && SMTP_USER !== '' && SMTP_PASS !== '';
}

function enviar_email(string $para, string $assunto, string $html): bool {
    if (!smtp_configurado()) {
        return false;
    }
    $fp = @stream_socket_client(
        'tcp://' . SMTP_HOST . ':' . SMTP_PORT,
        $errno,
        $errstr,
        12
    );
    if (!$fp) {
        error_log("SMTP conexão falhou: $errstr");
        return false;
    }
    stream_set_timeout($fp, 12);

    $ler = function () use ($fp): string {
        $linha = '';
        while (($l = fgets($fp, 512)) !== false) {
            $linha = $l;
            if (isset($l[3]) && $l[3] === ' ') break; // fim de resposta multi-linha
        }
        return $linha;
    };
    $mandar = function (string $cmd) use ($fp, $ler): string {
        fwrite($fp, $cmd . "\r\n");
        return $ler();
    };

    try {
        $ler();
        $mandar('EHLO habitar');
        $r = $mandar('STARTTLS');
        if (!str_starts_with($r, '220')) throw new Exception("STARTTLS: $r");
        if (!stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
            throw new Exception('TLS falhou');
        }
        $mandar('EHLO habitar');
        $r = $mandar('AUTH LOGIN');
        if (!str_starts_with($r, '334')) throw new Exception("AUTH: $r");
        $mandar(base64_encode(SMTP_USER));
        $r = $mandar(base64_encode(SMTP_PASS));
        if (!str_starts_with($r, '235')) throw new Exception("Login SMTP recusado: $r");

        $mandar('MAIL FROM:<' . SMTP_USER . '>');
        $r = $mandar('RCPT TO:<' . $para . '>');
        if (!str_starts_with($r, '250')) throw new Exception("RCPT: $r");
        $mandar('DATA');

        $de = '=?UTF-8?B?' . base64_encode(SMTP_FROM_NAME) . '?= <' . SMTP_USER . '>';
        $cabecalho =
            'From: ' . $de . "\r\n" .
            'To: <' . $para . ">\r\n" .
            'Subject: =?UTF-8?B?' . base64_encode($assunto) . "?=\r\n" .
            "MIME-Version: 1.0\r\n" .
            "Content-Type: text/html; charset=UTF-8\r\n" .
            "Content-Transfer-Encoding: base64\r\n";
        $corpo = chunk_split(base64_encode($html));
        $r = $mandar($cabecalho . "\r\n" . $corpo . "\r\n.");
        if (!str_starts_with($r, '250')) throw new Exception("DATA: $r");
        $mandar('QUIT');
        fclose($fp);
        return true;
    } catch (Exception $e) {
        error_log('SMTP erro: ' . $e->getMessage());
        @fclose($fp);
        return false;
    }
}

function email_moldura(string $titulo, string $conteudo): string {
    return '<div style="background:#F6F1E7;padding:32px 16px;font-family:Georgia,serif;color:#3E3A34">'
        . '<div style="max-width:520px;margin:0 auto;background:#FBF7EE;border:1px solid #E6DCC9;'
        . 'border-radius:16px;padding:32px 28px">'
        . '<h1 style="font-size:22px;margin:0 0 16px;color:#33302A">' . $titulo . '</h1>'
        . '<div style="font-size:15px;line-height:1.7">' . $conteudo . '</div>'
        . '<p style="margin-top:28px;font-size:12px;color:#978E81">Habitar — uma casa para habitar a si mesmo.</p>'
        . '</div></div>';
}
