<?php
declare(strict_types=1);

final class SimpleSmtpMailer {
    private $socket;
    public function __construct(private array $settings) {}
    private function read(int $expect): void { $response=''; do { $line=fgets($this->socket,515); if($line===false) throw new RuntimeException('SMTP sin respuesta.'); $response.=$line; } while(isset($line[3]) && $line[3]==='-'); if((int)substr($response,0,3)!==$expect) throw new RuntimeException('SMTP: '.trim($response)); }
    private function write(string $command,int $expect): void { fwrite($this->socket,$command."\r\n"); $this->read($expect); }
    public function send(string $subject,string $html): void {
        $host=$this->settings['host'];$port=(int)$this->settings['port'];$transport=($this->settings['encryption']??'ssl')==='ssl'?'ssl://':'';
        $this->socket=stream_socket_client($transport.$host.':'.$port,$errno,$errstr,15,STREAM_CLIENT_CONNECT);
        if(!$this->socket) throw new RuntimeException("No fue posible conectar al SMTP: $errstr");
        stream_set_timeout($this->socket,15); $this->read(220); $this->write('EHLO sonocamara.pe',250);
        $this->write('AUTH LOGIN',334); $this->write(base64_encode($this->settings['username']),334); $this->write(base64_encode($this->settings['password']),235);
        $this->write('MAIL FROM:<'.$this->settings['from_email'].'>',250); $this->write('RCPT TO:<'.$this->settings['to_email'].'>',250); $this->write('DATA',354);
        $headers=[
          'From: '.$this->settings['from_name'].' <'.$this->settings['from_email'].'>',
          'To: <'.$this->settings['to_email'].'>',
          'Subject: =?UTF-8?B?'.base64_encode($subject).'?=',
          'MIME-Version: 1.0','Content-Type: text/html; charset=UTF-8','Content-Transfer-Encoding: 8bit'
        ];
        $payload=implode("\r\n",$headers)."\r\n\r\n".$html; $payload=preg_replace('/(?m)^\./','..',$payload); fwrite($this->socket,$payload."\r\n.\r\n"); $this->read(250); $this->write('QUIT',221); fclose($this->socket);
    }
}
function notify_new_memory(array $memory): void {
    $settings=cfg('smtp'); if(empty($settings['enabled']) || str_contains((string)$settings['password'],'REEMPLAZAR')) { error_log('[Sonocamara SMTP] Configuración pendiente.'); return; }
    $review=admin_url('?route=edit&id='.(int)$memory['id']);
    $html='<h2>Nuevo recuerdo pendiente</h2><p><strong>Autor:</strong> '.e($memory['author_name']).'</p><p>'.nl2br(e($memory['message'])).'</p><p><a href="'.e($review).'">Revisar en el panel administrativo</a></p>';
    try { (new SimpleSmtpMailer($settings))->send('Nuevo recuerdo pendiente de aprobación — Sonocámara',$html); }
    catch(Throwable $e){ error_log('[Sonocamara SMTP] '.$e->getMessage()); }
}
