<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Spaceship Debug</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:monospace;background:#0d1117;color:#c9d1d9;padding:20px;}
h1{color:#25D366;margin-bottom:16px;font-size:20px;}
h2{color:#58a6ff;margin:16px 0 8px;font-size:15px;}
.card{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:14px;margin-bottom:12px;}
.pass{border-color:#25D366;}.fail{border-color:#f85149;}.warn{border-color:#d29922;}
label{font-size:13px;color:#8b949e;display:block;margin-bottom:4px;}
input{width:100%;padding:8px;background:#0d1117;border:1px solid #30363d;border-radius:6px;color:#c9d1d9;font-family:monospace;font-size:14px;outline:none;margin-bottom:8px;}
button{padding:8px 18px;background:#25D366;color:#000;border:none;border-radius:6px;cursor:pointer;font-weight:bold;font-size:14px;margin-right:8px;}
button:hover{background:#1ea952;}
button.sec{background:#21262d;color:#c9d1d9;border:1px solid #30363d;}
pre{font-size:13px;white-space:pre-wrap;margin-top:10px;padding:10px;background:#0d1117;border-radius:4px;border:1px solid #21262d;max-height:200px;overflow-y:auto;}
.ok{color:#25D366;}.er{color:#f85149;}.info{color:#58a6ff;}
.row{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px;}
</style>
</head>
<body>
<h1>🔐 Spaceship — Live Debug</h1>
<p style="color:#8b949e;margin-bottom:20px;font-size:13px;">This page tests every part of the setup. All results show raw server responses.</p>

<!-- SYSTEM CHECKS -->
<h2>1. System Checks</h2>
<div class="card" id="sys-card">
<button onclick="runChecks()">▶ Run Checks</button>
<pre id="sys-out">Click "Run Checks"</pre>
</div>

<!-- REGISTER -->
<h2>2. Register</h2>
<div class="card">
<div class="row">
  <div style="flex:1"><label>Username</label><input id="reg-u" value="testuser" placeholder="username"></div>
  <div style="flex:1"><label>Password</label><input id="reg-p" value="test123" type="password"></div>
</div>
<button onclick="doRegister()">Register</button>
<button class="sec" onclick="document.getElementById('reg-out').textContent=''">Clear</button>
<pre id="reg-out">—</pre>
</div>

<!-- LOGIN -->
<h2>3. Login</h2>
<div class="card">
<div class="row">
  <div style="flex:1"><label>Username</label><input id="log-u" value="testuser" placeholder="username"></div>
  <div style="flex:1"><label>Password</label><input id="log-p" value="test123" type="password"></div>
</div>
<button onclick="doLogin()">Login</button>
<pre id="log-out">—</pre>
</div>

<!-- TOKEN TEST -->
<h2>4. Test Auth Token</h2>
<div class="card">
<label>JWT Token (auto-filled from login)</label>
<input id="tok" placeholder="Will be filled after login">
<button onclick="testToken()">Test /api/online.php</button>
<pre id="tok-out">—</pre>
</div>

<!-- RAW TEST -->
<h2>5. Raw PHP Response Inspector</h2>
<div class="card">
<label>URL to fetch</label>
<input id="raw-url" value="api/register.php" placeholder="api/register.php">
<label>Body (JSON)</label>
<input id="raw-body" value='{"username":"hello","password":"world1","publicKey":"testkey"}'>
<div class="row">
<button onclick="doRaw('POST')">POST</button>
<button class="sec" onclick="doRaw('GET')">GET</button>
</div>
<pre id="raw-out">—</pre>
</div>

<script>
// Detect base path
var BASE = (function(){
    var p = window.location.pathname;
    return p.substring(0, p.lastIndexOf('/')+1);
})();

async function runChecks() {
    var out = document.getElementById('sys-out');
    out.innerHTML = '<span class="info">Running…</span>';
    var lines = [];

    // PHP check via a tiny inline endpoint
    try {
        var r = await fetch(BASE + 'api/ping.php');
        var t = await r.text();
        if (t.includes('pong')) lines.push('<span class="ok">✅ PHP is working</span>');
        else lines.push('<span class="er">❌ PHP returned: ' + esc(t.substring(0,100)) + '</span>');
    } catch(e) {
        lines.push('<span class="er">❌ Cannot reach api/ping.php — is Apache running?</span>');
    }

    // DB check
    try {
        var r2 = await fetch(BASE + 'api/dbcheck.php');
        var d2 = await r2.json();
        if (d2.ok) lines.push('<span class="ok">✅ MySQL connected — database "wachat" found</span>' +
            (d2.tables ? '\n   Tables: ' + d2.tables.join(', ') : ''));
        else lines.push('<span class="er">❌ DB error: ' + esc(d2.error) + '</span>\n<span class="info">   → Fix: Start MySQL in XAMPP, then run database.sql in phpMyAdmin</span>');
    } catch(e) {
        lines.push('<span class="er">❌ DB check failed: ' + esc(''+e) + '</span>');
    }

    // Register endpoint reachable?
    try {
        var r3 = await fetch(BASE + 'api/register.php', {method:'POST', headers:{'Content-Type':'application/json'}, body:'{}'});
        var t3 = await r3.text();
        if (t3[0] === '{') lines.push('<span class="ok">✅ register.php returns JSON</span>');
        else lines.push('<span class="er">❌ register.php returned non-JSON:\n' + esc(t3.substring(0,300)) + '</span>\n<span class="info">   → This means there is a PHP error. Check XAMPP error log.</span>');
    } catch(e) {
        lines.push('<span class="er">❌ register.php unreachable: ' + esc(''+e) + '</span>');
    }

    out.innerHTML = lines.join('\n');
}

async function doRegister() {
    var out = document.getElementById('reg-out');
    out.innerHTML = '<span class="info">Calling register.php…</span>';
    try {
        // Generate a real ECDH key
        var kp  = await crypto.subtle.generateKey({name:'ECDH',namedCurve:'P-256'},true,['deriveKey']);
        var raw = await crypto.subtle.exportKey('spki', kp.publicKey);
        var pk  = btoa(String.fromCharCode(...new Uint8Array(raw)));
        var u   = document.getElementById('reg-u').value.trim();
        var p   = document.getElementById('reg-p').value;
        var res = await fetch(BASE + 'api/register.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({username: u, password: p, publicKey: pk})
        });
        var txt = await res.text();
        out.innerHTML = '<span class="info">HTTP ' + res.status + '</span>\n' +
            '<span class="info">Raw response:</span>\n' + esc(txt) + '\n';
        try {
            var j = JSON.parse(txt);
            if (j.ok) {
                out.innerHTML += '\n<span class="ok">✅ REGISTERED OK! Now try Login.</span>';
                document.getElementById('log-u').value = u;
                document.getElementById('log-p').value = p;
            } else {
                out.innerHTML += '\n<span class="er">❌ Error: ' + esc(j.error) + '</span>';
            }
        } catch(e) {
            out.innerHTML += '\n<span class="er">❌ Response is NOT valid JSON — PHP error above</span>';
        }
    } catch(e) {
        out.innerHTML = '<span class="er">❌ JS exception: ' + esc(''+e) + '</span>';
    }
}

async function doLogin() {
    var out = document.getElementById('log-out');
    out.innerHTML = '<span class="info">Calling login.php…</span>';
    try {
        var kp  = await crypto.subtle.generateKey({name:'ECDH',namedCurve:'P-256'},true,['deriveKey']);
        var raw = await crypto.subtle.exportKey('spki', kp.publicKey);
        var pk  = btoa(String.fromCharCode(...new Uint8Array(raw)));
        var u   = document.getElementById('log-u').value.trim();
        var p   = document.getElementById('log-p').value;
        var res = await fetch(BASE + 'api/login.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({username: u, password: p, publicKey: pk})
        });
        var txt = await res.text();
        out.innerHTML = '<span class="info">HTTP ' + res.status + '</span>\n' +
            '<span class="info">Raw response:</span>\n' + esc(txt) + '\n';
        try {
            var j = JSON.parse(txt);
            if (j.token) {
                document.getElementById('tok').value = j.token;
                out.innerHTML += '\n<span class="ok">✅ LOGGED IN! Token stored above.</span>';
            } else {
                out.innerHTML += '\n<span class="er">❌ Error: ' + esc(j.error||'unknown') + '</span>';
            }
        } catch(e) {
            out.innerHTML += '\n<span class="er">❌ Response is NOT valid JSON — PHP error above</span>';
        }
    } catch(e) {
        out.innerHTML = '<span class="er">❌ JS exception: ' + esc(''+e) + '</span>';
    }
}

async function testToken() {
    var tok = document.getElementById('tok').value.trim();
    var out = document.getElementById('tok-out');
    if (!tok) { out.textContent = 'Paste a token first'; return; }
    out.innerHTML = '<span class="info">Testing…</span>';
    var res = await fetch(BASE + 'api/online.php?token=' + encodeURIComponent(tok));
    var txt = await res.text();
    out.innerHTML = 'HTTP ' + res.status + '\n' + esc(txt);
}

async function doRaw(method) {
    var url  = document.getElementById('raw-url').value;
    var body = document.getElementById('raw-body').value;
    var out  = document.getElementById('raw-out');
    out.innerHTML = '<span class="info">Fetching…</span>';
    var opts = {method: method, headers: {'Content-Type':'application/json'}};
    if (method === 'POST') opts.body = body;
    var res = await fetch(BASE + url, opts);
    var txt = await res.text();
    out.innerHTML = '<span class="info">HTTP ' + res.status + '</span>\n' + esc(txt);
}

function esc(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

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