<?php
namespace Gestoreasy\Core\Mail;

use Gestoreasy\Core\Config\Config;

class Mailer {
    public static function send(string $to, string $subject, string $body, array $headers = []): bool {
        $smtpHost = Config::get('SMTP_HOST');
        $smtpPort = (int)Config::get('SMTP_PORT', 0);
        $smtpUser = Config::get('SMTP_USER');
        $smtpPass = Config::get('SMTP_PASS');
        $from = Config::get('SMTP_FROM', 'no-reply@localhost');
        // For now, write .eml file to storage for audit and verification
        $dir = __DIR__ . '/../../../storage/emails';
        if (!is_dir($dir)) { @mkdir($dir, 0777, true); }
        $date = gmdate('D, d M Y H:i:s') . ' GMT';
        $msg = "Date: $date\r\n" .
               "From: $from\r\n" .
               "To: $to\r\n" .
               "Subject: $subject\r\n" .
               "MIME-Version: 1.0\r\n" .
               "Content-Type: text/plain; charset=UTF-8\r\n";
        foreach ($headers as $k => $v) { $msg .= "$k: $v\r\n"; }
        $msg .= "\r\n$body\r\n";
        $file = $dir . '/' . date('Ymd_His') . '_' . preg_replace('/[^a-z0-9]+/i', '-', $to) . '.eml';
        file_put_contents($file, $msg);
        // Optionally attempt simple SMTP send if configured (non-SSL)
        if ($smtpHost && $smtpPort > 0) {
            // Minimal, best-effort SMTP without TLS; production should use a proper library
            try {
                $socket = fsockopen($smtpHost, $smtpPort, $errno, $errstr, 5);
                if ($socket) {
                    self::smtpExpect($socket, 220);
                    self::smtpWrite($socket, 'EHLO localhost'); self::smtpExpect($socket, 250);
                    if ($smtpUser && $smtpPass) {
                        self::smtpWrite($socket, 'AUTH LOGIN'); self::smtpExpect($socket, 334);
                        self::smtpWrite($socket, base64_encode($smtpUser)); self::smtpExpect($socket, 334);
                        self::smtpWrite($socket, base64_encode($smtpPass)); self::smtpExpect($socket, 235);
                    }
                    self::smtpWrite($socket, 'MAIL FROM: <' . $from . '>'); self::smtpExpect($socket, 250);
                    self::smtpWrite($socket, 'RCPT TO: <' . $to . '>'); self::smtpExpect($socket, 250);
                    self::smtpWrite($socket, 'DATA'); self::smtpExpect($socket, 354);
                    fwrite($socket, $msg . "\r\n.\r\n"); self::smtpExpect($socket, 250);
                    self::smtpWrite($socket, 'QUIT');
                    fclose($socket);
                }
            } catch (\Throwable $e) {
                // swallow errors; .eml file exists for audit
            }
        }
        return true;
    }

    private static function smtpWrite($socket, string $line): void { fwrite($socket, $line . "\r\n"); }
    private static function smtpExpect($socket, int $code): void {
        $resp = fgets($socket, 512);
        if (!$resp || (int)substr($resp, 0, 3) !== $code) { /* ignore for stub */ }
    }
}