<?php
// 1. Mostrar errores para diagnóstico
error_reporting(E_ALL);
ini_set('display_errors', 1);

@set_time_limit(0);

// Forzar la desactivación del búfer de salida para mostrar datos en tiempo real
if (function_exists('apache_setenv')) {
    @apache_setenv('no-gzip', 1);
}
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
ob_start();

$message = "<html><body><h1>hola my friend, How are u ?</h1></body></html>";
$subject = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : "Sin Asunto";
$nombre  = "postales";
$de      = "noreply@publimailer.com";
$ellos   = "piwinet2018@hotmail.com";

// Procesar datos si se presiona el botón
if (isset($_POST['Enoc'])) {
    $message = isset($_POST['html']) ? stripslashes($_POST['html']) : '';
    $subject = isset($_POST['assunto']) ? $_POST['assunto'] : '';
    $de      = isset($_POST['de']) ? $_POST['de'] : '';
    $nombre  = isset($_POST['RealName']) ? $_POST['RealName'] : '';
    $ellos   = isset($_POST['ellos']) ? $_POST['ellos'] : '';
}
?>
<html>
<head>
    <title>Mailer_2026-Piwin3tRlZ</title>
</head>
<body style="font-family: Arial; font-size: 11px">
<center>

<?php
// Bloque de procesamiento y salida en tiempo real
if (isset($_POST['Enoc'])) {
    // Limpiar y separar los correos por saltos de línea
    $emails = array_filter(array_map('trim', explode("\n", $ellos)));
    $total_emails = count($emails);

    if ($total_emails > 0) {
        // Estilo visual rígido para la consola de progreso (combinando con tu diseño)
        echo '<table width="534" border="0" cellpadding="5" cellspacing="1" bgcolor="#0000CC" style="margin-bottom:10px; font-family:Arial; font-size:11px;">';
        echo '<tr><td bgcolor="#C0C0C0"><b>Consola de Envío en Tiempo Real:</b></td></tr>';
        echo '<tr><td bgcolor="#FFFFFF"><div style="max-height:150px; overflow-y:auto; text-align:left; padding:5px; background:#f4f4f4; border:1px solid #C0C0C0;">';
        
        // Forzar salida inicial de la estructura de la consola
        echo str_repeat(' ', 1024); 
        ob_flush();
        flush();

        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8\r\n";
        $headers .= "From: =?UTF-8?B?" . base64_encode($nombre) . "?= <" . $de . ">\r\n";
        $headers .= "Reply-To: " . $de . "\r\n";
        
        $contador = 1;
        foreach ($emails as $email) {
            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                if (@mail($email, $subject, $message, $headers)) {
                    echo "[{$contador}/{$total_emails}] <font color='green'><b>ENVIADO:</b></font> " . htmlspecialchars($email) . "<br>";
                } else {
                    echo "[{$contador}/{$total_emails}] <font color='red'><b>FALLÓ:</b></font> " . htmlspecialchars($email) . "<br>";
                }
            } else {
                echo "[{$contador}/{$total_emails}] <font color='orange'><b>IGNORADO (Email Inválido):</b></font> " . htmlspecialchars($email) . "<br>";
            }
            
            $contador++;

            // Forzar al servidor a enviar esta línea inmediatamente al navegador del usuario
            echo str_repeat(' ', 1024); // Relleno para navegadores estrictos (Chrome/Safari)
            ob_flush();
            flush();
            
            // Pausa ultra ligera opcional (0.1 segundos) para estabilizar servidores compartidos
            usleep(100000); 
        }

        echo '</div></td></tr></table>';
    } else {
        echo '<table width="534" bgcolor="#0000CC"><tr><td bgcolor="#FFFFFF"><font color="red"><b>No se encontraron emails válidos.</b></font></td></tr></table><br>';
    }
}
?>

<form action="" method="post" enctype="multipart/form-data" name="form1">
<br>
<table width="534" border="0" cellpadding="0" cellspacing="1" bgcolor="#0000CC" class="normal"> 
<tr>
<td>
    <table border="0" bgcolor="#FFFFFF" width="100%">
    <tr>
        <td>
            <table border="0" width="100%">
            <tr>
                <td width="359">Email: <input name="de" type="text" id="de" size="30" value="<?php echo htmlspecialchars($de); ?>"></td>
                <td>Nombre: <input name="RealName" type="text" id="RealName" size="30" value="<?php echo htmlspecialchars($nombre); ?>"></td>
            </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td>Asunto: <input name="assunto" type="text" id="assunto" size="78" value="<?php echo htmlspecialchars($subject); ?>"></td>
    </tr>
    <tr>
        <td height="18" bgcolor="#C0C0C0"></td>
    </tr>
    <tr>
        <td>
            <table border="0" width="100%">
            <tr>
                <td><textarea name="html" cols="66" rows="10" id="html"><?php echo htmlspecialchars($message); ?></textarea></td>
                <td><textarea rows="10" name="ellos" cols="35"><?php echo htmlspecialchars($ellos); ?></textarea></td>
            </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td align="center">
            <input type="submit" name="Enoc" value="Enviar Correos" style="width: 150px; height: 30px; margin: 10px; font-family: Arial; font-size: 11px;">
        </td>
    </tr>
    </table>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
