<?php
function mailer_config(array $config): array {
    return $config['mail'] ?? [
        'transport' => 'mail',
        'from_email' => $config['reset_from_email'] ?? '',
        'from_name' => 'KuhRator',
        'smtp_host' => '',
        'smtp_port' => 587,
        'smtp_encryption' => 'tls',
        'smtp_user' => '',
        'smtp_pass' => '',
    ];
}
function mailer_header_encode(string $value): string {
    return mb_encode_mimeheader($value, 'UTF-8', 'B', "\r\n");
}
function mailer_send_password_reset(array $config, string $to, string $resetLink): bool {
    $subject = 'KuhRator Passwort zuruecksetzen';
    $text = "Hallo\n\nDu hast ein neues Passwort fuer KuhRator angefordert. Oeffne diesen Link innerhalb von 1 Stunde:\n\n".$resetLink."\n\nFalls du die Anfrage nicht ausgelöst hast, kannst du diese Nachricht ignorieren.\n";
    $html = '<p>Hallo</p><p>Du hast ein neues Passwort fuer <strong>KuhRator</strong> angefordert.</p><p><a href="'.htmlspecialchars($resetLink, ENT_QUOTES, 'UTF-8').'">Passwort zuruecksetzen</a></p><p>Der Link ist 1 Stunde gueltig.</p><p>Falls du die Anfrage nicht ausgelöst hast, kannst du diese Nachricht ignorieren.</p>';
    return mailer_send($config, $to, $subject, $text, $html);
}
function mailer_send(array $config, string $to, string $subject, string $text, string $html = ''): bool {
    $mail = mailer_config($config);
    return (($mail['transport'] ?? 'mail') === 'smtp')
        ? mailer_send_smtp($mail, $to, $subject, $text, $html)
        : mailer_send_mail($mail, $to, $subject, $text, $html);
}
function mailer_from_header(array $mail): string {
    $fromEmail = trim((string)($mail['from_email'] ?? ''));
    $fromName = trim((string)($mail['from_name'] ?? 'KuhRator'));
    if ($fromEmail === '') return '';
    return $fromName !== '' ? mailer_header_encode($fromName).' <'.$fromEmail.'>' : $fromEmail;
}
function mailer_message(string $from, string $to, string $subject, string $text, string $html = ''): array {
    $boundary = '=_kuhrator_'.bin2hex(random_bytes(12));
    $headers = [];
    if ($from !== '') $headers[] = 'From: '.$from;
    $headers[] = 'MIME-Version: 1.0';
    if ($html !== '') {
        $headers[] = 'Content-Type: multipart/alternative; boundary="'.$boundary.'"';
        $body = "--$boundary\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n$text\r\n\r\n";
        $body .= "--$boundary\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n$html\r\n\r\n--$boundary--";
    } else {
        $headers[] = 'Content-Type: text/plain; charset=UTF-8';
        $body = $text;
    }
    return [$headers, $body];
}
function mailer_send_mail(array $mail, string $to, string $subject, string $text, string $html = ''): bool {
    $from = mailer_from_header($mail);
    [$headers, $body] = mailer_message($from, $to, $subject, $text, $html);
    return @mail($to, mailer_header_encode($subject), $body, implode("\r\n", $headers));
}
function smtp_read($socket): string {
    $data = '';
    while (($line = fgets($socket, 515)) !== false) {
        $data .= $line;
        if (isset($line[3]) && $line[3] === ' ') break;
    }
    return $data;
}
function smtp_command($socket, string $command, array $expect): string {
    if ($command !== '') fwrite($socket, $command."\r\n");
    $response = smtp_read($socket);
    $code = (int)substr($response, 0, 3);
    if (!in_array($code, $expect, true)) {
        throw new RuntimeException('SMTP-Fehler: '.$response);
    }
    return $response;
}
function mailer_send_smtp(array $mail, string $to, string $subject, string $text, string $html = ''): bool {
    $host = trim((string)($mail['smtp_host'] ?? ''));
    $port = (int)($mail['smtp_port'] ?? 587);
    $encryption = strtolower((string)($mail['smtp_encryption'] ?? 'tls'));
    $user = (string)($mail['smtp_user'] ?? '');
    $pass = (string)($mail['smtp_pass'] ?? '');
    $fromEmail = trim((string)($mail['from_email'] ?? ''));
    if ($host === '' || $fromEmail === '') return false;
    $remote = ($encryption === 'ssl' ? 'ssl://' : '').$host;
    $socket = @fsockopen($remote, $port, $errno, $errstr, 15);
    if (!$socket) return false;
    stream_set_timeout($socket, 20);
    try {
        smtp_command($socket, '', [220]);
        smtp_command($socket, 'EHLO '.($_SERVER['SERVER_NAME'] ?? 'localhost'), [250]);
        if ($encryption === 'tls') {
            smtp_command($socket, 'STARTTLS', [220]);
            if (!stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) throw new RuntimeException('TLS konnte nicht gestartet werden.');
            smtp_command($socket, 'EHLO '.($_SERVER['SERVER_NAME'] ?? 'localhost'), [250]);
        }
        if ($user !== '') {
            smtp_command($socket, 'AUTH LOGIN', [334]);
            smtp_command($socket, base64_encode($user), [334]);
            smtp_command($socket, base64_encode($pass), [235]);
        }
        smtp_command($socket, 'MAIL FROM:<'.$fromEmail.'>', [250]);
        smtp_command($socket, 'RCPT TO:<'.$to.'>', [250,251]);
        smtp_command($socket, 'DATA', [354]);
        $from = mailer_from_header($mail);
        [$headers, $body] = mailer_message($from, $to, $subject, $text, $html);
        $raw = 'To: <'.$to.'>' . "\r\n" . 'Subject: '.mailer_header_encode($subject)."\r\n".implode("\r\n", $headers)."\r\n\r\n".$body;
        $raw = preg_replace('/^\./m', '..', $raw);
        fwrite($socket, $raw."\r\n.\r\n");
        smtp_command($socket, '', [250]);
        smtp_command($socket, 'QUIT', [221]);
        fclose($socket);
        return true;
    } catch (Throwable $e) {
        @fclose($socket);
        return false;
    }
}

function mailer_send_email_verification(array $config, string $to, string $verifyLink): bool {
    $subject = 'KuhRator E-Mail-Adresse bestaetigen';
    $text = "Hallo\n\nBitte bestaetige deine E-Mail-Adresse fuer KuhRator. Oeffne diesen Link innerhalb von 24 Stunden:\n\n".$verifyLink."\n\nFalls du dich nicht registriert hast, kannst du diese Nachricht ignorieren.\n";
    $html = '<p>Hallo</p><p>Bitte bestaetige deine E-Mail-Adresse fuer <strong>KuhRator</strong>.</p><p><a href="'.htmlspecialchars($verifyLink, ENT_QUOTES, 'UTF-8').'">E-Mail-Adresse bestaetigen</a></p><p>Der Link ist 24 Stunden gueltig.</p><p>Falls du dich nicht registriert hast, kannst du diese Nachricht ignorieren.</p>';
    return mailer_send($config, $to, $subject, $text, $html);
}
