<?php
/**
 * Funkcja do wysyłki emaili przez SMTP używając PHP socket
 */
function sendEmailSMTP($to, $subject, $html_body, $config = null) {
    // Logowanie do pliku - na samym początku!
    $log_file = __DIR__ . '/smtp_debug.log';
    file_put_contents($log_file, date('Y-m-d H:i:s') . " - Function called for: $to\n", FILE_APPEND);
    
    if ($config === null) {
        $config = require __DIR__ . '/smtp_config.php';
    }
    
    $log = [];
    $log[] = date('Y-m-d H:i:s') . " - Starting SMTP to: $to";
    
    // Funkcja do odczytu pełnej odpowiedzi SMTP (także wieloliniowej)
    $readResponse = function($smtp) {
        $response = '';
        while ($line = fgets($smtp, 515)) {
            $response .= $line;
            // Jeśli linia nie ma '-' po kodzie (np. "250 " zamiast "250-"), to koniec
            if (preg_match('/^\d{3} /', $line)) {
                break;
            }
        }
        return $response;
    };
    
    // Połączenie z serwerem SMTP
    $smtp = @fsockopen($config['host'], $config['port'], $errno, $errstr, 30);
    
    if (!$smtp) {
        $log[] = "Connection FAILED: $errstr ($errno)";
        file_put_contents($log_file, implode("\n", $log) . "\n\n", FILE_APPEND);
        return false;
    }
    
    $log[] = "Connected to {$config['host']}:{$config['port']}";
    
    // Odczyt powitania serwera
    $response = $readResponse($smtp);
    $log[] = "Server: $response";
    
    // EHLO
    fputs($smtp, "EHLO " . $config['host'] . "\r\n");
    $response = $readResponse($smtp);
    $log[] = "EHLO: $response";
    
    // AUTH LOGIN
    fputs($smtp, "AUTH LOGIN\r\n");
    $response = $readResponse($smtp);
    $log[] = "AUTH: $response";
    
    fputs($smtp, base64_encode($config['username']) . "\r\n");
    $response = $readResponse($smtp);
    $log[] = "USER: $response";
    
    fputs($smtp, base64_encode($config['password']) . "\r\n");
    $response = $readResponse($smtp);
    $log[] = "PASS: $response";
    
    if (strpos($response, '235') === false) {
        $log[] = "Auth FAILED!";
        file_put_contents($log_file, implode("\n", $log) . "\n\n", FILE_APPEND);
        fclose($smtp);
        return false;
    }
    
    // MAIL FROM
    fputs($smtp, "MAIL FROM: <" . $config['from_email'] . ">\r\n");
    $response = $readResponse($smtp);
    $log[] = "FROM: $response";
    
    // RCPT TO
    fputs($smtp, "RCPT TO: <$to>\r\n");
    $response = $readResponse($smtp);
    $log[] = "TO: $response";
    
    // DATA
    fputs($smtp, "DATA\r\n");
    $response = $readResponse($smtp);
    $log[] = "DATA: $response";
    
    // Headers i treść
    $headers = "From: " . $config['from_name'] . " <" . $config['from_email'] . ">\r\n";
    $headers .= "To: <$to>\r\n";
    $headers .= "Subject: =?UTF-8?B?" . base64_encode($subject) . "?=\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    $headers .= "\r\n";
    
    fputs($smtp, $headers . $html_body . "\r\n.\r\n");
    $response = $readResponse($smtp);
    $log[] = "SEND: $response";
    
    // QUIT
    fputs($smtp, "QUIT\r\n");
    $response = $readResponse($smtp);
    $log[] = "QUIT: $response";
    
    fclose($smtp);
    
    $success = strpos($response, '250') !== false || strpos($response, '221') !== false;
    $log[] = "Result: " . ($success ? "SUCCESS" : "FAILED");
    
    file_put_contents($log_file, implode("\n", $log) . "\n\n", FILE_APPEND);
    
    return $success;
}
