<?php
// ================================================================
//  🔥 MAILER v7.2 - FAST MODE
// ================================================================

// ============================================================
//  CONFIGURATION
// ============================================================
error_reporting(0);
ini_set('display_errors', 0);
ini_set('max_execution_time', 30);
ini_set('memory_limit', '128M');
ignore_user_abort(true);

$settings_file = __DIR__ . '/.mailer-settings.json';
$lock_file = __DIR__ . '/.mailer.lock';

$defaults = [
    'subject'    => '',
    'from_name'  => '',
    'letter'     => '',
    'emails'     => '',
    'offset'     => 0,
    'total_sent' => 0,
    'total_failed' => 0,
    'html_mode'  => true,
    'speed'      => 'fast'  // NEW: fast, medium, slow
];

if (file_exists($settings_file)) {
    $settings = json_decode(file_get_contents($settings_file), true);
    if (!is_array($settings)) $settings = $defaults;
} else {
    $settings = $defaults;
    file_put_contents($settings_file, json_encode($settings, JSON_PRETTY_PRINT));
}

// ============================================================
//  ATOMIC: Get Next Email
// ============================================================
function get_next_email() {
    global $settings_file, $lock_file;
    
    $fp = fopen($lock_file, 'w');
    if (!flock($fp, LOCK_EX)) {
        fclose($fp);
        return ['error' => 'Could not acquire lock'];
    }
    
    if (!file_exists($settings_file)) {
        flock($fp, LOCK_UN);
        fclose($fp);
        return ['error' => 'Settings file not found'];
    }
    
    $settings = json_decode(file_get_contents($settings_file), true);
    if (!is_array($settings)) $settings = [];
    
    $emails = explode("\n", $settings['emails'] ?? '');
    $emails = array_filter(array_map('trim', $emails));
    $total = count($emails);
    $offset = intval($settings['offset'] ?? 0);
    
    if ($offset >= $total) {
        flock($fp, LOCK_UN);
        fclose($fp);
        return ['completed' => true, 'total' => $total];
    }
    
    $email = trim($emails[$offset]);
    $settings['offset'] = $offset + 1;
    file_put_contents($settings_file, json_encode($settings, JSON_PRETTY_PRINT));
    
    flock($fp, LOCK_UN);
    fclose($fp);
    
    return [
        'completed' => false,
        'index' => $offset,
        'email' => $email,
        'total' => $total
    ];
}

// ============================================================
//  BUILD HTML EMAIL
// ============================================================
function build_multipart_email($html_content) {
    $text_content = strip_tags($html_content);
    $text_content = preg_replace('/\s+/', ' ', $text_content);
    $text_content = trim($text_content);
    
    $boundary = md5(uniqid(time()));
    
    $email = "--$boundary\n";
    $email .= "Content-Type: text/plain; charset=UTF-8\n";
    $email .= "Content-Transfer-Encoding: 7bit\n\n";
    $email .= $text_content . "\n\n";
    
    $email .= "--$boundary\n";
    $email .= "Content-Type: text/html; charset=UTF-8\n";
    $email .= "Content-Transfer-Encoding: 7bit\n\n";
    $email .= $html_content . "\n\n";
    
    $email .= "--$boundary--";
    
    return ['content' => $email, 'boundary' => $boundary];
}

// ============================================================
//  AJAX HANDLERS
// ============================================================
if (isset($_POST['get_next'])) {
    header('Content-Type: application/json');
    $result = get_next_email();
    echo json_encode($result);
    exit;
}

if (isset($_POST['send_one'])) {
    header('Content-Type: application/json');
    
    $index = intval($_POST['index'] ?? 0);
    $email = trim($_POST['email'] ?? '');
    
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['sent' => false, 'error' => 'Invalid email']);
        exit;
    }
    
    if (file_exists($settings_file)) {
        $settings = json_decode(file_get_contents($settings_file), true);
        if (!is_array($settings)) $settings = $defaults;
    }
    
    $domain = $_SERVER['SERVER_NAME'];
    $from_email = "support@" . $domain;
    $from_display = !empty($settings['from_name']) ? $settings['from_name'] : "Mailer";
    
    $is_html = $settings['html_mode'] ?? true;
    $raw_content = $settings['letter'] ?? '';
    
    if ($is_html && (stripos($raw_content, '<html') !== false || stripos($raw_content, '<body') !== false || stripos($raw_content, '<div') !== false || stripos($raw_content, '<table') !== false)) {
        $multipart = build_multipart_email($raw_content);
        $email_content = $multipart['content'];
        $content_type = "multipart/alternative; boundary=\"" . $multipart['boundary'] . "\"";
    } else {
        $email_content = $raw_content;
        $content_type = "text/plain; charset=UTF-8";
    }
    
    $headers = "From: \"$from_display\" <$from_email>\r\n";
    $headers .= "Reply-To: $from_email\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: $content_type\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
    $headers .= "X-Priority: 3\r\n";
    $headers .= "Message-ID: <" . time() . "." . md5(uniqid() . $email) . "@$domain>\r\n";
    $headers .= "Date: " . date('r') . "\r\n";
    
    $sent = mail($email, $settings['subject'] ?? '', $email_content, $headers);
    
    $fp = fopen($lock_file, 'w');
    if (flock($fp, LOCK_EX)) {
        if (file_exists($settings_file)) {
            $settings = json_decode(file_get_contents($settings_file), true);
            if (!is_array($settings)) $settings = $defaults;
        }
        
        if ($sent) {
            $settings['total_sent'] = intval($settings['total_sent'] ?? 0) + 1;
        } else {
            $settings['total_failed'] = intval($settings['total_failed'] ?? 0) + 1;
        }
        file_put_contents($settings_file, json_encode($settings, JSON_PRETTY_PRINT));
        flock($fp, LOCK_UN);
    }
    fclose($fp);
    
    echo json_encode([
        'sent' => $sent,
        'email' => $email,
        'index' => $index,
        'error' => $sent ? '' : 'Mail function failed'
    ]);
    exit;
}

if (isset($_POST['save_settings'])) {
    header('Content-Type: application/json');
    $settings['subject'] = $_POST['subject'] ?? '';
    $settings['from_name'] = $_POST['from_name'] ?? '';
    $settings['letter'] = $_POST['letter'] ?? '';
    $settings['emails'] = $_POST['emails'] ?? '';
    $settings['html_mode'] = isset($_POST['html_mode']) ? true : false;
    $settings['speed'] = $_POST['speed'] ?? 'fast';
    $settings['offset'] = 0;
    $settings['total_sent'] = 0;
    $settings['total_failed'] = 0;
    file_put_contents($settings_file, json_encode($settings, JSON_PRETTY_PRINT));
    echo json_encode(['success' => true]);
    exit;
}

if (isset($_POST['reset'])) {
    header('Content-Type: application/json');
    if (file_exists($settings_file)) {
        $settings = json_decode(file_get_contents($settings_file), true);
        if (is_array($settings)) {
            $settings['offset'] = 0;
            $settings['total_sent'] = 0;
            $settings['total_failed'] = 0;
            file_put_contents($settings_file, json_encode($settings, JSON_PRETTY_PRINT));
        }
    }
    echo json_encode(['success' => true]);
    exit;
}

// ============================================================
//  HTML PAGE
// ============================================================
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Carder DZ - Mailer v7.2</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            background: #0a0e17;
            font-family: Arial, sans-serif;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        .container {
            background: #141b2b;
            border-radius: 16px;
            padding: 40px;
            width: 100%;
            max-width: 1000px;
            border: 1px solid #2a3a5a;
        }
        .header {
            text-align: center;
            margin-bottom: 25px;
        }
        .header h1 {
            color: #00d4ff;
            font-size: 28px;
            letter-spacing: 2px;
        }
        .header p {
            color: #6a7a9a;
            font-size: 13px;
            margin-top: 5px;
        }
        .badge {
            display: inline-block;
            background: #4CAF5022;
            color: #4CAF50;
            padding: 2px 10px;
            border-radius: 12px;
            font-size: 11px;
            border: 1px solid #4CAF5044;
        }
        .badge-fast {
            background: #FF980022;
            color: #FF9800;
            border-color: #FF980044;
        }
        .row {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }
        .col {
            flex: 1;
            min-width: 280px;
        }
        .form-group {
            margin-bottom: 14px;
        }
        .form-group label {
            color: #8a9abb;
            font-size: 12px;
            font-weight: 600;
            display: block;
            margin-bottom: 4px;
            letter-spacing: 0.5px;
        }
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 10px 14px;
            background: #0a0e17;
            border: 1px solid #2a3a5a;
            border-radius: 8px;
            color: #e0e8f0;
            font-size: 14px;
            transition: all 0.3s;
            font-family: inherit;
        }
        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            border-color: #00d4ff;
            outline: none;
        }
        .form-group textarea {
            min-height: 120px;
            resize: vertical;
            font-family: 'Courier New', monospace;
            font-size: 13px;
        }
        .form-group .hint {
            color: #5a6a8a;
            font-size: 11px;
            margin-top: 3px;
        }
        .form-group select {
            cursor: pointer;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%238a9abb' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 12px center;
        }
        .btn {
            background: #00d4ff;
            color: #0a0e17;
            border: none;
            padding: 14px 30px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            letter-spacing: 1px;
        }
        .btn:hover:not(:disabled) {
            transform: scale(1.01);
            box-shadow: 0 0 30px rgba(0,212,255,0.2);
        }
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .btn-danger {
            background: #ff4444;
            color: #fff;
        }
        .btn-warning {
            background: #FF9800;
            color: #fff;
        }
        .btn-sm {
            padding: 8px 15px;
            font-size: 13px;
            width: auto;
        }
        .btn-fast {
            background: linear-gradient(135deg, #00d4ff, #4CAF50);
        }
        .status-bar {
            background: #0a0e17;
            border-radius: 10px;
            padding: 18px;
            margin-top: 20px;
            border: 1px solid #1a2a4a;
            display: none;
        }
        .status-bar.active {
            display: block;
        }
        .stats {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            margin-bottom: 12px;
        }
        .stat {
            background: #0a0e17;
            padding: 8px 16px;
            border-radius: 8px;
            text-align: center;
            flex: 1;
            min-width: 70px;
            border: 1px solid #1a2a4a;
        }
        .stat-value {
            font-size: 20px;
            font-weight: 700;
        }
        .stat-label {
            color: #6a7a9a;
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .stat-sent .stat-value { color: #4CAF50; }
        .stat-failed .stat-value { color: #f44336; }
        .stat-total .stat-value { color: #00d4ff; }
        .stat-progress .stat-value { color: #FF9800; }
        
        .progress-container {
            width: 100%;
            background: #0a0e17;
            border-radius: 8px;
            height: 24px;
            overflow: hidden;
            border: 1px solid #1a2a4a;
            margin-bottom: 10px;
        }
        .progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #00d4ff, #4CAF50);
            width: 0%;
            transition: width 0.5s ease;
            border-radius: 8px;
            line-height: 24px;
            color: #0a0e17;
            font-size: 12px;
            font-weight: 700;
            text-align: center;
        }
        .logs {
            max-height: 200px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            background: #05080f;
            padding: 10px;
            border-radius: 6px;
            border: 1px solid #0a1a2a;
        }
        .logs::-webkit-scrollbar { width: 5px; }
        .logs::-webkit-scrollbar-track { background: #0a0e17; }
        .logs::-webkit-scrollbar-thumb { background: #1a2a4a; border-radius: 3px; }
        .log-success { color: #4CAF50; }
        .log-failed { color: #f44336; }
        .log-info { color: #FF9800; }
        
        .controls {
            display: flex;
            gap: 10px;
            margin-top: 10px;
            flex-wrap: wrap;
        }
        .controls .btn {
            flex: 1;
            padding: 10px;
            font-size: 14px;
            min-width: 100px;
        }
        .toggle-container {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 8px 0;
        }
        .toggle {
            position: relative;
            width: 44px;
            height: 24px;
            background: #2a3a5a;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .toggle.active { background: #00d4ff; }
        .toggle-slider {
            position: absolute;
            top: 2px;
            left: 2px;
            width: 20px;
            height: 20px;
            background: #fff;
            border-radius: 50%;
            transition: all 0.3s;
        }
        .toggle.active .toggle-slider { left: 22px; }
        .toggle-label { color: #8a9abb; font-size: 13px; }
        
        @media (max-width: 768px) {
            .container { padding: 20px; }
            .col { min-width: 100%; }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>⚡ CARDER DZ MAILER</h1>
        <p>v7.2 — <span class="badge">NO DUPLICATES</span> <span class="badge badge-fast">FAST MODE</span></p>
    </div>
    
    <form id="mailForm">
        <div class="row">
            <div class="col">
                <div class="form-group">
                    <label>📧 SUBJECT</label>
                    <input type="text" name="subject" id="subject" placeholder="Subject" value="<?= htmlspecialchars($settings['subject']) ?>">
                </div>
                <div class="form-group">
                    <label>👤 FROM NAME</label>
                    <input type="text" name="from_name" id="from_name" placeholder="Your Name" value="<?= htmlspecialchars($settings['from_name']) ?>">
                </div>
                <div class="form-group">
                    <label>📝 MESSAGE</label>
                    <textarea name="letter" id="letter" placeholder="Message"><?= htmlspecialchars($settings['letter']) ?></textarea>
                </div>
            </div>
            <div class="col">
                <div class="form-group">
                    <label>📋 EMAIL LIST</label>
                    <textarea name="emails" id="mlist" placeholder="email1@domain.com&#10;email2@domain.com"><?= htmlspecialchars($settings['emails']) ?></textarea>
                    <div class="hint">One email per line — each gets ONE message</div>
                </div>
                <div class="form-group">
                    <label>⚡ SPEED</label>
                    <select name="speed" id="speed">
                        <option value="fast" <?= ($settings['speed'] ?? 'fast') == 'fast' ? 'selected' : '' ?>>🚀 Fast (0.3s delay)</option>
                        <option value="medium" <?= ($settings['speed'] ?? 'fast') == 'medium' ? 'selected' : '' ?>>⚡ Medium (0.7s delay)</option>
                        <option value="slow" <?= ($settings['speed'] ?? 'fast') == 'slow' ? 'selected' : '' ?>>🐢 Slow (1.5s delay)</option>
                        <option value="turbo" <?= ($settings['speed'] ?? 'fast') == 'turbo' ? 'selected' : '' ?>>🔥 Turbo (no delay)</option>
                    </select>
                    <div class="hint">Faster = more emails per minute, but higher spam risk</div>
                </div>
                <div class="toggle-container">
                    <div class="toggle <?= $settings['html_mode'] ? 'active' : '' ?>" id="htmlToggle" onclick="toggleHTML()">
                        <div class="toggle-slider"></div>
                    </div>
                    <span class="toggle-label" id="htmlLabel"><?= $settings['html_mode'] ? '🔷 HTML Mode' : '⬜ Text Mode' ?></span>
                </div>
                <div style="display:flex;gap:10px;flex-wrap:wrap;">
                    <button type="button" class="btn btn-sm btn-fast" id="sendBtn" style="flex:2;">🚀 SEND</button>
                    <button type="button" class="btn btn-sm btn-danger" id="stopBtn" style="display:none;flex:1;">⏹ STOP</button>
                    <button type="button" class="btn btn-sm btn-warning" id="resetBtn" style="flex:1;">↺ RESET</button>
                </div>
            </div>
        </div>
    </form>
    
    <div class="status-bar" id="statusBar">
        <div class="stats">
            <div class="stat stat-total"><div class="stat-value" id="totalCount">0</div><div class="stat-label">Total</div></div>
            <div class="stat stat-sent"><div class="stat-value" id="sentCount">0</div><div class="stat-label">Sent</div></div>
            <div class="stat stat-failed"><div class="stat-value" id="failedCount">0</div><div class="stat-label">Failed</div></div>
            <div class="stat stat-progress"><div class="stat-value" id="progressPercent">0%</div><div class="stat-label">Progress</div></div>
        </div>
        <div class="progress-container">
            <div class="progress-bar" id="progressBar">0%</div>
        </div>
        <div class="logs" id="logs">
            <div class="log-info">⏳ Ready. Click SEND to start.</div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // ============================================================
    //  DOM Elements
    // ============================================================
    const sendBtn = document.getElementById('sendBtn');
    const stopBtn = document.getElementById('stopBtn');
    const resetBtn = document.getElementById('resetBtn');
    const statusBar = document.getElementById('statusBar');
    const logs = document.getElementById('logs');
    const progressBar = document.getElementById('progressBar');
    const progressPercent = document.getElementById('progressPercent');
    const sentCount = document.getElementById('sentCount');
    const failedCount = document.getElementById('failedCount');
    const totalCount = document.getElementById('totalCount');
    
    const subject = document.getElementById('subject');
    const fromName = document.getElementById('from_name');
    const letter = document.getElementById('letter');
    const mlist = document.getElementById('mlist');
    const speedSelect = document.getElementById('speed');
    
    let isRunning = false;
    let shouldStop = false;
    let totalEmails = 0;
    let sent = 0;
    let failed = 0;
    let htmlMode = <?= $settings['html_mode'] ? 'true' : 'false' ?>;
    let isCompleted = false;
    
    // ============================================================
    //  Speed Map
    // ============================================================
    function getDelay(speed) {
        switch(speed) {
            case 'turbo': return 0;      // No delay
            case 'fast': return 300;      // 0.3 seconds
            case 'medium': return 700;    // 0.7 seconds
            case 'slow': return 1500;     // 1.5 seconds
            default: return 500;
        }
    }
    
    // ============================================================
    //  HTML Toggle
    // ============================================================
    window.toggleHTML = function() {
        const toggle = document.getElementById('htmlToggle');
        const label = document.getElementById('htmlLabel');
        htmlMode = !htmlMode;
        toggle.classList.toggle('active');
        label.textContent = htmlMode ? '🔷 HTML Mode' : '⬜ Text Mode';
        saveSettings();
    };
    
    // ============================================================
    //  Auto-save
    // ============================================================
    function saveSettings() {
        const formData = new FormData();
        formData.append('save_settings', '1');
        formData.append('subject', subject.value);
        formData.append('from_name', fromName.value);
        formData.append('letter', letter.value);
        formData.append('emails', mlist.value);
        formData.append('html_mode', htmlMode ? '1' : '0');
        formData.append('speed', speedSelect.value);
        fetch(window.location.href, { method: 'POST', body: formData }).catch(() => {});
    }
    
    [subject, fromName, letter, mlist, speedSelect].forEach(el => {
        el.addEventListener('change', saveSettings);
        el.addEventListener('input', function() {
            clearTimeout(this._timer);
            this._timer = setTimeout(saveSettings, 500);
        });
    });
    
    // ============================================================
    //  Logs & Stats
    // ============================================================
    function addLog(message, type = 'info') {
        const div = document.createElement('div');
        div.className = 'log-' + type;
        div.textContent = message;
        logs.appendChild(div);
        logs.scrollTop = logs.scrollHeight;
    }
    
    function clearLogs() {
        logs.innerHTML = '';
    }
    
    function updateStats() {
        sentCount.textContent = sent;
        failedCount.textContent = failed;
        totalCount.textContent = totalEmails;
        const progress = totalEmails > 0 ? Math.round((sent + failed) / totalEmails * 100) : 0;
        progressBar.style.width = progress + '%';
        progressBar.textContent = progress + '%';
        progressPercent.textContent = progress + '%';
    }
    
    // ============================================================
    //  Get Next Email
    // ============================================================
    async function getNextEmail() {
        const formData = new FormData();
        formData.append('get_next', '1');
        const response = await fetch(window.location.href, { method: 'POST', body: formData });
        const text = await response.text();
        try {
            return JSON.parse(text);
        } catch(e) {
            console.error('JSON error:', text.substring(0, 100));
            throw new Error('Server error');
        }
    }
    
    // ============================================================
    //  Send Email
    // ============================================================
    async function sendEmail(index, email) {
        const formData = new FormData();
        formData.append('send_one', '1');
        formData.append('index', index.toString());
        formData.append('email', email);
        const response = await fetch(window.location.href, { method: 'POST', body: formData });
        const text = await response.text();
        try {
            return JSON.parse(text);
        } catch(e) {
            console.error('JSON error:', text.substring(0, 100));
            return { sent: false, error: 'Server error' };
        }
    }
    
    // ============================================================
    //  Worker - Send one email at a time
    // ============================================================
    async function worker() {
        const delay = getDelay(speedSelect.value);
        
        // Log speed
        const speedNames = {
            'turbo': '🔥 Turbo (no delay)',
            'fast': '🚀 Fast (0.3s)',
            'medium': '⚡ Medium (0.7s)',
            'slow': '🐢 Slow (1.5s)'
        };
        addLog('⚡ Speed: ' + (speedNames[speedSelect.value] || 'Fast'), 'info');
        
        while (isRunning && !shouldStop) {
            try {
                const next = await getNextEmail();
                
                if (next.completed || next.error) {
                    isCompleted = true;
                    break;
                }
                
                const result = await sendEmail(next.index, next.email);
                
                if (result.sent) {
                    sent++;
                    if (sent % 10 === 0 || sent <= 5) {
                        addLog('✅ #' + next.index + ' ' + next.email, 'success');
                    }
                } else {
                    failed++;
                    addLog('❌ #' + next.index + ' ' + next.email + ' - ' + (result.error || 'Failed'), 'failed');
                }
                
                updateStats();
                
                // Delay based on speed setting
                if (delay > 0) {
                    await new Promise(r => setTimeout(r, delay));
                }
                
            } catch(error) {
                addLog('⚠️ Error: ' + error.message, 'failed');
                await new Promise(r => setTimeout(r, 2000));
            }
        }
    }
    
    // ============================================================
    //  START
    // ============================================================
    sendBtn.addEventListener('click', async function() {
        if (isRunning) return;
        
        const emails = mlist.value.trim();
        if (!emails) {
            alert('⚠️ Please enter emails.');
            return;
        }
        
        saveSettings();
        
        isRunning = true;
        shouldStop = false;
        isCompleted = false;
        sent = 0;
        failed = 0;
        totalEmails = emails.split('\n').filter(e => e.trim()).length;
        
        statusBar.classList.add('active');
        clearLogs();
        addLog('🚀 Starting...', 'info');
        addLog('📧 Total: ' + totalEmails + ' email(s)', 'info');
        addLog('📝 Mode: ' + (htmlMode ? 'HTML' : 'Text'), 'info');
        addLog('🔒 Each email gets ONE message', 'success');
        
        sendBtn.disabled = true;
        sendBtn.textContent = '⏳ SENDING...';
        stopBtn.style.display = 'inline-block';
        updateStats();
        
        await worker();
        
        isRunning = false;
        sendBtn.disabled = false;
        stopBtn.style.display = 'none';
        
        if (isCompleted) {
            sendBtn.textContent = '✅ DONE!';
            addLog('🎉 Complete! Sent: ' + sent + ' | Failed: ' + failed, 'info');
        } else if (shouldStop) {
            sendBtn.textContent = '⏹ STOPPED';
            addLog('⏹ Stopped at ' + (sent + failed) + ' of ' + totalEmails, 'info');
        } else {
            sendBtn.textContent = '✅ DONE!';
        }
    });
    
    // ============================================================
    //  STOP
    // ============================================================
    stopBtn.addEventListener('click', function() {
        if (isRunning) {
            shouldStop = true;
            addLog('⏹ Stopping...', 'info');
            stopBtn.disabled = true;
        }
    });
    
    // ============================================================
    //  RESET
    // ============================================================
    resetBtn.addEventListener('click', function() {
        if (confirm('Reset all progress?')) {
            const formData = new FormData();
            formData.append('reset', '1');
            fetch(window.location.href, { method: 'POST', body: formData })
                .then(() => location.reload());
        }
    });
});
</script>
</body>
</html>