<?php
// Configurar exibição de erros para depuração
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Função para validar e-mails
function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

try {
    // Obter domínio do servidor e criar e-mail automático
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $dominio = preg_replace('/^www\./', '', strtolower($host));
    $email_automatico = "support@$dominio";

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Obter e limpar dados do formulário
        $nome_remetente = trim($_POST['nome'] ?? '');
        $de = trim($_POST['de'] ?? '') ?: $email_automatico;
        $assunto = trim($_POST['assunto'] ?? '');
        $mensagem_html = stripslashes($_POST['html'] ?? '');
        $linhas = array_filter(array_map('trim', explode("\n", $_POST['emails'] ?? '')));

        // Configurar cabeçalhos MIME
        $boundary = md5(uniqid(time()));
        $headers_base = "MIME-Version: 1.0\r\n";
        $headers_base .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
        $headers_base .= "X-Mailer: PHP/" . phpversion() . "\r\n";
        $headers_base .= "X-Priority: 1\r\n";
        $headers_base .= "X-MSmail-Priority: High\r\n";

        // Verificar anexo
        $temAnexo = isset($_FILES['arquivo']) && $_FILES['arquivo']['error'] === UPLOAD_ERR_OK;
        $anexo_nome = $anexo_tipo = $anexo_dados = '';
        if ($temAnexo) {
            $anexo_nome = basename($_FILES['arquivo']['name'] ?? '');
            $anexo_tipo = $_FILES['arquivo']['type'] ?? 'application/octet-stream';
            $anexo_dados = chunk_split(base64_encode(file_get_contents($_FILES['arquivo']['tmp_name'] ?? '')));
        }

        $count = 1;
        foreach ($linhas as $linha) {
            // Dividir linha em e-mail, CPF e nome
            $partes = array_map('trim', explode(";", $linha));
            $email = $partes[0] ?? '';
            $cpf = $partes[1] ?? '';
            $nome = $partes[2] ?? '';

            // Validar e-mail
            if (!empty($email) && !isValidEmail($email)) {
                echo "* Número: $count <b>" . htmlspecialchars($email) . "</b> <font color='orange'>E-MAIL INVÁLIDO</font><br><hr>";
                $count++;
                continue;
            }

            // Se não houver e-mail, pular para o próximo
            if (empty($email)) {
                continue;
            }

            // Extrair parte local do e-mail
            $email_user = explode('@', $email)[0] ?? '';

            // Gerar variáveis dinâmicas
            $uppercase_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $rand1 = substr(str_shuffle($uppercase_letters), 0, 6);
            $random1 = substr(md5(uniqid(mt_rand(), true)), 0, 6);
            $random_num = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);

            // Calcular data de 5 dias a partir de hoje
            $data5dias = date('d/m/Y', strtotime('+5 days'));

            $vars = [
                '%email%'      => $email,
                '%cpf%'        => $cpf,
                '%nome%'       => $nome,
                '%data%'       => date('d/m/Y'),
                '%hora%'       => date('H:i:s'),
                '%random1%'    => $random1,
                '%random2%'    => substr(md5(uniqid()), 0, 6),
                '%random3%'    => substr(md5(uniqid()), 0, 6),
                '%random4%'    => substr(md5(uniqid()), 0, 6),
                '%random5%'    => substr(md5(uniqid()), 0, 6),
                '%random6%'    => substr(md5(uniqid()), 0, 6),
                '%random_num%' => $random_num,
                '%rand%'       => rand(1000, 9999),
                '%rand1%'      => $rand1,
                '%email_user%' => $email_user,
                '%data5dias%'  => $data5dias, // Nova variável adicionada
            ];

            // Aplicar placeholders
            $nome_final = str_replace(array_keys($vars), array_values($vars), $nome_remetente ?: $email_automatico);
            $de_final = str_replace(array_keys($vars), array_values($vars), $de);
            $assunto_personalizado = str_replace(array_keys($vars), array_values($vars), $assunto ?: 'Sem assunto');
            $mensagem_personalizada = str_replace(array_keys($vars), array_values($vars), $mensagem_html ?: '<p>Não foi fornecida mensagem.</p>');

            // Codificar assunto e nome para UTF-8
            $subject = '=?UTF-8?B?' . base64_encode($assunto_personalizado) . '?=';
            $nome_encoded = '=?UTF-8?B?' . base64_encode($nome_final) . '?=';

            // Configurar cabeçalhos
            $headers = "From: $nome_encoded <$de_final>\r\n" . $headers_base;

            // Montar corpo do e-mail
            $corpo = "--$boundary\r\n";
            $corpo .= "Content-Type: text/html; charset=UTF-8\r\n";
            $corpo .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
            $corpo .= $mensagem_personalizada . "\r\n";

            if ($temAnexo) {
                $corpo .= "--$boundary\r\n";
                $corpo .= "Content-Type: $anexo_tipo; name=\"$anexo_nome\"\r\n";
                $corpo .= "Content-Transfer-Encoding: base64\r\n";
                $corpo .= "Content-Disposition: attachment; filename=\"$anexo_nome\"\r\n\r\n";
                $corpo .= $anexo_dados . "\r\n";
            }

            $corpo .= "--$boundary--";

            // Enviar e-mail
            if (mail($email, $subject, $corpo, $headers)) {
                echo "* Número: $count <b>" . htmlspecialchars($email) . "</b> <font color='green'>OK</font><br><hr>";
            } else {
                echo "* Número: $count <b>" . htmlspecialchars($email) . "</b> <font color='red'>ERRO AO ENVIAR</font><br><hr>";
            }

            $count++;
        }
    }
} catch (Exception $e) {
    echo "Erro no script: " . htmlspecialchars($e->getMessage()) . "<br>";
}
?>

<html>
<head>
    <title>IBASE</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style>
        body { margin: 0; font-family: Arial; }
        .titulo { font-size: 18px; font-weight: bold; }
        .normal { font-size: 12px; }
        .form { font-size: 10px; color: #333; background-color: #FFF; border: 1px dashed #666; }
        .texto { font-weight: bold; font-family: Verdana; }
        .alerta { font-weight: bold; color: #990000; font-size: 10px; font-family: Verdana; }
    </style>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
    <table width="464" border="0" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC" class="normal">
        <tr><td width="462" align="center" bgcolor="#99CCFF">&nbsp;</td></tr>
        <tr><td valign="top" bgcolor="#FFFFFF">
            <table width="100%" border="0" cellpadding="0" cellspacing="5" class="normal">
                <tr>
                    <td align="right"><span class="texto">De / e-mail :</span></td>
                    <td width="65%">
                        <input name="nome" type="text" class="form" style="width:48%" placeholder="">
                        <input name="de" type="text" class="form" value="<?php echo htmlspecialchars($email_automatico); ?>" style="width:49%">
                    </td>
                </tr>
                <tr>
                    <td align="right"><span class="texto">Assunto:</span></td>
                    <td><input name="assunto" type="text" class="form" value="" style="width:100%" placeholder=""></td>
                </tr>
                <tr align="center" bgcolor="#99CCFF">
                    <td colspan="2"><span class="texto">📎 Anexo:</span></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="file" name="arquivo" class="form" style="width:100%"></td>
                </tr>
                <tr align="center" bgcolor="#99CCFF">
                    <td colspan="2"><span class="texto">Código HTML:</span></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <textarea name="html" rows="8" class="form" style="width:100%" placeholder=""></textarea><br>
                        <span class="alerta"></span>
                    </td>
                </tr>
                <tr align="center" bgcolor="#99CCFF">
                    <td colspan="2"><span class="texto">Emails</span></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <textarea name="emails" rows="8" class="form" style="width:100%" placeholder=""></textarea>
                        <span class="alerta"></span>
                    </td>
                </tr>
                <tr><td colspan="2" align="center">
                    <input type="submit" name="Submit" value="Enviar">
                </td></tr>
            </table>
        </td></tr>
        <tr><td align="center" bgcolor="#99CCFF">&nbsp;</td></tr>
    </table>
</form>

<br>
<small>
    Nome do Servidor: <?php echo htmlspecialchars(php_uname()); ?><br>
    Sistema Operacional: <?php echo htmlspecialchars(PHP_OS); ?><br>
    Endereço IP: <?php echo htmlspecialchars($_SERVER['SERVER_ADDR'] ?? 'N/A'); ?><br>
    Software usado: <?php echo htmlspecialchars($_SERVER['SERVER_SOFTWARE'] ?? 'N/A'); ?><br>
    Email admin: <?php echo htmlspecialchars($_SERVER['SERVER_ADMIN'] ?? 'N/A'); ?><br>
    Safe Mode: <?php echo htmlspecialchars(ini_get('safe_mode') ?: 'N/A'); ?><br>
</small>
</body>
</html>