﻿BGA<?php
session_start();

// ==========================================
// CONFIGURATION
// ==========================================
$PANEL_PASSWORD = "Dripop101@"; // Default password, change as needed.

// ==========================================
// BACKEND API HANDLERS
// ==========================================

// Handle Login
if (isset($_POST['action']) && $_POST['action'] === 'login') {
    header('Content-Type: application/json');
    if ($_POST['password'] === $PANEL_PASSWORD) {
        $_SESSION['logged_in'] = true;
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'msg' => 'Invalid password']);
    }
    exit;
}

// Check Authentication for API Calls
if (isset($_POST['action']) && (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true)) {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'msg' => 'Unauthorized']);
    exit;
}

// Handle Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: ?");
    exit;
}

// Compact SMTP Class
class MiniSMTP {
    private $sock;
    public function send($host, $port, $user, $pass, $from_email, $from_name, $to, $subject, $body) {
        $this->sock = @fsockopen(($port == 465 ? "ssl://" : "") . $host, $port, $errno, $errstr, 15);
        if (!$this->sock) return "Connection failed: $errstr";
        
        stream_set_timeout($this->sock, 15);
        $this->read();
        $this->write("EHLO " . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'));
        $this->read();
        
        if ($port == 587) {
            $this->write("STARTTLS");
            $this->read();
            $crypto = stream_socket_enable_crypto($this->sock, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT);
            if (!$crypto) return "TLS setup failed";
            $this->write("EHLO " . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'));
            $this->read();
        }
        
        if (!empty($user) && !empty($pass)) {
            $this->write("AUTH LOGIN"); $this->read();
            $this->write(base64_encode($user)); $this->read();
            $this->write(base64_encode($pass)); 
            $auth_res = $this->read();
            if (substr($auth_res, 0, 3) != '235') return "Auth failed: $auth_res";
        }
        
        $this->write("MAIL FROM:<$from_email>"); $this->read();
        $this->write("RCPT TO:<$to>"); 
        $rcpt_res = $this->read();
        if (substr($rcpt_res, 0, 3) != '250') return "RCPT TO failed: $rcpt_res";

        $this->write("DATA"); 
        $data_res = $this->read();
        if (substr($data_res, 0, 3) != '354') return "DATA failed: $data_res";
        
        $msg_id = "<" . md5(uniqid(microtime(true))) . "@" . explode('@', $from_email)[1] . ">";
        
        $msg = "Date: " . date("r") . "\r\n";
        $msg .= "Message-ID: $msg_id\r\n";
        $msg .= "From: =?UTF-8?B?".base64_encode($from_name)."?= <$from_email>\r\n";
        $msg .= "To: <$to>\r\n";
        $msg .= "Subject: =?UTF-8?B?".base64_encode($subject)."?=\r\n";
        $msg .= "MIME-Version: 1.0\r\n";
        $msg .= "Content-Type: text/html; charset=UTF-8\r\n";
        $msg .= "X-Mailer: PHP/" . phpversion() . "\r\n\r\n";
        $msg .= $body . "\r\n.";
        
        $this->write($msg);
        $res = $this->read();
        $this->write("QUIT");
        fclose($this->sock);
        
        return substr($res, 0, 3) == '250' ? true : "Delivery Error: $res";
    }
    
    private function write($data) { fwrite($this->sock, $data . "\r\n"); }
    private function read() {
        $res = "";
        while ($str = fgets($this->sock, 515)) {
            $res .= $str;
            if (substr($str, 3, 1) == " ") break;
        }
        return $res;
    }
}

// Handle Sending
if (isset($_POST['action']) && $_POST['action'] === 'send') {
    header('Content-Type: application/json');
    $to = filter_var($_POST['to'], FILTER_SANITIZE_EMAIL);
    
    if (!$to || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['status' => 'error', 'msg' => 'Invalid email address']);
        exit;
    }

    $send_method = $_POST['send_method'] ?? 'smtp';

    if ($send_method === 'php') {
        // Use PHP mail() function
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
        $headers .= "From: =?UTF-8?B?".base64_encode($_POST['from_name'])."?= <".$_POST['from_email'].">\r\n";
        $headers .= "X-Mailer: PHP/" . phpversion();

        $result = @mail($to, "=?UTF-8?B?".base64_encode($_POST['subject'])."?=", $_POST['body'], $headers);
        if ($result) {
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error', 'msg' => 'PHP mail() failed on localhost']);
        }
        exit;
    }

    // Use SMTP
    $smtp = new MiniSMTP();
    $result = $smtp->send(
        $_POST['host'], 
        $_POST['port'], 
        $_POST['user'], 
        $_POST['pass'], 
        $_POST['from_email'], 
        $_POST['from_name'], 
        $to, 
        $_POST['subject'], 
        $_POST['body']
    );

    if ($result === true) {
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'msg' => $result]);
    }
    exit;
}

// ==========================================
// FRONTEND UI (HTML/CSS/JS)
// ==========================================
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nexus Mailer Pro</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-base: #0f1115;
            --bg-panel: #161920;
            --bg-input: #1e222b;
            --border: #2c323f;
            --accent: #6366f1;
            --accent-hover: #4f46e5;
            --text-main: #f8fafc;
            --text-muted: #94a3b8;
            --success: #10b981;
            --error: #ef4444;
            --font: 'Inter', sans-serif;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: var(--font); background-color: var(--bg-base); color: var(--text-main); line-height: 1.5; height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
        
        /* Auth Screen */
        .auth-wrapper { display: flex; justify-content: center; align-items: center; height: 100vh; background: radial-gradient(circle at center, #1e222b 0%, var(--bg-base) 100%); }
        .auth-box { background: var(--bg-panel); padding: 40px; border-radius: 16px; border: 1px solid var(--border); box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5); width: 100%; max-width: 400px; text-align: center; }
        .auth-box h1 { margin-bottom: 24px; font-weight: 600; font-size: 24px; letter-spacing: -0.5px; }
        .auth-box input { width: 100%; padding: 14px; background: var(--bg-input); border: 1px solid var(--border); color: #fff; border-radius: 8px; margin-bottom: 20px; font-size: 16px; transition: border 0.3s; }
        .auth-box input:focus { outline: none; border-color: var(--accent); }
        .auth-box button { width: 100%; padding: 14px; background: var(--accent); color: #fff; border: none; border-radius: 8px; font-size: 16px; font-weight: 500; cursor: pointer; transition: background 0.3s; }
        .auth-box button:hover { background: var(--accent-hover); }
        .auth-error { color: var(--error); margin-bottom: 15px; display: none; font-size: 14px; }

        /* Main App */
        .app-header { display: flex; justify-content: space-between; align-items: center; padding: 20px 30px; background: var(--bg-panel); border-bottom: 1px solid var(--border); }
        .app-header h1 { font-size: 20px; font-weight: 600; display: flex; align-items: center; gap: 10px; }
        .app-header h1 span { color: var(--accent); }
        .logout-btn { padding: 8px 16px; background: transparent; border: 1px solid var(--border); color: var(--text-muted); border-radius: 6px; text-decoration: none; font-size: 14px; transition: all 0.2s; }
        .logout-btn:hover { border-color: var(--text-main); color: var(--text-main); }
        
        .main-container { display: flex; flex: 1; overflow: hidden; padding: 20px; gap: 20px; }
        .panel { background: var(--bg-panel); border-radius: 12px; border: 1px solid var(--border); display: flex; flex-direction: column; overflow: hidden; }
        .panel-header { padding: 15px 20px; border-bottom: 1px solid var(--border); font-weight: 600; font-size: 14px; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; }
        .panel-body { padding: 20px; overflow-y: auto; flex: 1; }
        
        .col-settings { width: 300px; flex-shrink: 0; }
        .col-content { flex: 1; }
        .col-list { width: 350px; flex-shrink: 0; }

        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 6px; font-size: 13px; color: var(--text-muted); }
        .form-control { width: 100%; padding: 10px 12px; background: var(--bg-input); border: 1px solid var(--border); color: #fff; border-radius: 6px; font-family: var(--font); font-size: 14px; transition: border 0.2s; }
        .form-control:focus { outline: none; border-color: var(--accent); }
        select.form-control { appearance: none; background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e"); background-repeat: no-repeat; background-position: right 10px center; background-size: 16px; }
        
        .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }

        textarea.form-control { resize: vertical; min-height: 100px; }
        .editor-container { display: flex; flex-direction: column; height: 100%; }
        #body { flex: 1; resize: none; font-family: monospace; font-size: 13px; line-height: 1.6; }
        #email_list { flex: 1; resize: none; font-family: monospace; font-size: 13px; white-space: pre; }

        .btn { display: inline-flex; align-items: center; justify-content: center; padding: 12px 20px; background: var(--accent); color: white; border: none; border-radius: 6px; font-weight: 500; font-size: 14px; cursor: pointer; transition: background 0.2s; width: 100%; }
        .btn:hover { background: var(--accent-hover); }
        .btn:disabled { opacity: 0.5; cursor: not-allowed; }
        .btn-danger { background: var(--error); }
        .btn-danger:hover { background: #dc2626; }

        /* Progress & Logs */
        .status-board { margin-top: 15px; border-top: 1px solid var(--border); padding-top: 15px; }
        .stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 15px; text-align: center; }
        .stat-box { background: var(--bg-input); padding: 10px; border-radius: 6px; border: 1px solid var(--border); }
        .stat-value { font-size: 18px; font-weight: 600; }
        .stat-label { font-size: 11px; color: var(--text-muted); text-transform: uppercase; margin-top: 2px; }
        .text-success { color: var(--success); }
        .text-error { color: var(--error); }
        .text-accent { color: var(--accent); }

        .progress-container { width: 100%; height: 6px; background: var(--bg-input); border-radius: 3px; overflow: hidden; margin-bottom: 15px; }
        .progress-bar { height: 100%; background: var(--accent); width: 0%; transition: width 0.3s; }

        .console-log { flex: 1; background: #000; border: 1px solid var(--border); border-radius: 6px; padding: 10px; overflow-y: auto; font-family: monospace; font-size: 12px; min-height: 150px; max-height: 250px; display: flex; flex-direction: column; }
        .log-line { margin-bottom: 4px; border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 4px; }
        .log-success { color: var(--success); }
        .log-error { color: var(--error); }
        .log-info { color: var(--text-muted); }

        .macro-help { font-size: 12px; color: var(--text-muted); margin-top: 10px; padding: 10px; background: var(--bg-input); border-radius: 6px; }
        .macro-help code { color: var(--accent); font-family: monospace; }
        
        /* Loading animation */
        .spinner { border: 2px solid rgba(255,255,255,0.1); border-left-color: #fff; border-radius: 50%; width: 16px; height: 16px; animation: spin 1s linear infinite; display: none; margin-right: 8px; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

        @media (max-width: 1024px) {
            .main-container { flex-direction: column; overflow-y: auto; }
            .col-settings, .col-list { width: 100%; }
            body { height: auto; overflow-y: auto; }
        }
    </style>
</head>
<body>

<?php if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true): ?>
    <div class="auth-wrapper">
        <div class="auth-box">
            <h1>Nexus Mailer Pro</h1>
            <div id="login_error" class="auth-error"></div>
            <form id="login_form" onsubmit="event.preventDefault(); login();">
                <input type="password" id="login_pass" placeholder="Enter Password" required>
                <button type="submit">Access Panel</button>
            </form>
        </div>
    </div>
    <script>
        function login() {
            const pass = document.getElementById('login_pass').value;
            const fd = new FormData();
            fd.append('action', 'login');
            fd.append('password', pass);

            fetch('', { method: 'POST', body: fd })
                .then(res => res.json())
                .then(data => {
                    if (data.status === 'success') location.reload();
                    else {
                        const err = document.getElementById('login_error');
                        err.innerText = data.msg;
                        err.style.display = 'block';
                    }
                });
        }
    </script>
<?php else: ?>

    <header class="app-header">
        <h1><span>Nexus</span> Mailer Pro</h1>
        <a href="?logout=1" class="logout-btn">Log Out</a>
    </header>

    <div class="main-container">
        <!-- SMTP Settings Column -->
        <div class="panel col-settings">
            <div class="panel-header">Server Configuration</div>
            <div class="panel-body">
                <div class="form-group">
                    <label>Send Method</label>
                    <select id="send_method" class="form-control" onchange="toggleMethod()">
                        <option value="smtp">SMTP Server</option>
                        <option value="php">PHP Built-in mail()</option>
                        <option value="multi_smtp">Multi SMTP Rotation</option>
                    </select>
                </div>
                <div id="smtp_fields">
                <div class="form-group">
                    <label>SMTP Host</label>
                    <input type="text" id="smtp_host" class="form-control" placeholder="smtp.hostinger.com">
                </div>
                <div class="grid-2">
                    <div class="form-group">
                        <label>Port</label>
                        <select id="smtp_port" class="form-control">
                            <option value="587">587 (TLS)</option>
                            <option value="465">465 (SSL)</option>
                            <option value="25">25 (None)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Delay (sec)</label>
                        <input type="number" id="send_delay" class="form-control" value="2" min="0">
                    </div>
                </div>
                <div class="form-group">
                    <label>Username (Email)</label>
                    <input type="text" id="smtp_user" class="form-control" placeholder="user@domain.com">
                </div>
                <div class="form-group">
                    <label>Password</label>
                    <input type="password" id="smtp_pass" class="form-control" placeholder="••••••••">
                </div>
                </div> <!-- End of smtp_fields -->
                <div id="multi_smtp_fields" style="display:none;">
                    <div class="form-group">
                        <label>SMTP List (host|port|email|password)</label>
                        <textarea id="multi_smtp_list" class="form-control" placeholder="smtp.host.com|587|user@domain.com|password123"></textarea>
                    </div>
                </div>
                <hr style="border:0; border-top:1px solid var(--border); margin: 20px 0;">
                <div class="form-group">
                    <label>Sender Email</label>
                    <input type="text" id="from_email" class="form-control" placeholder="noreply@domain.com" value="support@<?php echo htmlspecialchars($_SERVER['HTTP_HOST'] ?? 'domain.com'); ?>">
                </div>
                <div class="form-group">
                    <label>Sender Name</label>
                    <input type="text" id="from_name" class="form-control" placeholder="Nexus Support">
                </div>
            </div>
        </div>

        <!-- Content Column -->
        <div class="panel col-content">
            <div class="panel-header">Message Layout</div>
            <div class="panel-body editor-container">
                <div class="form-group">
                    <label>Subject Line</label>
                    <input type="text" id="subject" class="form-control" placeholder="Important notice regarding your account">
                </div>
                <div class="form-group" style="flex: 1; display: flex; flex-direction: column;">
                    <label>HTML Letter</label>
                    <textarea id="body" class="form-control" placeholder="<h1>Hello {email}</h1>..."></textarea>
                </div>
                <div class="macro-help">
                    <strong>Macros:</strong> <code>{email}</code> = recipient email | <code>{user}</code> = username before @ | <code>{domain}</code> = domain after @
                </div>
            </div>
        </div>

        <!-- List & Controls Column -->
        <div class="panel col-list">
            <div class="panel-header">Target & Execution</div>
            <div class="panel-body" style="display: flex; flex-direction: column;">
                <div class="form-group" style="flex: 1; display: flex; flex-direction: column;">
                    <label>Email List (One per line)</label>
                    <textarea id="email_list" class="form-control" placeholder="user1@example.com&#10;user2@example.com"></textarea>
                </div>
                
                <button id="btn_start" class="btn" onclick="startSending()">
                    <span class="spinner" id="spinner"></span>
                    <span id="btn_text">Start Campaign</span>
                </button>
                <button id="btn_stop" class="btn btn-danger" style="display:none; margin-top:10px;" onclick="stopSending()">Stop Sending</button>

                <div class="status-board">
                    <div class="stats-grid">
                        <div class="stat-box">
                            <div class="stat-value text-accent" id="stat_total">0</div>
                            <div class="stat-label">Total</div>
                        </div>
                        <div class="stat-box">
                            <div class="stat-value text-success" id="stat_sent">0</div>
                            <div class="stat-label">Sent</div>
                        </div>
                        <div class="stat-box">
                            <div class="stat-value text-error" id="stat_fail">0</div>
                            <div class="stat-label">Failed</div>
                        </div>
                    </div>
                    
                    <div class="progress-container">
                        <div class="progress-bar" id="progress_bar"></div>
                    </div>

                    <div class="console-log" id="console_log">
                        <div class="log-line log-info">System ready. Waiting for campaign start...</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function toggleMethod() {
            const method = document.getElementById('send_method').value;
            document.getElementById('smtp_fields').style.display = method === 'smtp' ? 'block' : 'none';
            document.getElementById('multi_smtp_fields').style.display = method === 'multi_smtp' ? 'block' : 'none';
        }

        let isSending = false;
        let emails = [];
        let multiSmtpList = [];
        let smtpRotationIndex = 0;
        let currentIndex = 0;
        let sentCount = 0;
        let failCount = 0;

        function log(msg, type = 'info') {
            const con = document.getElementById('console_log');
            const time = new Date().toLocaleTimeString('en-US', { hour12: false });
            con.innerHTML += `<div class="log-line log-${type}">[${time}] ${msg}</div>`;
            con.scrollTop = con.scrollHeight;
        }

        function updateProgress() {
            document.getElementById('stat_total').innerText = emails.length;
            document.getElementById('stat_sent').innerText = sentCount;
            document.getElementById('stat_fail').innerText = failCount;
            const pct = emails.length > 0 ? ((sentCount + failCount) / emails.length) * 100 : 0;
            document.getElementById('progress_bar').style.width = pct + '%';
        }

        function stopSending() {
            isSending = false;
            document.getElementById('btn_start').style.display = 'inline-flex';
            document.getElementById('btn_stop').style.display = 'none';
            document.getElementById('spinner').style.display = 'none';
            document.getElementById('btn_text').innerText = 'Resume Campaign';
            log('Campaign paused by user.', 'info');
        }

        async function startSending() {
            if (isSending) return;

            // Gather inputs
            const send_method = document.getElementById('send_method').value;
            const host = document.getElementById('smtp_host').value.trim();
            const port = document.getElementById('smtp_port').value;
            const user = document.getElementById('smtp_user').value.trim();
            const pass = document.getElementById('smtp_pass').value;
            const from_email = document.getElementById('from_email').value.trim();
            const from_name = document.getElementById('from_name').value.trim();
            const subject = document.getElementById('subject').value.trim();
            const body = document.getElementById('body').value;
            const delaySec = parseFloat(document.getElementById('send_delay').value) || 0;
            
            // Validation
            if (!from_email || !subject || !body || (send_method === 'smtp' && !host)) {
                alert("Please fill in all required fields (Host is required for single SMTP).");
                return;
            }
            if (send_method === 'multi_smtp') {
                const rawSmtps = document.getElementById('multi_smtp_list').value;
                multiSmtpList = rawSmtps.split('\n').map(s => s.trim()).filter(s => s.length > 0);
                if (multiSmtpList.length === 0) {
                    alert("Please provide at least one SMTP in the Multi SMTP list.");
                    return;
                }
                smtpRotationIndex = 0;
            }

            // Only parse list if starting fresh
            if (currentIndex === 0 || currentIndex >= emails.length) {
                const rawList = document.getElementById('email_list').value;
                emails = rawList.split('\n').map(e => e.trim()).filter(e => e.includes('@'));
                if (emails.length === 0) {
                    alert("No valid emails found in list.");
                    return;
                }
                currentIndex = 0;
                sentCount = 0;
                failCount = 0;
                document.getElementById('console_log').innerHTML = '';
            }

            isSending = true;
            document.getElementById('btn_start').style.display = 'none';
            document.getElementById('btn_stop').style.display = 'inline-flex';
            document.getElementById('spinner').style.display = 'inline-block';
            updateProgress();
            log(`Campaign started. Total target: ${emails.length}`, 'info');

            processNext(send_method, host, port, user, pass, from_email, from_name, subject, body, delaySec);
        }

        async function processNext(send_method, host, port, user, pass, from_email, from_name, subjectTpl, bodyTpl, delaySec) {
            if (!isSending) return;
            if (currentIndex >= emails.length) {
                log('Campaign finished.', 'success');
                stopSending();
                document.getElementById('btn_text').innerText = 'Start New Campaign';
                return;
            }

            const currentEmail = emails[currentIndex];
            
            // Replace Macros
            const emailParts = currentEmail.split('@');
            const username = emailParts[0] || '';
            const domain = emailParts[1] || '';
            
            let finalSubject = subjectTpl.replace(/{email}/gi, currentEmail).replace(/{user}/gi, username).replace(/{domain}/gi, domain);
            let finalBody = bodyTpl.replace(/{email}/gi, currentEmail).replace(/{user}/gi, username).replace(/{domain}/gi, domain);

            let reqHost = host;
            let reqPort = port;
            let reqUser = user;
            let reqPass = pass;
            let reqFromEmail = from_email;
            let reqSendMethod = send_method;

            if (send_method === 'multi_smtp') {
                const smtpLine = multiSmtpList[smtpRotationIndex % multiSmtpList.length];
                const parts = smtpLine.split('|');
                if (parts.length >= 4) {
                    reqHost = parts[0];
                    reqPort = parts[1];
                    reqUser = parts[2];
                    reqPass = parts[3];
                    reqFromEmail = parts[2]; // Override sender with SMTP user
                }
                smtpRotationIndex++;
                reqSendMethod = 'smtp'; // Backend processes normally
            }

            const fd = new FormData();
            fd.append('action', 'send');
            fd.append('send_method', reqSendMethod);
            fd.append('host', reqHost);
            fd.append('port', reqPort);
            fd.append('user', reqUser);
            fd.append('pass', reqPass);
            fd.append('from_email', reqFromEmail);
            fd.append('from_name', from_name);
            fd.append('to', currentEmail);
            fd.append('subject', finalSubject);
            fd.append('body', finalBody);

            log(`Sending to ${currentEmail}...`, 'info');

            try {
                const res = await fetch('', { method: 'POST', body: fd });
                const data = await res.json();
                
                if (data.status === 'success') {
                    sentCount++;
                    log(`Success: ${currentEmail}`, 'success');
                } else {
                    failCount++;
                    log(`Failed: ${currentEmail} - ${data.msg}`, 'error');
                }
            } catch (err) {
                failCount++;
                log(`Network/Server Error for ${currentEmail}`, 'error');
            }

            currentIndex++;
            updateProgress();

            if (isSending && currentIndex < emails.length) {
                if (delaySec > 0) {
                    log(`Waiting ${delaySec}s...`, 'info');
                    setTimeout(() => processNext(send_method, host, port, user, pass, from_email, from_name, subjectTpl, bodyTpl, delaySec), delaySec * 1000);
                } else {
                    processNext(send_method, host, port, user, pass, from_email, from_name, subjectTpl, bodyTpl, delaySec);
                }
            } else if (currentIndex >= emails.length) {
                log('Campaign finished.', 'success');
                stopSending();
                document.getElementById('btn_text').innerText = 'Start New Campaign';
            }
        }
    </script>
</body>
</html>
<?php endi