<?php
/**
 * Script de prueba SMTP - iPage (smtp.ipage.com:465 SSL)
 */

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 enviarCorreo($para, $asunto, $cuerpoHtml) {
    $smtpHost = 'smtp.ipage.com';
    $smtpPort = 465;
    $smtpUser = 'noresponder@rrbmexico.com';
    $smtpPass = 'Mikel123123correo*';
    $fromName = 'Real Rich Business';
    $fromEmail = 'noresponder@rrbmexico.com';

    $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() . "@rrbmexico.com>\r\n";

    $mensaje  = "--$boundary\r\n";
    $mensaje .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
    $mensaje .= strip_tags($cuerpoHtml) . "\r\n";
    $mensaje .= "--$boundary\r\n";
    $mensaje .= "Content-Type: text/html; charset=UTF-8\r\n\r\n";
    $mensaje .= $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://$smtpHost:$smtpPort", $errno, $errstr, 15, STREAM_CLIENT_CONNECT, $context);
    if (!$socket) {
        return ['ok' => false, 'error' => "No se pudo conectar: $errstr ($errno)"];
    }

    smtpRead($socket, $log);

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

    // AUTH LOGIN
    smtpWrite($socket, "AUTH LOGIN\r\n", $log);
    $r = smtpRead($socket, $log);
    if (strpos($r, '334') === false) {
        fclose($socket);
        return ['ok' => false, 'error' => "AUTH LOGIN no aceptado: $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 no aceptado: $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 fallido: $authResp", 'log' => $log];
    }

    smtpWrite($socket, "MAIL FROM:<$fromEmail>\r\n", $log);
    smtpRead($socket, $log);

    smtpWrite($socket, "RCPT TO:<$para>\r\n", $log);
    $rcptResp = smtpRead($socket, $log);
    if (strpos($rcptResp, '250') === false) {
        fclose($socket);
        return ['ok' => false, 'error' => "RCPT fallido: $rcptResp", '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' => 'Correo enviado exitosamente', 'log' => $log];
    }
    return ['ok' => false, 'error' => "DATA fallido: $dataResp", 'log' => $log];
}

$resultado = enviarCorreo(
    'sg.mike@gmail.com',
    'Prueba de correo - Real Rich Business',
    '<h2>Prueba de correo ✓</h2><p>Este es un correo de prueba enviado desde el servidor de <strong>Real Rich Business</strong>.</p><p>Si recibes este mensaje, el sistema de correo está funcionando correctamente y los códigos de verificación comenzarán a llegar.</p>'
);

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