<?php
/**
 * Prueba con noreply@productosrrb.com
 * Intenta SMTP directo (IP iPage) y también mail() nativo
 */

function smtpRead($socket, &$log) {
    $response = '';
    while (true) {
        $line = fgets($socket, 515);
        if ($line === false) break;
        $log[] = "S: " . trim($line);
        $response .= $line;
        if (strlen($line) >= 4 && $line[3] === ' ') break;
        if (strlen($line) < 4) break;
    }
    return $response;
}

function smtpWrite($socket, $cmd, &$log) {
    $display = (strlen(trim($cmd)) > 60) ? substr(trim($cmd), 0, 30) . '...(b64)' : trim($cmd);
    $log[] = "C: " . $display;
    fwrite($socket, $cmd);
}

function enviarSMTP($para, $asunto, $cuerpoHtml, $smtpUser, $smtpPass, $fromEmail) {
    $smtpIp   = '66.96.143.170'; // IP real de smtp.ipage.com
    $smtpPort = 465;
    $fromName = 'Real Rich Business';

    $boundary = md5(uniqid());
    $headers  = "From: =?UTF-8?B?" . base64_encode($fromName) . "?= <$fromEmail>\r\n";
    $headers .= "To: $para\r\n";
    $headers .= "Subject: =?UTF-8?B?" . base64_encode($asunto) . "?=\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: multipart/alternative; boundary=\"$boundary\"\r\n";
    $headers .= "Date: " . date('r') . "\r\n";
    $headers .= "Message-ID: <" . uniqid() . "@productosrrb.com>\r\n";

    $mensaje  = "--$boundary\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n" . strip_tags($cuerpoHtml) . "\r\n";
    $mensaje .= "--$boundary\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n" . $cuerpoHtml . "\r\n";
    $mensaje .= "--$boundary--\r\n";

    $context = stream_context_create([
        'ssl' => ['verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true]
    ]);

    $log = [];
    $errno = 0; $errstr = '';
    $socket = stream_socket_client("ssl://$smtpIp:$smtpPort", $errno, $errstr, 15, STREAM_CLIENT_CONNECT, $context);
    if (!$socket) return ['ok' => false, 'error' => "Conexión fallida: $errstr ($errno)"];

    smtpRead($socket, $log);
    smtpWrite($socket, "EHLO productosrrb.com\r\n", $log);
    smtpRead($socket, $log);

    smtpWrite($socket, "AUTH LOGIN\r\n", $log);
    $r = smtpRead($socket, $log);
    if (strpos($r, '334') === false) { fclose($socket); return ['ok' => false, 'error' => "AUTH LOGIN: $r", 'log' => $log]; }

    smtpWrite($socket, base64_encode($smtpUser) . "\r\n", $log);
    $r = smtpRead($socket, $log);
    if (strpos($r, '334') === false) { fclose($socket); return ['ok' => false, 'error' => "Usuario: $r", 'log' => $log]; }

    smtpWrite($socket, base64_encode($smtpPass) . "\r\n", $log);
    $authResp = smtpRead($socket, $log);
    if (strpos($authResp, '235') === false) { fclose($socket); return ['ok' => false, 'error' => "AUTH: $authResp", 'log' => $log]; }

    smtpWrite($socket, "MAIL FROM:<$fromEmail>\r\n", $log); smtpRead($socket, $log);
    smtpWrite($socket, "RCPT TO:<$para>\r\n", $log);
    $r = smtpRead($socket, $log);
    if (strpos($r, '250') === false) { fclose($socket); return ['ok' => false, 'error' => "RCPT: $r", 'log' => $log]; }

    smtpWrite($socket, "DATA\r\n", $log); smtpRead($socket, $log);
    smtpWrite($socket, $headers . "\r\n" . $mensaje . "\r\n.\r\n", $log);
    $dataResp = smtpRead($socket, $log);
    smtpWrite($socket, "QUIT\r\n", $log);
    fclose($socket);

    if (strpos($dataResp, '250') !== false) return ['ok' => true, 'message' => 'Enviado OK', 'log' => $log];
    return ['ok' => false, 'error' => "DATA: $dataResp", 'log' => $log];
}

$resultados = [];

// Prueba 1: noreply@productosrrb.com
$resultados['noreply_smtp'] = enviarSMTP(
    'sg.mike@gmail.com',
    'Prueba noreply@productosrrb.com',
    '<h2>Prueba ✓</h2><p>Correo enviado con <strong>noreply@productosrrb.com</strong></p>',
    'noreply@productosrrb.com',
    'Mikel123123correo*',
    'noreply@productosrrb.com'
);

// Prueba 2: mail() nativo con noreply
$asunto2 = '=?UTF-8?B?' . base64_encode('Prueba noreply mail() nativo') . '?=';
$hdrs2  = "From: Real Rich Business <noreply@productosrrb.com>\r\n";
$hdrs2 .= "Reply-To: noreply@productosrrb.com\r\n";
$hdrs2 .= "MIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n";
$r2 = mail('sg.mike@gmail.com', $asunto2, '<p>Prueba mail() nativo con noreply@productosrrb.com</p>', $hdrs2, '-f noreply@productosrrb.com');
$resultados['noreply_mail_native'] = ['ok' => $r2, 'message' => $r2 ? 'mail() OK' : 'mail() false'];

header('Content-Type: application/json');
echo json_encode($resultados, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
