<?php
// setup.php — FormBuilder setup wizard. DELETE after setup is complete.
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'];

    if ($action === 'self_delete') { @unlink(__FILE__); echo json_encode(['ok'=>true]); exit; }

    if ($action === 'env_check') {
        $checks = [
            ['label'=>'PHP Version','value'=>PHP_VERSION,'ok'=>version_compare(PHP_VERSION,'7.4','>='),'need'=>'>=7.4'],
            ['label'=>'PDO MySQL','value'=>extension_loaded('pdo_mysql')?'Enabled':'Missing','ok'=>extension_loaded('pdo_mysql')],
            ['label'=>'OpenSSL','value'=>extension_loaded('openssl')?'Enabled':'Missing','ok'=>extension_loaded('openssl')],
            ['label'=>'JSON','value'=>extension_loaded('json')?'Enabled':'Missing','ok'=>extension_loaded('json')],
            ['label'=>'FileInfo','value'=>extension_loaded('fileinfo')?'Enabled':'Missing (needed for uploads)','ok'=>extension_loaded('fileinfo'),'warn'=>true],
            ['label'=>'allow_url_fopen','value'=>ini_get('allow_url_fopen')?'On':'Off','ok'=>(bool)ini_get('allow_url_fopen'),'warn'=>true],
            ['label'=>'config.php writable','value'=>(is_writable(__DIR__.'/config.php')||!file_exists(__DIR__.'/config.php'))?'Yes':'No','ok'=>(is_writable(__DIR__.'/config.php')||!file_exists(__DIR__.'/config.php'))],
            ['label'=>'data/ writable','value'=>is_writable(__DIR__.'/data')||(is_dir(__DIR__.'/data')&&is_writable(__DIR__.'/data'))||@mkdir(__DIR__.'/data',0755,true)?'Yes':'No','ok'=>is_writable(__DIR__.'/data')],
            ['label'=>'PHPMailer','value'=>file_exists(__DIR__.'/vendor/autoload.php')?'Installed':'Not installed (raw SMTP fallback)','ok'=>file_exists(__DIR__.'/vendor/autoload.php'),'warn'=>true],
        ];
        echo json_encode(['ok'=>true,'checks'=>$checks]); exit;
    }

    if ($action === 'save_config') {
        $f = ['DB_HOST','DB_PORT','DB_NAME','DB_USER','DB_PASS','ADMIN_PASSWORD','APP_NAME','APP_URL','APP_TIMEZONE','FROM_EMAIL','FROM_NAME','ADMIN_EMAIL','SMTP_HOST','SMTP_PORT','SMTP_SECURE','SMTP_USER','SMTP_PASS','ALLOWED_ORIGIN'];
        $v = []; foreach($f as $k) $v[$k]=trim($_POST[$k]??'');
        $php="<?php\n// FormBuilder config — generated by setup wizard ".date('Y-m-d H:i:s')."\n\n";
        $php.="define('DB_HOST',    ".var_export($v['DB_HOST'],true).");\n";
        $php.="define('DB_PORT',    ".(int)($v['DB_PORT']?:3306).");\n";
        $php.="define('DB_NAME',    ".var_export($v['DB_NAME'],true).");\n";
        $php.="define('DB_USER',    ".var_export($v['DB_USER'],true).");\n";
        $php.="define('DB_PASS',    ".var_export($v['DB_PASS'],true).");\n\n";
        $php.="define('ADMIN_PASSWORD',  ".var_export($v['ADMIN_PASSWORD'],true).");\n";
        $php.="define('ADMIN_SESSION_TTL', 28800);\n\n";
        $php.="define('APP_NAME',    ".var_export($v['APP_NAME']?:'FormBuilder',true).");\n";
        $php.="define('APP_URL',     ".var_export(rtrim($v['APP_URL'],'/'),true).");\n";
        $php.="define('APP_TIMEZONE',".var_export($v['APP_TIMEZONE']?:'UTC',true).");\n\n";
        $php.="define('FROM_EMAIL',  ".var_export($v['FROM_EMAIL'],true).");\n";
        $php.="define('FROM_NAME',   ".var_export($v['FROM_NAME']?:'FormBuilder',true).");\n";
        $php.="define('ADMIN_EMAIL', ".var_export($v['ADMIN_EMAIL'],true).");\n\n";
        $php.="define('SMTP_HOST',   ".var_export($v['SMTP_HOST'],true).");\n";
        $php.="define('SMTP_PORT',   ".(int)($v['SMTP_PORT']?:587).");\n";
        $php.="define('SMTP_SECURE', ".var_export($v['SMTP_SECURE'],true).");\n";
        $php.="define('SMTP_USER',   ".var_export($v['SMTP_USER'],true).");\n";
        $php.="define('SMTP_PASS',   ".var_export($v['SMTP_PASS'],true).");\n\n";
        $php.="define('UPLOAD_MAX_MB',       10);\n";
        $php.="define('EMAIL_ATTACH_MAX_MB',  8);\n";
        $php.="define('ALLOWED_EXTENSIONS', 'jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx,txt,zip');\n";
        $php.="define('RATE_LIMIT_MAX',    10);\n";
        $php.="define('RATE_LIMIT_WINDOW', 3600);\n";
        $php.="define('ALLOWED_ORIGIN', ".var_export($v['ALLOWED_ORIGIN']?:'*',true).");\n";
        if(file_put_contents(__DIR__.'/config.php',$php)===false){echo json_encode(['ok'=>false,'error'=>'Cannot write config.php']);exit;}
        echo json_encode(['ok'=>true]); exit;
    }

    if ($action === 'test_db') {
        if(!file_exists(__DIR__.'/config.php')){echo json_encode(['ok'=>false,'error'=>'Save config first']);exit;}
        require_once __DIR__.'/config.php';
        try{
            $pdo=new PDO('mysql:host='.DB_HOST.';port='.DB_PORT.';dbname='.DB_NAME.';charset=utf8mb4',DB_USER,DB_PASS,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
            require_once __DIR__.'/lib.php'; init_db();
            echo json_encode(['ok'=>true,'message'=>'Connected & tables created successfully.']); exit;
        }catch(\Throwable $e){echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);exit;}
    }

    if ($action === 'install_phpmailer') {
        $log=[];
        if(file_exists(__DIR__.'/vendor/autoload.php')){echo json_encode(['ok'=>true,'log'=>['PHPMailer already installed.'],'skipped'=>true]);exit;}
        $phar=__DIR__.'/composer.phar';
        if(!file_exists($phar)){
            $log[]='Downloading composer.phar…';
            if(!ini_get('allow_url_fopen')){echo json_encode(['ok'=>false,'log'=>$log,'error'=>'allow_url_fopen disabled.']);exit;}
            $inst=@file_get_contents('https://getcomposer.org/installer');
            if(!$inst){echo json_encode(['ok'=>false,'log'=>$log,'error'=>'Could not download Composer.']);exit;}
            file_put_contents(__DIR__.'/composer-setup.php',$inst);
            ob_start();passthru('php '.escapeshellarg(__DIR__.'/composer-setup.php').' --install-dir='.escapeshellarg(__DIR__).' --filename=composer.phar 2>&1',$ret);$out=ob_get_clean();
            @unlink(__DIR__.'/composer-setup.php');$log[]=trim($out);
            if($ret!==0||!file_exists($phar)){echo json_encode(['ok'=>false,'log'=>$log,'error'=>'Composer install failed.']);exit;}
        }else{$log[]='composer.phar already present.';}
        $log[]='Running composer install…';
        ob_start();passthru('cd '.escapeshellarg(__DIR__).' && php composer.phar install --no-dev --no-interaction 2>&1',$ret);$out=ob_get_clean();$log[]=trim($out);
        if($ret!==0||!file_exists(__DIR__.'/vendor/autoload.php')){echo json_encode(['ok'=>false,'log'=>$log,'error'=>'composer install failed. Raw SMTP fallback will be used.']);exit;}
        $log[]='PHPMailer installed.';
        echo json_encode(['ok'=>true,'log'=>$log]); exit;
    }

    if ($action === 'test_smtp') {
        if(!file_exists(__DIR__.'/config.php')){echo json_encode(['ok'=>false,'error'=>'Save config first']);exit;}
        require_once __DIR__.'/config.php';
        if(file_exists(__DIR__.'/vendor/autoload.php'))require_once __DIR__.'/vendor/autoload.php';
        require_once __DIR__.'/lib.php';
        $to=trim($_POST['test_email']??ADMIN_EMAIL);
        $sent=send_mail($to,'Test','FormBuilder SMTP Test','<p>✅ SMTP is working correctly.</p>','SMTP is working correctly.');
        echo json_encode(['ok'=>$sent,'error'=>$sent?null:'Email failed — check SMTP settings.']); exit;
    }

    echo json_encode(['ok'=>false,'error'=>'Unknown action']); exit;
}
?><!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"/>
<title>FormBuilder Setup</title>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Syne:wght@700;800&family=DM+Sans:opsz,wght@9..40,400;9..40,500;9..40,600&display=swap" rel="stylesheet"/>
<style>
*{box-sizing:border-box;margin:0;padding:0}body{font-family:'DM Sans',sans-serif;-webkit-font-smoothing:antialiased;background:#f1f5f9;min-height:100vh;padding:32px 16px}
.wrap{max-width:760px;margin:0 auto}.hdr{background:linear-gradient(135deg,#f0a500,#c47f00);border-radius:16px;padding:32px;color:#000;margin-bottom:24px;box-shadow:0 4px 20px rgba(240,165,0,0.25)}.hdr h1{font-family:'Syne',sans-serif;font-size:24px;font-weight:800;margin-bottom:4px}.hdr p{color:rgba(0,0,0,.6);font-size:14px}
.warn{background:#fef3c7;border:1px solid #f59e0b;border-radius:10px;padding:14px 18px;font-size:13px;color:#92400e;margin-bottom:20px}
.card{background:#fff;border-radius:14px;box-shadow:0 2px 12px rgba(0,0,0,.07);margin-bottom:18px;overflow:hidden}
.ch{padding:18px 24px;display:flex;align-items:center;gap:14px;cursor:pointer;user-select:none;border-bottom:1px solid #f1f5f9}.ch:hover{background:#f8fafc}
.sn{width:34px;height:34px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:14px;flex-shrink:0}
.sn.p{background:#e2e8f0;color:#64748b}.sn.a{background:#f0a500;color:#000}.sn.d{background:#10b981;color:#fff}.sn.e{background:#ef4444;color:#fff}
.ch h2{font-size:15px;font-weight:700;flex:1}.ch .st{font-size:12px;color:#94a3b8}
.cb{padding:24px;display:none}.cb.open{display:block}
.fg{margin-bottom:14px}.fg label{display:block;font-size:12px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.06em;margin-bottom:5px}
.fg input,.fg select{width:100%;border:1.5px solid #e2e8f0;border-radius:8px;padding:9px 12px;font-size:14px;outline:none;transition:border .15s}.fg input:focus,.fg select:focus{border-color:#f0a500}
.row2{display:grid;grid-template-columns:1fr 1fr;gap:12px}.row3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px}
.btn{display:inline-flex;align-items:center;gap:8px;padding:10px 20px;border-radius:999px;font-size:13px;font-weight:700;border:none;cursor:pointer;transition:opacity .15s}
.btn:disabled{opacity:.5;cursor:not-allowed}.bp{background:#f0a500;color:#000;font-weight:700}.bp:hover:not(:disabled){background:#d4920a;color:#000}
.skip{font-size:12px;color:#94a3b8;text-decoration:underline;cursor:pointer;background:none;border:none;display:block;margin-top:8px}
.res{margin-top:14px;border-radius:10px;padding:12px 16px;font-size:13px;display:none}.res.show{display:block}.res.ok{background:#ecfdf5;border:1px solid #a7f3d0;color:#065f46}.res.err{background:#fef2f2;border:1px solid #fca5a5;color:#991b1b}.res.warn{background:#fef9c3;border:1px solid #fde68a;color:#92400e}
.log{background:#1e293b;color:#94a3b8;border-radius:8px;padding:12px;font-size:12px;font-family:monospace;white-space:pre-wrap;margin-top:8px;max-height:150px;overflow-y:auto}
.chklist{display:flex;flex-direction:column;gap:8px}.chkrow{display:flex;align-items:center;gap:10px;font-size:13px}.chkrow .ic{width:20px;text-align:center;flex-shrink:0}.chkrow .lb{color:#64748b;width:200px;flex-shrink:0}.chkrow .vl{color:#0a1628;font-weight:600}
.done-box{background:linear-gradient(135deg,#ecfdf5,#d1fae5);border:2px solid #10b981;border-radius:14px;padding:28px;text-align:center;margin-top:8px;display:none}.done-box h2{color:#065f46;font-size:20px;margin-bottom:8px}.done-box p{color:#047857;font-size:14px;margin-bottom:16px}
.sp{display:inline-block;width:14px;height:14px;border:2px solid rgba(255,255,255,.4);border-top-color:#fff;border-radius:50%;animation:spin .7s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}

/* ── Responsive ─────────────────────────────────────────────── */
@media(max-width:600px){
  body{padding:16px 10px}
  .hdr{padding:22px 20px;border-radius:12px}
  .hdr h1{font-size:20px}
  .card{margin-bottom:12px}
  .ch{padding:14px 16px}
  .cb{padding:16px}
  .row2,.row3{grid-template-columns:1fr}
  .fg input,.fg select{font-size:16px} /* prevent iOS zoom */
  .btn{padding:10px 18px}
  .chkrow .lb{width:140px}
}
</style></head><body><div class="wrap">
<div class="hdr"><h1>⚙️ FormBuilder — Setup Wizard</h1><p>Complete each step to configure your installation.</p></div>
<div class="warn"><strong>🔒 Delete this file</strong> after setup is complete. The final step does it automatically.</div>

<div class="card" id="c0"><div class="ch" onclick="tog(0)"><div class="sn a" id="n0">0</div><h2>Environment Check</h2><span class="st" id="s0">Auto-running…</span></div>
<div class="cb open" id="b0"><button class="btn bp" onclick="envCheck()" id="btn0">Run Check</button><div class="res" id="r0"></div></div></div>

<div class="card" id="c1"><div class="ch" onclick="tog(1)"><div class="sn p" id="n1">1</div><h2>Configuration</h2><span class="st" id="s1">Pending</span></div>
<div class="cb" id="b1">
  <div class="fg"><label>App Name</label><input id="APP_NAME" value="FormBuilder"/></div>
  <div class="fg"><label>App URL (no trailing slash)</label><input id="APP_URL" placeholder="https://yourdomain.com/formbuilder"/></div>
  <div class="row2">
    <div class="fg"><label>Timezone</label><select id="APP_TIMEZONE"><option>UTC</option><option>America/New_York</option><option>America/Chicago</option><option>America/Denver</option><option>America/Los_Angeles</option><option>Europe/London</option><option>Europe/Paris</option><option>Asia/Tokyo</option><option>Asia/Dubai</option><option>Australia/Sydney</option></select></div>
    <div class="fg"><label>Admin Password *</label><div style="display:flex;gap:8px"><input id="ADMIN_PASSWORD" type="password" placeholder="Strong password" style="flex:1"/><button class="btn bp" onclick="genPW()" style="border-radius:8px;padding:9px 12px;white-space:nowrap">Gen</button></div></div>
  </div>
  <hr style="margin:16px 0;border:none;border-top:1px solid #f1f5f9"/>
  <div class="row2"><div class="fg"><label>DB Host</label><input id="DB_HOST" value="localhost"/></div><div class="fg"><label>DB Port</label><input id="DB_PORT" value="3306"/></div></div>
  <div class="fg"><label>Database Name *</label><input id="DB_NAME" placeholder="user123_formbuilder"/></div>
  <div class="row2"><div class="fg"><label>DB User *</label><input id="DB_USER" placeholder="user123_fbuser"/></div><div class="fg"><label>DB Password *</label><input id="DB_PASS" type="password"/></div></div>
  <hr style="margin:16px 0;border:none;border-top:1px solid #f1f5f9"/>
  <div class="row2"><div class="fg"><label>From Email</label><input id="FROM_EMAIL" type="email" placeholder="noreply@yourdomain.com"/></div><div class="fg"><label>From Name</label><input id="FROM_NAME" placeholder="FormBuilder"/></div></div>
  <div class="fg"><label>Admin Notification Email</label><input id="ADMIN_EMAIL" type="email" placeholder="admin@yourdomain.com"/></div>
  <div class="fg"><label>SMTP Host</label><input id="SMTP_HOST" placeholder="mail.yourdomain.com"/></div>
  <div class="row3">
    <div class="fg"><label>Port</label><select id="SMTP_PORT" onchange="syncSec()"><option value="587">587 STARTTLS</option><option value="465">465 SSL</option><option value="25">25 Plain</option></select></div>
    <div class="fg"><label>Encryption</label><select id="SMTP_SECURE"><option value="tls">TLS</option><option value="ssl">SSL</option><option value="">None</option></select></div>
    <div class="fg"><label>SMTP User</label><input id="SMTP_USER" placeholder="noreply@yourdomain.com"/></div>
  </div>
  <div class="fg"><label>SMTP Password</label><input id="SMTP_PASS" type="password"/></div>
  <div class="fg"><label>Allowed Origin (CORS)</label><input id="ALLOWED_ORIGIN" placeholder="https://yourdomain.com"/></div>
  <button class="btn bp" onclick="saveCfg()" id="btn1">Save config.php</button>
  <div class="res" id="r1"></div>
</div></div>

<div class="card"><div class="ch" onclick="tog(2)"><div class="sn p" id="n2">2</div><h2>Test Database & Create Tables</h2><span class="st" id="s2">Pending</span></div>
<div class="cb" id="b2"><button class="btn bp" onclick="testDB()" id="btn2">Test & Create Tables</button><div class="res" id="r2"></div></div></div>

<div class="card"><div class="ch" onclick="tog(3)"><div class="sn p" id="n3">3</div><h2>Install PHPMailer <span style="font-size:12px;font-weight:400;color:#94a3b8">(optional)</span></h2><span class="st" id="s3">Pending</span></div>
<div class="cb" id="b3"><p style="font-size:13px;color:#64748b;margin-bottom:12px">Downloads Composer and installs PHPMailer for reliable email. Falls back to built-in SMTP if unavailable.</p>
<button class="btn bp" onclick="installPM()" id="btn3">Download & Install</button>
<button class="skip" onclick="skipStep(3)">Skip — use built-in SMTP</button>
<div class="res" id="r3"></div></div></div>

<div class="card"><div class="ch" onclick="tog(4)"><div class="sn p" id="n4">4</div><h2>Test Email</h2><span class="st" id="s4">Pending</span></div>
<div class="cb" id="b4">
<div class="fg" style="max-width:320px"><label>Send test to</label><input id="test_email" type="email" placeholder="your@email.com"/></div>
<button class="btn bp" onclick="testSMTP()" id="btn4">Send Test Email</button>
<button class="skip" onclick="skipStep(4)">Skip email test</button>
<div class="res" id="r4"></div></div></div>

<div class="card"><div class="ch" onclick="tog(5)"><div class="sn p" id="n5">5</div><h2>Complete</h2><span class="st" id="s5">Pending</span></div>
<div class="cb" id="b5">
<div class="done-box" id="done-box"><div style="font-size:48px;margin-bottom:8px">🎉</div><h2>Setup Complete!</h2><p>FormBuilder is ready. setup.php has been deleted.</p>
<div style="display:flex;gap:12px;justify-content:center;flex-wrap:wrap"><a href="index.php" class="btn bp">View Forms →</a><a href="admin.php" id="adm-link" class="btn" style="background:#10b981;color:#fff">Admin Dashboard →</a></div></div>
<div id="finish-box"><p style="font-size:13px;color:#64748b;margin-bottom:16px">Deletes setup.php and takes you to the app.</p>
<button class="btn" style="background:#ef4444;color:#fff" onclick="finish()">🗑 Delete setup.php & Finish</button></div>
<div class="res" id="r5"></div></div></div>
</div>

<script>
function tog(n){document.getElementById('b'+n).classList.toggle('open');}
function set(n,st,msg){const e=document.getElementById('n'+n);e.className='sn '+st;e.innerHTML=st==='d'?'✓':st==='e'?'✗':n;if(msg)document.getElementById('s'+n).textContent=msg;}
function res(n,ok,msg,log){const e=document.getElementById('r'+n);e.className='res show '+(ok?'ok':'err');e.innerHTML=(ok?'✅ ':'❌ ')+msg+(log?'<div class="log">'+log.map(l=>l.replace(/&/g,'&amp;').replace(/</g,'&lt;')).join('\n')+'</div>':'');}
function loading(id,on){const b=document.getElementById(id);if(!b)return;b.disabled=on;if(on)b.innerHTML='<span class="sp"></span> Working…';}
function post(a,ex){const fd=new FormData();fd.append('action',a);if(ex)Object.entries(ex).forEach(([k,v])=>fd.append(k,v));return fetch('setup.php',{method:'POST',body:fd}).then(r=>r.json());}
function genPW(){const a=new Uint8Array(20);crypto.getRandomValues(a);document.getElementById('ADMIN_PASSWORD').value=Array.from(a).map(b=>b.toString(16).padStart(2,'0')).join('');}
function syncSec(){const p=document.getElementById('SMTP_PORT').value,s=document.getElementById('SMTP_SECURE');if(p==='465')s.value='ssl';else if(p==='587')s.value='tls';else s.value='';}
function skipStep(n){set(n,'d','Skipped');if(n===3){document.getElementById('b4').classList.add('open');set(4,'a','Ready');}if(n===4){document.getElementById('b5').classList.add('open');set(5,'a','Ready');}}

async function envCheck(){
  loading('btn0',true);const j=await post('env_check');loading('btn0',false);
  if(!j.ok){res(0,false,'Check failed');set(0,'e','Failed');return;}
  const hf=j.checks.some(c=>!c.ok&&!c.warn);
  document.getElementById('r0').className='res show '+(hf?'err':'ok');
  document.getElementById('r0').innerHTML=(hf?'❌ Issues found:':'✅ Environment looks good!')+
    '<div class="chklist" style="margin-top:12px">'+j.checks.map(c=>`<div class="chkrow"><span class="ic">${c.ok?'✅':c.warn?'⚠️':'❌'}</span><span class="lb">${c.label}</span><span class="vl">${c.value}</span></div>`).join('')+'</div>';
  set(0,hf?'e':'d',hf?'Issues found':'Passed');
  if(!hf){document.getElementById('b1').classList.add('open');set(1,'a','Ready');}
}

async function saveCfg(){
  const req=['ADMIN_PASSWORD','DB_NAME','DB_USER','DB_PASS'];
  for(const f of req){if(!document.getElementById(f).value.trim()){res(1,false,'Please fill all required fields (*)');return;}}
  loading('btn1',true);
  const fields=['APP_NAME','APP_URL','APP_TIMEZONE','ADMIN_PASSWORD','DB_HOST','DB_PORT','DB_NAME','DB_USER','DB_PASS','FROM_EMAIL','FROM_NAME','ADMIN_EMAIL','SMTP_HOST','SMTP_PORT','SMTP_SECURE','SMTP_USER','SMTP_PASS','ALLOWED_ORIGIN'];
  const ex={};fields.forEach(f=>{const el=document.getElementById(f);if(el)ex[f]=el.value;});
  const j=await post('save_config',ex);loading('btn1',false);
  if(j.ok){res(1,true,'config.php saved.');set(1,'d','Saved');document.getElementById('b2').classList.add('open');set(2,'a','Ready');}
  else{res(1,false,j.error);set(1,'e','Failed');}
}

async function testDB(){
  loading('btn2',true);const j=await post('test_db');loading('btn2',false);
  if(j.ok){res(2,true,j.message);set(2,'d','Connected');document.getElementById('b3').classList.add('open');set(3,'a','Ready');}
  else{res(2,false,j.error);set(2,'e','Failed');}
}

async function installPM(){
  loading('btn3',true);const j=await post('install_phpmailer');loading('btn3',false);
  if(j.ok){res(3,true,j.skipped?'Already installed.':'Installed.',j.log);set(3,'d','Installed');}
  else{document.getElementById('r3').className='res show warn';document.getElementById('r3').innerHTML='⚠️ '+j.error+(j.log?'<div class="log">'+j.log.join('\n')+'</div>':'')+'<p style="margin-top:8px;font-size:12px">Raw SMTP fallback will be used.</p>';set(3,'d','Fallback');}
  document.getElementById('b4').classList.add('open');set(4,'a','Ready');
  document.getElementById('test_email').value=document.getElementById('ADMIN_EMAIL')?.value||'';
}

async function testSMTP(){
  const em=document.getElementById('test_email').value.trim();
  if(!em){res(4,false,'Enter an email address.');return;}
  loading('btn4',true);const j=await post('test_smtp',{test_email:em});loading('btn4',false);
  if(j.ok){res(4,true,'Test email sent to '+em);set(4,'d','Sent');document.getElementById('b5').classList.add('open');set(5,'a','Ready');}
  else{res(4,false,j.error||'Failed');set(4,'e','Failed');}
}

async function finish(){
  await post('self_delete').catch(()=>{});
  document.getElementById('finish-box').style.display='none';
  document.getElementById('done-box').style.display='block';
  set(5,'d','Complete');
}

window.addEventListener('load',envCheck);
</script></body></html>
