<?php
/**
 * Simple SMTP mailer using socket — no Composer.
 * Settings from site_settings: smtp_enabled, smtp_host, smtp_port, smtp_encryption, smtp_user, smtp_pass, smtp_from_email, smtp_from_name
 */
function smtpSend($to, $subject, $body, $replyTo = null) {
    if (getSetting('smtp_enabled', '0') !== '1') {
        return false;
    }
    $host = trim(getSetting('smtp_host', ''));
    $port = (int)getSetting('smtp_port', 587);
    $enc = strtolower(trim(getSetting('smtp_encryption', 'tls')));
    $user = getSetting('smtp_user', '');
    $pass = getSetting('smtp_pass', '');
    $from = trim(getSetting('smtp_from_email', ''));
    $fromName = trim(getSetting('smtp_from_name', 'Site'));
    if (!$host || !$from || !$to) return false;

    $errno = 0; $errstr = '';
    $remote = ($enc === 'ssl') ? 'ssl://' . $host . ':' . $port : $host . ':' . $port;
    $fp = @stream_socket_client($remote, $errno, $errstr, 25, STREAM_CLIENT_CONNECT);
    if (!$fp) return false;

    $read = function() use ($fp) {
        $data = '';
        while ($line = fgets($fp, 515)) {
            $data .= $line;
            if (isset($line[3]) && $line[3] === ' ') break;
        }
        return $data;
    };
    $write = function($cmd) use ($fp) {
        fwrite($fp, $cmd . "\r\n");
    };

    $read();
    $write('EHLO localhost');
    $read();

    if ($enc === 'tls' && $port !== 465) {
        $write('STARTTLS');
        $r = $read();
        if (strpos($r, '220') === false) { fclose($fp); return false; }
        stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
        $write('EHLO localhost');
        $read();
    }

    if ($user !== '' && $pass !== '') {
        $write('AUTH LOGIN');
        $read();
        $write(base64_encode($user));
        $read();
        $write(base64_encode($pass));
        $r = $read();
        if (strpos($r, '235') === false) { fclose($fp); return false; }
    }

    $write('MAIL FROM:<' . $from . '>');
    $read();
    $write('RCPT TO:<' . $to . '>');
    $read();
    $write('DATA');
    $read();

    $boundary = 'b' . md5(uniqid());
    $headers = "From: " . mb_encode_mimeheader($fromName, 'UTF-8') . " <{$from}>\r\n";
    $headers .= "To: <{$to}>\r\n";
    $headers .= "Subject: " . mb_encode_mimeheader($subject, 'UTF-8') . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    if ($replyTo) $headers .= "Reply-To: {$replyTo}\r\n";
    $headers .= "\r\n";
    $msg = $headers . '<pre style="font-family:sans-serif">' . htmlspecialchars($body) . '</pre>';
    $msg = str_replace("\r\n", "\n", $msg);
    $msg = str_replace("\n", "\r\n", $msg);
    $write($msg . "\r\n.");
    $r = $read();
    $write('QUIT');
    fclose($fp);
    return (strpos($r, '250') !== false);
}

function notifyEnquiryOrContact($type, $data) {
    $notify = trim(getSetting('smtp_notify_email', ''));
    if ($notify === '') $notify = trim(getSetting('contact_email', ''));
    if ($notify === '') return;
    $subject = $type === 'enquiry' ? 'New enquiry — ' . ($data['subject'] ?? 'Website') : 'New contact message';
    $body = "Type: {$type}\n\n";
    foreach ($data as $k => $v) {
        $body .= $k . ": " . $v . "\n";
    }
    smtpSend($notify, $subject, $body, $data['email'] ?? null);
}
