<?php
// index.php - Bulk Mailer Elite • Multi-SMTP + Tracker + Spam Check
require_once __DIR__ . '/assets/PHPMailer/PHPMailer.php';
require_once __DIR__ . '/assets/PHPMailer/SMTP.php';
require_once __DIR__ . '/assets/PHPMailer/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
?>
<!DOCTYPE html>
<html lang="id" data-bs-theme="dark">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Bulk Mailer Elite • Multi-SMTP</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono&display=swap" rel="stylesheet">
  <style>
    :root {
      --primary: #6366f1;
      --gradient: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #111827 100%);
      --glass: rgba(15, 23, 42, 0.62);
      --glass-border: rgba(255,255,255,0.1);
      --text: #f8fafc;
      --terminal-bg: #0b1120;
    }
    body { background: var(--gradient); background-attachment: fixed; min-height: 100vh; color: var(--text); font-family: 'Inter', sans-serif; padding: 2.5rem 1rem; }
    .main-title { font-weight: 900; background: linear-gradient(90deg, #a5b4fc, #c084fc); -webkit-background-clip: text; -webkit-text-fill-color: transparent; text-shadow: 0 0 30px rgba(99,102,241,0.5); text-align: center; margin-bottom: 2.5rem; }
    .card { background: var(--glass); backdrop-filter: blur(24px); border: 1px solid var(--glass-border); border-radius: 24px; box-shadow: 0 30px 70px -15px rgba(0,0,0,0.6); transition: transform 0.4s ease; }
    .card:hover { transform: translateY(-10px); }
    .card-header { background: linear-gradient(90deg, rgba(99,102,241,0.45), rgba(139,92,246,0.45)); font-weight: 700; border-bottom: 1px solid var(--glass-border); }
    .form-control, .form-select { background: rgba(30,41,59,0.7); border: 1px solid rgba(165,180,252,0.35); color: white; }
    .form-control:focus { border-color: #a5b4fc; box-shadow: 0 0 0 0.3rem rgba(99,102,241,0.3); background: rgba(30,41,59,0.9); }
    #smtp-terminal, #send-terminal { background: var(--terminal-bg); border: 1px solid #1e293b; border-radius: 16px; font-family: 'JetBrains Mono', monospace; font-size: 13.5px; padding: 1.5rem; height: 440px; overflow-y: auto; box-shadow: inset 0 3px 12px rgba(0,0,0,0.7); }
    .terminal-line { margin: 4px 0; word-break: break-all; }
    .success { color: #34d399; }
    .error   { color: #f87171; }
    .info    { color: #60a5fa; }
    .warning { color: #fbbf24; }
    .btn { border: none; font-weight: 600; }
    .btn-primary  { background: linear-gradient(90deg, #6366f1, #8b5cf6); }
    .btn-warning  { background: linear-gradient(90deg, #f59e0b, #d97706); }
    .btn-stop     { background: linear-gradient(90deg, #ef4444, #b91c1c); }
    .btn-preview  { background: linear-gradient(90deg, #8b5cf6, #d946ef); }
    .progress-container { background: rgba(30,41,59,0.7); border-radius: 999px; overflow: hidden; box-shadow: 0 10px 30px rgba(0,0,0,0.5); }
    .progress-bar { font-weight: 800; font-size: 1.35rem; display: flex; align-items: center; justify-content: center; transition: width 1.8s ease-out; }
    .smtp-item { background: rgba(30,41,59,0.75); padding: 0.8rem 1.2rem; border-radius: 12px; margin: 0.5rem 0; display: flex; justify-content: space-between; align-items: center; }
    #previewIframe { width: 100%; height: 65vh; border: none; border-radius: 12px; background: white; }
  </style>
</head>
<body>

<div class="container">

  <h1 class="main-title display-4"><i class="fas fa-rocket-launch me-3"></i>Bulk Mailer Elite</h1>

  <!-- 1. SMTP Configuration -->
  <div class="card mb-5">
    <div class="card-header text-white">
      <i class="fas fa-server me-2"></i> 1. Konfigurasi SMTP
    </div>
    <div class="card-body p-5">
      <form id="smtpForm">
        <div class="row g-4">
          <div class="col-md-6"><input type="text" name="host" class="form-control" placeholder="smtp.gmail.com" required></div>
          <div class="col-md-3"><input type="number" name="port" class="form-control" value="587" required></div>
          <div class="col-md-3">
            <select name="secure" class="form-select">
              <option value="tls">STARTTLS (587)</option>
              <option value="ssl">SSL/TLS (465)</option>
              <option value="">None</option>
            </select>
          </div>
          <div class="col-md-6"><input type="text" name="username" class="form-control" placeholder="email@gmail.com" required></div>
          <div class="col-md-6"><input type="password" name="password" class="form-control" required></div>
          <div class="col-md-6"><input type="email" name="from_email" class="form-control" required></div>
          <div class="col-md-6"><input type="text" name="from_name" class="form-control" value="My Team"></div>
        </div>

        <div class="d-flex gap-3 mt-4">
          <button type="submit" class="btn btn-warning btn-lg flex-grow-1" id="testBtn">
            <i class="fas fa-bolt me-2"></i> TEST & TAMBAH SMTP
          </button>
          <button type="button" class="btn btn-danger btn-lg" id="clearSmtps">
            <i class="fas fa-trash me-2"></i> HAPUS SEMUA
          </button>
        </div>
      </form>

      <div id="smtp-list" class="mt-4"></div>
      <div id="smtp-terminal" style="display:none;" class="mt-4"></div>
      <div id="smtp-summary" class="mt-4"></div>
    </div>
  </div>

  <!-- 2. Bulk Send -->
  <div class="card">
    <div class="card-header text-white">
      <i class="fas fa-paper-plane me-2"></i> 2. Kirim Bulk Email
    </div>
    <div class="card-body p-5">
      <form id="bulkForm">

        <div class="mb-4">
          <div class="form-check form-switch">
            <input class="form-check-input" type="checkbox" id="rotationToggle" checked>
            <label class="form-check-label fw-bold" for="rotationToggle">Gunakan rotasi semua SMTP</label>
          </div>
          <small class="form-text text-muted">Matikan toggle jika ingin memilih satu SMTP saja.</small>
        </div>

        <div class="mb-4" id="singleSmtpGroup" style="display:none;">
          <label class="form-label fw-bold">Pilih SMTP yang digunakan</label>
          <select name="selected_smtp_index" id="smtpSelector" class="form-select" required>
            <option value="">-- Pilih SMTP --</option>
          </select>
        </div>

        <ul class="nav nav-tabs mb-4">
          <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#csv">Upload CSV</button></li>
          <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#manual">Daftar Manual</button></li>
        </ul>

        <div class="tab-content mb-4">
          <div class="tab-pane fade show active" id="csv">
            <input type="file" name="csv_file" class="form-control" accept=".csv">
          </div>
          <div class="tab-pane fade" id="manual">
            <textarea name="manual_recipients" class="form-control" rows="7" placeholder="email | nama\nsatu baris satu penerima"></textarea>
          </div>
        </div>

        <div class="mb-4">
          <label class="form-label fw-bold">Subjek</label>
          <input type="text" name="subject" class="form-control" required value="Update Khusus">
        </div>

        <div class="mb-4">
          <label class="form-label fw-bold">Delay antar email</label>
          <div class="input-group">
            <input type="number" name="delay_seconds" class="form-control" min="0" max="30" step="0.1" value="0.5" required>
            <span class="input-group-text">detik</span>
          </div>
        </div>

        <div class="mb-4">
          <div class="d-flex justify-content-between align-items-center mb-2">
            <label class="form-label fw-bold">Isi Email (support {nama} & {email})</label>
            <div>
              <button type="button" class="btn btn-preview btn-sm me-2" id="btnPreview">
                <i class="fas fa-eye me-1"></i> Preview
              </button>
              <button type="button" class="btn btn-warning btn-sm" id="btnSpamCheck">
                <i class="fas fa-shield-virus me-1"></i> Cek Spam
              </button>
            </div>
          </div>
          <textarea name="body" id="emailBody" class="form-control" rows="12" required>
Hai {nama},

Ini pesan khusus untuk akun {email}.
Klik tombol di bawah:

<a href="https://example.com/offer?email={email}" style="display:inline-block;background:#6366f1;color:white;padding:12px 24px;border-radius:8px;text-decoration:none;">Lihat Penawaran</a>

Salam,
Tim Kami
          </textarea>
        </div>

        <input type="hidden" name="smtps_json" id="h_smtps_json">
        <input type="hidden" name="use_rotation" id="h_use_rotation" value="true">

        <div class="d-flex gap-3 mt-5">
          <button type="submit" class="btn btn-primary btn-lg flex-grow-1" id="sendBtn" disabled>MULAI KIRIM</button>
          <button type="button" class="btn btn-stop btn-lg" id="stopBtn" style="display:none;">STOP</button>
        </div>

        <div class="progress-container mt-4" id="progressContainer" style="display:none; height:60px;">
          <div class="progress-bar" id="progressBar" style="width:0%;">0%</div>
        </div>
        <div class="text-center mt-3 fw-bold fs-5" id="progressInfo">Siap</div>

        <div id="send-terminal" style="display:none;" class="mt-4"></div>
      </form>
    </div>
  </div>

  <!-- Tracker Dashboard -->
  <div class="card mt-5">
    <div class="card-header text-white">
      <i class="fas fa-chart-line me-2"></i> Tracker Pengiriman
    </div>
    <div class="card-body">
      <select id="campaignSelector" class="form-select mb-4">
        <option value="">-- Pilih Campaign --</option>
      </select>
      <div id="statsDashboard" class="row g-4"></div>
    </div>
  </div>

</div>

<!-- Preview Modal -->
<div class="modal fade" id="previewModal" tabindex="-1">
  <div class="modal-dialog modal-xl modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Preview Email</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-4">
        <iframe id="previewIframe" sandbox="allow-same-origin"></iframe>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
      </div>
    </div>
  </div>
</div>

<!-- Spam Check Modal -->
<div class="modal fade" id="spamCheckModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content bg-dark text-white">
      <div class="modal-header border-0">
        <h5 class="modal-title">Analisis Risiko Spam</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body text-center">
        <div class="progress-container mx-auto mb-4" style="width:85%; height:70px;">
          <div class="progress-bar" id="spamProgressBar" style="width:0%;">0%</div>
        </div>
        <div class="fw-bold fs-1 mb-3" id="spamPercentage">0%</div>
        <div id="spamMessage" style="min-height:80px;">Tekan Analyze untuk memulai.</div>
        <small class="text-muted mt-3 d-block">Estimasi heuristic sederhana — bukan pengganti Mail-Tester atau layanan profesional.</small>
      </div>
      <div class="modal-footer border-0">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
        <button type="button" class="btn btn-primary" id="analyzeSpamBtn">Analyze Sekarang</button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// SMTP Management
let smtps = JSON.parse(localStorage.getItem('bulkMailerSmtps') || '[]');

const smtpListEl       = document.getElementById('smtp-list');
const hSmtpsJson       = document.getElementById('h_smtps_json');
const hUseRotation     = document.getElementById('h_use_rotation');
const sendBtn          = document.getElementById('sendBtn');
const smtpSelector     = document.getElementById('smtpSelector');
const rotationToggle   = document.getElementById('rotationToggle');
const singleSmtpGroup  = document.getElementById('singleSmtpGroup');

function renderSmtpList() {
    smtpListEl.innerHTML = smtps.map((s, i) => `
        <div class="smtp-item">
            <div><strong>${s.username}</strong> @ ${s.host}:${s.port}</div>
            <button class="btn btn-sm btn-danger" onclick="removeSmtp(${i})">
                <i class="fas fa-trash"></i>
            </button>
        </div>
    `).join('');

    smtpSelector.innerHTML = '<option value="">-- Pilih SMTP --</option>';
    smtps.forEach((s, i) => {
        const opt = document.createElement('option');
        opt.value = i;
        opt.textContent = `${s.username} @ ${s.host}:${s.port}`;
        smtpSelector.appendChild(opt);
    });

    const saved = localStorage.getItem('selectedSmtpIndex');
    if (saved !== null && Number(saved) < smtps.length) {
        smtpSelector.value = saved;
    } else if (smtps.length > 0) {
        smtpSelector.value = '0';
    } else {
        smtpSelector.value = '';
    }

    hSmtpsJson.value = JSON.stringify(smtps);
    updateSendButton();
}

function updateSendButton() {
    const rot = rotationToggle.checked;
    sendBtn.disabled = rot ? (smtps.length === 0) : (smtps.length === 0 || smtpSelector.value === '');
}

function addSmtp(data) {
    smtps.push(data);
    localStorage.setItem('bulkMailerSmtps', JSON.stringify(smtps));
    renderSmtpList();
}

function removeSmtp(idx) {
    smtps.splice(idx, 1);
    localStorage.setItem('bulkMailerSmtps', JSON.stringify(smtps));
    if (Number(smtpSelector.value) === idx) {
        localStorage.removeItem('selectedSmtpIndex');
        smtpSelector.value = '';
    } else if (Number(smtpSelector.value) > idx) {
        smtpSelector.value = Number(smtpSelector.value) - 1;
        localStorage.setItem('selectedSmtpIndex', smtpSelector.value);
    }
    renderSmtpList();
}

document.getElementById('clearSmtps').onclick = () => {
    if (confirm('Hapus semua SMTP tersimpan?')) {
        smtps = [];
        localStorage.removeItem('bulkMailerSmtps');
        localStorage.removeItem('selectedSmtpIndex');
        renderSmtpList();
    }
};

rotationToggle.addEventListener('change', () => {
    const isRot = rotationToggle.checked;
    hUseRotation.value = isRot ? 'true' : 'false';
    singleSmtpGroup.style.display = isRot ? 'none' : 'block';
    updateSendButton();
});

smtpSelector.addEventListener('change', () => {
    localStorage.setItem('selectedSmtpIndex', smtpSelector.value);
    updateSendButton();
});

renderSmtpList();

// Test SMTP
document.getElementById('smtpForm').addEventListener('submit', async e => {
    e.preventDefault();
    const term = document.getElementById('smtp-terminal');
    const sum = document.getElementById('smtp-summary');
    const btn = document.getElementById('testBtn');

    term.style.display = 'block';
    term.innerHTML = '<div class="terminal-line info">[TEST] Memulai...</div>';
    sum.innerHTML = '<div class="alert alert-info">Menguji koneksi...</div>';
    btn.disabled = true;

    const fd = new FormData(e.target);
    fd.append('action', 'test_smtp');

    try {
        const res = await fetch('', {method:'POST', body: fd});
        const html = await res.text();
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');

        term.innerHTML += doc.getElementById('term-content')?.innerHTML || '';
        sum.innerHTML = doc.getElementById('sum-content')?.innerHTML || '';

        if (sum.innerHTML.includes('alert-success')) {
            addSmtp({
                host: fd.get('host'),
                port: fd.get('port'),
                secure: fd.get('secure'),
                username: fd.get('username'),
                password: fd.get('password'),
                from_email: fd.get('from_email'),
                from_name: fd.get('from_name')
            });
        }
    } catch(err) {
        term.innerHTML += `<div class="terminal-line error">[ERROR] ${err.message}</div>`;
    } finally {
        btn.disabled = false;
        term.scrollTop = term.scrollHeight;
    }
});

// Preview
document.getElementById('btnPreview')?.addEventListener('click', () => {
    const body = document.getElementById('emailBody').value;
    const subj = document.querySelector('[name="subject"]').value || '(No Subject)';

    const preview = body.replace(/{nama}/gi, 'Budi').replace(/{email}/gi, 'budi@example.com');

    document.getElementById('previewIframe').srcdoc = `
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>${subj}</title></head>
<body style="font-family:Arial;max-width:600px;margin:30px auto;padding:20px;background:#f9fafb;border-radius:12px;">
<h2>Halo Budi,</h2>${preview}<p>Salam,<br>Tim</p></body></html>`;
    new bootstrap.Modal(document.getElementById('previewModal')).show();
});

// Spam Check (sederhana)
document.getElementById('btnSpamCheck')?.addEventListener('click', () => {
    const subj = document.querySelector('[name="subject"]').value.trim();
    const body = document.getElementById('emailBody').value.trim();
    if (!subj || !body) return alert('Isi subjek dan isi email terlebih dahulu');

    const modal = new bootstrap.Modal(document.getElementById('spamCheckModal'));
    modal.show();

    const bar = document.getElementById('spamProgressBar');
    const pct = document.getElementById('spamPercentage');
    const msg = document.getElementById('spamMessage');

    bar.style.width = '0%';
    pct.textContent = '0%';
    msg.textContent = 'Menganalisis...';

    setTimeout(() => {
        let score = 0;
        if ((body.match(/https?:\/\//gi) || []).length > 3) score += 25;
        if (/free|gratis|menang|hadiah|urgent|klik|prize/gi.test(body + subj)) score += 20;
        if ((body.match(/[A-Z]/g) || []).length / body.length > 0.4) score += 15;
        score = Math.min(100, score);

        let cur = 0;
        const intv = setInterval(() => {
            cur += Math.ceil(score / 30);
            if (cur >= score) { cur = score; clearInterval(intv); }
            pct.textContent = cur + '%';
            bar.style.width = cur + '%';
        }, 80);

        setTimeout(() => {
            if (score <= 25) msg.innerHTML = '<span class="text-success">Risiko spam rendah – sepertinya aman</span>';
            else if (score <= 55) msg.innerHTML = '<span class="text-warning">Risiko sedang – perbaiki beberapa bagian</span>';
            else msg.innerHTML = '<span class="text-danger">Risiko tinggi – sangat disarankan revisi</span>';
        }, 2800);
    }, 400);
});

// Sending logic (sederhana - tanpa tracking lengkap di sini)
let abortCtrl = null;
let sending = false;

document.getElementById('bulkForm').addEventListener('submit', async e => {
    e.preventDefault();
    if (sending) return;

    sending = true;
    abortCtrl = new AbortController();

    sendBtn.disabled = true;
    document.getElementById('stopBtn').style.display = 'inline-block';
    sendBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> Mengirim...';

    const term = document.getElementById('send-terminal');
    const progC = document.getElementById('progressContainer');
    const progB = document.getElementById('progressBar');
    const info  = document.getElementById('progressInfo');

    term.style.display = 'block';
    term.innerHTML = '<div class="terminal-line info">[START] Inisialisasi...</div>';
    progC.style.display = 'block';
    progB.style.width = '0%';
    progB.textContent = '0%';
    info.textContent = 'Menyiapkan...';

    const fd = new FormData(e.target);

    try {
        const res = await fetch('process.php', {
            method: 'POST',
            body: fd,
            signal: abortCtrl.signal
        });

        const reader = res.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        let total = 0, doneCount = 0;

        while (true) {
            const {done, value} = await reader.read();
            if (done) break;

            buffer += decoder.decode(value, {stream:true});
            let lines = buffer.split('\n');
            buffer = lines.pop() || '';

            for (let line of lines) {
                if (!line.trim()) continue;
                term.innerHTML += line + '\n';
                term.scrollTop = term.scrollHeight;

                if (line.includes('Ditemukan <b>')) {
                    const m = line.match(/<b>(\d+)<\/b>/);
                    if (m) total = parseInt(m[1]);
                }
                if (line.includes('BERHASIL') || line.includes('GAGAL')) {
                    doneCount++;
                    if (total > 0) {
                        const pct = Math.round((doneCount / total) * 100);
                        progB.style.width = pct + '%';
                        progB.textContent = pct + '%';
                        info.textContent = `Diproses: ${doneCount}/${total}`;
                    }
                }
            }
        }
    } catch (err) {
        if (err.name === 'AbortError') {
            term.innerHTML += '<div class="terminal-line warning">[DIBATALKAN]</div>';
        } else {
            term.innerHTML += `<div class="terminal-line error">[ERROR] ${err.message}</div>`;
        }
    } finally {
        sending = false;
        sendBtn.disabled = false;
        document.getElementById('stopBtn').style.display = 'none';
        sendBtn.innerHTML = 'MULAI KIRIM';
        term.innerHTML += '<div class="terminal-line success">[SELESAI]</div>';
    }
});

document.getElementById('stopBtn').onclick = () => {
    if (!sending) return;
    fetch('stop.php', {method: 'POST'});
    abortCtrl?.abort();
};

// Tracker sederhana
function loadCampaigns() {
    fetch('list_campaigns.php')
        .then(r => r.json())
        .then(c => {
            const sel = document.getElementById('campaignSelector');
            sel.innerHTML = '<option value="">-- Pilih Campaign --</option>';
            c.forEach(x => {
                const o = document.createElement('option');
                o.value = x.id;
                o.textContent = `${x.id} • ${new Date(x.time*1000).toLocaleString('id-ID')}`;
                sel.appendChild(o);
            });
        });
}

document.getElementById('campaignSelector')?.addEventListener('change', e => {
    const cid = e.target.value;
    if (!cid) return;
    fetch(`tracking/${cid}.json`)
        .then(r => r.json())
        .then(d => {
            const s = d.sent || 0, del = d.delivered || 0, b = d.bounced || 0, o = d.opened || 0, cl = d.clicked || 0;
            document.getElementById('statsDashboard').innerHTML = `
<div class="col-md-3"><div class="card bg-success text-white"><div class="card-body"><h5>Delivery</h5><h3>${s ? ((del/s)*100).toFixed(1) : 0}%</h3></div></div></div>
<div class="col-md-3"><div class="card bg-info text-white"><div class="card-body"><h5>Open</h5><h3>${del ? ((o/del)*100).toFixed(1) : 0}%</h3></div></div></div>
<div class="col-md-3"><div class="card bg-primary text-white"><div class="card-body"><h5>Click</h5><h3>${del ? ((cl/del)*100).toFixed(1) : 0}%</h3></div></div></div>
<div class="col-md-3"><div class="card bg-danger text-white"><div class="card-body"><h5>Bounce</h5><h3>${s ? ((b/s)*100).toFixed(1) : 0}%</h3></div></div></div>`;
        });
});

loadCampaigns();
</script>
</body>
</html>

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'test_smtp') {
    $mail = new PHPMailer(true);
    $mail->SMTPDebug = 3;
    $mail->Timeout = 60;
    $debug = [];

    $mail->Debugoutput = function($str, $level) use (&$debug) {
        $prefix = ['[ERROR]','[CLIENT]','[SERVER]','[DETAIL]','[INFO]'][$level] ?? '[INFO]';
        $class = in_array($level, [0]) ? 'error' : (in_array($level, [1,3]) ? 'info' : 'success');
        $debug[] = "<div class=\"terminal-line $class\">$prefix " . htmlspecialchars($str) . "</div>";
    };

    $mail->isSMTP();
    $mail->Host = trim($_POST['host'] ?? '');
    $mail->Port = (int)($_POST['port'] ?? 587);
    $mail->SMTPAuth = true;
    $mail->Username = trim($_POST['username'] ?? '');
    $mail->Password = $_POST['password'] ?? '';
    $mail->SMTPSecure = $_POST['secure'] ?? 'tls';
    $mail->SMTPOptions = ['ssl' => ['verify_peer'=>false, 'verify_peer_name'=>false, 'allow_self_signed'=>true]];

    $ok = false; $err = '';
    try {
        $ok = $mail->smtpConnect();
        $debug[] = '<div class="terminal-line success">[SUCCESS] Koneksi berhasil!</div>';
    } catch (Exception $e) {
        $err = $e->getMessage();
        $debug[] = '<div class="terminal-line error">[GAGAL] ' . htmlspecialchars($err) . '</div>';
    }
    $mail->smtpClose();

    echo '<div id="term-content">' . implode('', $debug) . '</div>';
    if ($ok) {
        echo '<div id="sum-content"><div class="alert alert-success"><strong>BERHASIL!</strong> SMTP siap digunakan.</div></div>';
    } else {
        echo '<div id="sum-content"><div class="alert alert-danger"><strong>GAGAL:</strong> ' . htmlspecialchars($err) . '</div></div>';
    }
    exit;
}
?>