<?php
// =============================================================================
// selftest.php — end-to-end endpoint probe.
//
// One-click test that has the panel call every endpoint the app relies on
// (locally, via cURL to its own public URL) and reports pass/fail with the
// exact HTTP code + expected outcome.  Answers the "is the panel itself
// broken, or is my APK the problem?" question in 3 seconds.
// =============================================================================
$page_title  = 'Self Test';
$page_active = 'selftest';
require __DIR__ . '/includes/page_header.php';

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
$base   = $scheme . '://' . $host . rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? '/'), '/');

function probe(string $url, string $method, ?string $body, array $expect_codes, string $note = ''): array {
    $t0 = microtime(true);
    $ch = curl_init($url);
    $opts = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 4,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
    ];
    if ($body !== null) $opts[CURLOPT_POSTFIELDS] = $body;
    curl_setopt_array($ch, $opts);
    $resp = curl_exec($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);
    $ms = (int)((microtime(true) - $t0) * 1000);
    return [
        'url'    => $url,
        'method' => $method,
        'code'   => $code,
        'ok'     => $code !== 0 && in_array($code, $expect_codes, true),
        'expect' => implode('|', array_map('strval', $expect_codes)),
        'ms'     => $ms,
        'err'    => $err,
        'note'   => $note,
        'body'   => substr((string)$resp, 0, 120),
    ];
}

$probes = [];
if (($_POST['run'] ?? '') === '1') {
    // Local endpoints — app-facing
    $probes[] = probe("$base/auth",         'POST', '{}',                      [400], 'auth expects encrypted envelope; 400 = handler alive');
    $probes[] = probe("$base/auth",         'GET',  null,                      [405], 'auth accepts POST only');
    $probes[] = probe("$base/has_playlist?mac=aa:bb:cc:dd:ee:ff", 'GET', null, [200], 'always returns 200 with "0" or "1"');
    $probes[] = probe("$base/vpns.php",     'GET',  null,                      [200], 'app-facing VPN list; 200 = OK');
    $probes[] = probe("$base/api/webview/slideshow.php", 'GET', null,          [200], 'slideshow WebView; 200 = OK');
    $probes[] = probe("$base/api/webview/frameview.php", 'GET', null,          [200], 'frameview WebView; 200 = OK');
    $probes[] = probe("$base/api/addaplaylist.php?action=get_dns", 'GET', null,[403, 404], '403/404 without auth token = handler present');
    // Outbound
    $probes[] = probe("https://addaplaylist.com/",     'HEAD', null, [200, 301, 302, 400, 403, 404, 405], 'outbound HTTPS to addaplaylist.com');
    $probes[] = probe("https://raw.githubusercontent.com/", 'HEAD', null, [200, 301, 302, 400, 403, 404, 405], 'outbound HTTPS test');
}

$pass = $fail = 0;
foreach ($probes as $p) { if ($p['ok']) $pass++; else $fail++; }
?>

<div class="-mx-6 -mt-6 px-6 py-5 mb-6 border-b border-dark-700" style="background:#111;">
    <p class="text-xs font-semibold text-primary-400 uppercase tracking-wider mb-1">
        <span class="text-dark-400">Master Panel</span> / Support / Self Test
    </p>
    <h2 class="text-2xl font-bold text-white flex items-center gap-3">
        <i class="ph ph-broadcast text-primary-400"></i> Self Test
    </h2>
</div>

<div class="card mb-4">
    <div class="p-5">
        <p class="text-sm text-dark-300 mb-3">
            Runs a probe against every panel endpoint the app depends on, plus outbound HTTPS.
            Answers "is my panel healthy?" in one click. Nothing is written or changed.
        </p>
        <form method="POST">
            <input type="hidden" name="run" value="1">
            <button class="btn-primary text-sm" type="submit"><i class="ph ph-play"></i> Run diagnostics</button>
        </form>
    </div>
</div>

<?php if ($probes): ?>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
    <div class="card p-4">
        <p class="text-[11px] text-dark-400 uppercase tracking-wider">Passing</p>
        <p class="text-3xl font-bold" style="color:#22c55e"><?php echo $pass; ?></p>
    </div>
    <div class="card p-4">
        <p class="text-[11px] text-dark-400 uppercase tracking-wider">Failing</p>
        <p class="text-3xl font-bold" style="color:<?php echo $fail ? '#ef4444' : '#22c55e'; ?>"><?php echo $fail; ?></p>
    </div>
</div>

<div class="card">
    <div class="card-head"><h3><i class="ph ph-list-bullets text-primary-400"></i> Probe results</h3></div>
    <table class="compact w-full">
        <thead>
            <tr><th>#</th><th>Endpoint</th><th>Got</th><th>Expected</th><th>ms</th><th>Note</th></tr>
        </thead>
        <tbody>
        <?php foreach ($probes as $i => $p): ?>
        <tr>
            <td style="width:32px" class="text-center">
                <i class="ph <?php echo $p['ok'] ? 'ph-check-circle' : 'ph-x-circle'; ?> text-lg"
                   style="color:<?php echo $p['ok'] ? '#22c55e' : '#ef4444'; ?>"></i>
            </td>
            <td class="mono text-xs text-dark-200"><?php echo h($p['method']); ?> <?php echo h(str_replace($base, '.', $p['url'])); ?></td>
            <td class="mono <?php echo $p['ok'] ? '' : 'text-red-400'; ?>">
                <?php echo $p['code'] ? (int)$p['code'] : 'ERR'; ?>
                <?php if ($p['err']): ?><span class="text-red-400 text-[10px]"> · <?php echo h($p['err']); ?></span><?php endif; ?>
            </td>
            <td class="mono text-xs text-dark-400"><?php echo h($p['expect']); ?></td>
            <td class="mono text-xs text-dark-400"><?php echo (int)$p['ms']; ?></td>
            <td class="text-[11px] text-dark-400"><?php echo h($p['note']); ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<?php require __DIR__ . '/includes/page_footer.php'; ?>
