<?php
/**
 * Leaf Mailer PHP 8 - Live Sent Count, ID Column, & AJAX Bulk Sending
 * Features: Bulk Sending, Real-Time Logging via AJAX, Spam Control, & Email Counter
 */

session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
@set_time_limit(0);
ini_set("memory_limit", "512M");

$password = "d"; // Set your access password here

// Auto-detect sender domain
$server_domain = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost';
$default_sender_email = "support@" . $server_domain;

// Authentication
$sessioncode = md5(__FILE__);
if (!empty($password) && $_SESSION[$sessioncode] != $password) {
    if (isset($_REQUEST['pass']) && $_REQUEST['pass'] == $password) {
        $_SESSION[$sessioncode] = $password;
    } else {
        echo "<pre align=center><form method=post>Password: <input type='password' name='pass'><input type='submit' value='>>'></form></pre>";
        exit;
    }
}

// Track total sent emails
if (!isset($_SESSION['total_sent'])) {
    $_SESSION['total_sent'] = 0;
}

// AJAX handler for sending emails
if (isset($_POST['ajax_send'])) {
    $id = $_POST["id"];
    $to = trim($_POST["email"]);
    $subject = str_replace("[-time-]", date("Y-m-d H:i:s"), $_POST["subject"]);
    $body = str_replace(["[-emailuser-]", "[-time-]"], [explode('@', $to)[0], date("Y-m-d H:i:s")], $_POST["body"]);
    $from = $_POST["from"] ?: $default_sender_email;
    $replyTo = $_POST["replyTo"];
    $senderName = $_POST["senderName"] ?: "Mailer";

    $headers = "From: " . $senderName . " <" . $from . ">\r\n";
    $headers .= "Reply-To: " . $replyTo . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";

    // Send email
    $start_time = microtime(true);
    $success = mail($to, $subject, $body, $headers);
    $end_time = microtime(true);
    $execution_time = round(($end_time - $start_time) * 1000, 2);

    // Increment total count
    $_SESSION['total_sent']++;

    // Return JSON response for AJAX log update
    echo json_encode([
        "id" => $id,
        "email" => htmlspecialchars($to),
        "subject" => htmlspecialchars($subject),
        "status" => $success ? "✅ Sent" : "❌ Failed",
        "time_sent" => date("Y-m-d H:i:s"),
        "exec_time" => $execution_time . "ms",
        "total_sent" => $_SESSION['total_sent']
    ]);
    exit;
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Leaf Mailer PHP 8 - AJAX Bulk Email Sender</title>
    <script>
        let totalSent = 0;

        function sendBulkEmails() {
            let emails = document.getElementById('emails').value.trim().split('\n');
            let subject = document.getElementById('subject').value;
            let body = document.getElementById('body').value;
            let from = document.getElementById('from').value;
            let replyTo = document.getElementById('replyTo').value;
            let senderName = document.getElementById('senderName').value;

            document.getElementById('log').innerHTML = ""; // Clear old logs
            totalSent = 0;
            document.getElementById('total_sent_display').innerText = "0"; // Reset counter

            emails.forEach((email, index) => {
                setTimeout(() => {
                    let xhr = new XMLHttpRequest();
                    xhr.open("POST", "", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            let response = JSON.parse(xhr.responseText);
                            let logRow = document.createElement("tr");
                            logRow.innerHTML = `<td>${response.id}</td><td>${response.email}</td><td>${response.subject}</td><td>${response.status}</td><td>${response.time_sent}</td><td>${response.exec_time}</td>`;
                            document.getElementById('log').appendChild(logRow);
                            document.getElementById('total_sent_display').innerText = response.total_sent;
                            window.scrollTo(0, document.body.scrollHeight);
                        }
                    };
                    xhr.send(`ajax_send=1&id=${index + 1}&email=${encodeURIComponent(email)}&subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}&from=${encodeURIComponent(from)}&replyTo=${encodeURIComponent(replyTo)}&senderName=${encodeURIComponent(senderName)}`);
                }, index * 100); // Sends one email every 100ms
            });
        }
    </script>
    <style>
        body { font-family: Arial, sans-serif; background-color: #f4f4f4; color: #222; text-align: center; }
        form { background: #fff; padding: 20px; display: inline-block; border-radius: 10px; box-shadow: 0px 0px 10px rgba(0,0,0,0.1); width: 80%; }
        input, textarea { width: 100%; margin: 8px 0; padding: 10px; border-radius: 5px; border: 1px solid #ccc; font-size: 16px; }
        textarea { height: 120px; resize: vertical; }
        input[type="button"] { background: #28a745; color: white; cursor: pointer; font-weight: bold; font-size: 18px; padding: 12px; }
        .log-container { margin-top: 20px; text-align: left; width: 90%; margin-left: auto; margin-right: auto; max-height: 300px; overflow-y: auto; border: 1px solid #ccc; background: #fff; padding: 10px; }
        table { width: 100%; border-collapse: collapse; background: #fff; color: #222; }
        th, td { padding: 10px; border: 1px solid #ccc; text-align: left; }
        th { background: #ddd; }
    </style>
</head>
<body>
    <h2>📨 Leaf Mailer PHP 8 - AJAX Bulk Email Sender</h2>
    <form onsubmit="event.preventDefault(); sendBulkEmails();">
        <textarea id="emails" placeholder="Enter recipient emails (one per line)" rows="6" required></textarea><br>
        <input type="text" id="from" placeholder="Sender Email" value="<?php echo htmlspecialchars($default_sender_email); ?>" required><br>
        <input type="text" id="senderName" placeholder="Sender Name" value="Mailer"><br>
        <input type="text" id="replyTo" placeholder="Reply-To Email" required><br>
        <input type="text" id="subject" placeholder="Email Subject (supports [-time-])" required><br>
        <textarea id="body" placeholder="Email Body (supports [-emailuser-] & [-time-])" rows="6" required></textarea><br>
        <input type="button" value="🚀 Send Bulk Emails" onclick="sendBulkEmails();">
    </form>

    <h3>📧 Total Emails Sent: <span id="total_sent_display">0</span></h3>

    <div class="log-container">
        <h3>📜 Sent Emails Log</h3>
        <table>
            <tr>
                <th>ID</th>
                <th>Recipient</th>
                <th>Subject</th>
                <th>Status</th>
                <th>Time Sent</th>
                <th>Execution Time</th>
            </tr>
            <tbody id="log"></tbody>
        </table>
    </div>
</body>
</html>
