<?php
function smtp_read_all($conn): string {
    $data = '';
    while ($line = fgets($conn, 512)) {
        $data .= $line;
        if (substr($line, 3, 1) === ' ') break;
    }
    return $data;
}
function smtp_cmd($conn, string $cmd, string $label): string {
    fwrite($conn, $cmd . "\r\n");
    $r = smtp_read_all($conn);
    echo "<b>$label:</b> " . htmlspecialchars($r) . "\n";
    return $r;
}

echo "<pre>";
echo "<b>Conectando a smtp.gmail.com:465...</b>\n";
$conn = @fsockopen("ssl://smtp.gmail.com", 465, $errno, $errstr, 15);
if (!$conn) { echo "FALLO conexion: $errno - $errstr\n"; exit; }
stream_set_timeout($conn, 15);

echo "<b>Banner:</b> " . htmlspecialchars(smtp_read_all($conn));
smtp_cmd($conn, "EHLO smtp.gmail.com", "EHLO");
$r = smtp_cmd($conn, "AUTH LOGIN", "AUTH LOGIN");
if (strpos($r, '334') !== false) {
    $r = smtp_cmd($conn, base64_encode('ottolimser19@gmail.com'), "Username");
    $r = smtp_cmd($conn, base64_encode('xlujeozdnxjdwfoi'), "Password");
    if (strpos($r, '235') !== false) {
        echo "\n<b>✅ AUTENTICACION EXITOSA - enviando correo de prueba...</b>\n\n";
        smtp_cmd($conn, "MAIL FROM:<ottolimser19@gmail.com>", "MAIL FROM");
        smtp_cmd($conn, "RCPT TO:<info@ottolimser.com.ar>", "RCPT TO");
        $r = smtp_cmd($conn, "DATA", "DATA");
        if (strpos($r, '354') !== false) {
            $msg  = "Date: " . date('r') . "\r\n";
            $msg .= "From: ottolimser19@gmail.com\r\n";
            $msg .= "To: info@ottolimser.com.ar\r\n";
            $msg .= "Subject: TEST formulario web\r\n\r\n";
            $msg .= "Correo de prueba desde el formulario.\r\n";
            fwrite($conn, $msg . "\r\n.\r\n");
            $r = smtp_read_all($conn);
            echo "<b>Resultado:</b> " . htmlspecialchars($r) . "\n";
            if (strpos($r, '250') !== false) echo "✅ CORREO ENVIADO\n";
            else echo "❌ RECHAZO: " . htmlspecialchars($r) . "\n";
        }
    } else {
        echo "\n❌ AUTENTICACION FALLIDA: " . htmlspecialchars($r) . "\n";
    }
}
smtp_cmd($conn, "QUIT", "QUIT");
fclose($conn);
echo "</pre>";