<?php
require_once __DIR__ . '/../vendor/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/../vendor/phpmailer/src/SMTP.php';
require_once __DIR__ . '/../vendor/phpmailer/src/Exception.php';
require_once 'smtp_config.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function send_mail($to, $subject, $message_body) {
    global $smtp_config;

    $logFile = __DIR__ . '/error.log';
    if (!extension_loaded('openssl')) {
        error_log("OpenSSL extension not loaded; SSL/TLS may fail\n", 3, $logFile);
    }

    // Çoklu sağlayıcı varsa sırayla dene
    if (isset($smtp_config['providers']) && isset($smtp_config['order'])) {
        foreach ($smtp_config['order'] as $providerKey) {
            if (!isset($smtp_config['providers'][$providerKey])) { continue; }
            $cfg = $smtp_config['providers'][$providerKey];
            $host = $cfg['host'];
            $port = $cfg['port'];
            $secure = $cfg['secure'];
            error_log("SMTP provider=$providerKey host=$host port=$port secure=$secure\n", 3, $logFile);

            // Önden ham TCP bağlantısını dene, errno/errstr yakala
            $errno = 0; $errstr = '';
            $sock = @fsockopen($host, $port, $errno, $errstr, 10);
            if ($sock === false) {
                error_log("Preconnect failed ($providerKey): errno=$errno errstr=$errstr host=$host port=$port\n", 3, $logFile);
                // Alternatif port/güvenlik kombinasyonlarını dene
                $altCandidates = [];
                if ($secure === 'tls' && $port == 587) {
                    // Önce 465/ssl, sonra 2525/tls (MailerSend gibi sağlayıcılar için)
                    $altCandidates[] = ['host' => $host, 'port' => 465, 'secure' => 'ssl'];
                    $altCandidates[] = ['host' => $host, 'port' => 2525, 'secure' => 'tls'];
                } else if ($secure === 'ssl' && $port == 465) {
                    $altCandidates[] = ['host' => $host, 'port' => 587, 'secure' => 'tls'];
                    $altCandidates[] = ['host' => $host, 'port' => 2525, 'secure' => 'tls'];
                } else if ($secure === 'tls' && $port == 2525) {
                    $altCandidates[] = ['host' => $host, 'port' => 587, 'secure' => 'tls'];
                    $altCandidates[] = ['host' => $host, 'port' => 465, 'secure' => 'ssl'];
                }

                foreach ($altCandidates as $alt) {
                    $errno2 = 0; $errstr2 = '';
                    $sock2 = @fsockopen($alt['host'], $alt['port'], $errno2, $errstr2, 10);
                    if ($sock2 !== false) {
                        fclose($sock2);
                        $host = $alt['host']; $port = $alt['port']; $secure = $alt['secure'];
                        error_log("Preconnect alt succeeded ($providerKey): host=$host port=$port secure=$secure\n", 3, $logFile);
                        break;
                    } else {
                        error_log("Preconnect alt failed ($providerKey): errno=$errno2 errstr=$errstr2 host={$alt['host']} port={$alt['port']}\n", 3, $logFile);
                    }
                }
            } else {
                fclose($sock);
                error_log("Preconnect succeeded ($providerKey): host=$host port=$port\n", 3, $logFile);
            }
            try {
                $mail = new PHPMailer(true);
                $mail->isSMTP();
                // Hostname kullan (IP yerine), sağlayıcıların SNI/DNS yönlendirmesi için daha sağlıklı
                $mail->Host = $host;
                $mail->SMTPAuth = true;
                $mail->Username = $cfg['username'];
                $mail->Password = $cfg['password'];
                $mail->Port = $port;
                $mail->CharSet = 'UTF-8';
                $mail->Timeout = 30;
                $mail->SMTPAutoTLS = true;
                $mail->AuthType = 'LOGIN';
                if ($secure === 'ssl' || $port == 465) {
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                } else {
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                }
                $mail->SMTPOptions = [
                    'ssl' => [
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                    ]
                ];
                $mail->setFrom($cfg['from_email'], $cfg['from_name']);
                $mail->addAddress($to);
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body = $message_body;
                $mail->SMTPDebug = 4; // Daha düşük seviyede bağlantı debug
                $mail->Debugoutput = function($str, $level) use ($logFile, $providerKey) {
                    error_log("PHPMailer [$providerKey][$level]: $str\n", 3, $logFile);
                };
                $sent = $mail->send();
                error_log(("PHPMailer gönderim ($providerKey): Result=" . ($sent ? "Başarılı" : "Başarısız")) . "\n", 3, $logFile);
                if ($sent) { return true; }
            } catch (Exception $e) {
                error_log(("PHPMailer Exception ($providerKey): " . $e->getMessage()) . "\n", 3, $logFile);
                // Eğer Yandex'te kimlik doğrulama hatası ise, alternatif kullanıcı adı ve AuthType denemeleri yap
                if ($providerKey === 'yandex') {
                    $baseUser = $cfg['username'];
                    $local = $baseUser;
                    $domain = '';
                    if (strpos($baseUser, '@') !== false) {
                        [$local, $domain] = explode('@', $baseUser, 2);
                    }
                    $alts = array_unique(array_filter([
                        $local, // sadece kullanıcı adı
                        $baseUser, // tam adres (mevcut)
                        $local . '@yandex.com',
                        $local . '@yandex.com.tr',
                    ]));

                    foreach ($alts as $altUser) {
                        foreach (['LOGIN','PLAIN'] as $authType) {
                            try {
                                error_log("Yandex auth fallback deneme: user=$altUser auth=$authType host=$host port=$port secure=$secure\n", 3, $logFile);
                                $mail = new PHPMailer(true);
                                $mail->isSMTP();
                                $mail->Host = $host;
                                $mail->SMTPAuth = true;
                                $mail->Username = $altUser;
                                $mail->Password = $cfg['password'];
                                $mail->Port = $port;
                                $mail->CharSet = 'UTF-8';
                                $mail->Timeout = 30;
                                $mail->SMTPAutoTLS = true;
                                $mail->AuthType = $authType;
                                if ($secure === 'ssl' || $port == 465) {
                                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                                } else {
                                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                                }
                                $mail->SMTPOptions = [
                                    'ssl' => [
                                        'verify_peer' => false,
                                        'verify_peer_name' => false,
                                        'allow_self_signed' => true
                                    ]
                                ];
                                $mail->setFrom($cfg['from_email'], $cfg['from_name']);
                                $mail->addAddress($to);
                                $mail->isHTML(true);
                                $mail->Subject = $subject;
                                $mail->Body = $message_body;
                                $mail->SMTPDebug = 4;
                                $mail->Debugoutput = function($str, $level) use ($logFile, $providerKey, $altUser, $authType) {
                                    error_log("PHPMailer [$providerKey][$authType][$altUser][$level]: $str\n", 3, $logFile);
                                };
                                $sent = $mail->send();
                                error_log(("PHPMailer gönderim ($providerKey fallback): user=$altUser auth=$authType Result=" . ($sent ? "Başarılı" : "Başarısız")) . "\n", 3, $logFile);
                                if ($sent) { return true; }
                            } catch (Exception $e2) {
                                error_log(("PHPMailer Yandex fallback Exception: user=$altUser auth=$authType msg=" . $e2->getMessage()) . "\n", 3, $logFile);
                                // sıradaki kombinasyonu dene
                            }
                        }
                    }
                }
                // Sonraki sağlayıcıyı dene
            }
        }
        return false;
    }

    // Geri uyumluluk: tek sağlayıcı yapısı
    try {
        $resolved = gethostbyname($smtp_config['host']);
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host = $resolved ?: $smtp_config['host'];
        $mail->SMTPAuth = true;
        $mail->Username = $smtp_config['username'];
        $mail->Password = $smtp_config['password'];
        $mail->Port = $smtp_config['port'];
        $mail->CharSet = 'UTF-8';
        $mail->Timeout = 20;
        $mail->SMTPAutoTLS = true;
        $mail->AuthType = 'LOGIN';
        if ($smtp_config['secure'] === 'ssl' || $smtp_config['port'] == 465) {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        } else {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        }
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ];
        $mail->setFrom($smtp_config['from_email'], $smtp_config['from_name']);
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = $message_body;
        $mail->SMTPDebug = 2;
        $mail->Debugoutput = function($str, $level) use ($logFile) {
            error_log("PHPMailer [legacy][$level]: $str\n", 3, $logFile);
        };
        $sent = $mail->send();
        error_log(("PHPMailer legacy gönderim: Result=" . ($sent ? "Başarılı" : "Başarısız")) . "\n", 3, $logFile);
        return $sent;
    } catch (Exception $e) {
        error_log(("PHPMailer legacy Exception: " . $e->getMessage()) . "\n", 3, $logFile);
        return false;
    }
}
?>