<?php
/**
 * Valu-Basic — Health Check
 * Zugriff: healthcheck_basic.php?token=valu_health_2026
 */

$token = $_GET['token'] ?? '';
if ($token !== 'valu_health_2026') { http_response_code(403); die('Kein Zugriff.'); }

$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
         . '://' . $_SERVER['HTTP_HOST'];

$checks = [
    // [Kategorie, Pfad, Erwartete Codes (Array), Muss-enthalten, Darf-nicht-enthalten]
    ['Frontend', '/index.php',                [200],      'Valu-Basic', 'Fatal error'],
    ['Frontend', '/add.php',                  [200],      null,         'Fatal error'],
    ['Frontend', '/dashboard.php',            [200],      null,         'Fatal error'],
    ['Frontend', '/settings.php',             [200],      null,         'Fatal error'],
    ['Frontend', '/export_csv.php',           [200],      null,         'Fatal error'],
    ['Frontend', '/export_pdf.php',           [200],      null,         'Fatal error'],
    ['Frontend', '/manifest.json',            [200],      'name',       null],
    ['Frontend', '/sw.js',                    [200],      null,         null],
    ['Frontend', '/offline.php',              [200],      null,         'Fatal error'],
    ['Security', '/login.php',                [200,302],  null,         'Fatal error'],  // 302 = eingeloggt
    ['Security', '/data/valu_basic.sqlite',   [403,404],  null,         null],
    ['Security', '/backups/',                 [403,404],  null,         null],           // 404 = nicht vorhanden = OK
    ['Backend',  '/backend/',                 [200],      null,         'Fatal error'],
    ['Backend',  '/backend/categories.php',   [200],      null,         'Fatal error'],
    ['Backend',  '/backend/gallery.php',      [200],      null,         'Fatal error'],
    ['Backend',  '/backend/locations.php',    [200],      null,         'Fatal error'],
    ['Backend',  '/backend/standorte.php',    [200],      null,         'Fatal error'],
    ['Backend',  '/backend/stats.php',        [200],      null,         'Fatal error'],
    ['Backend',  '/backend/backup.php',       [200],      null,         'Fatal error'],
    ['Backend',  '/backend/system.php',       [200],      null,         'Fatal error'],
    ['Backend',  '/backend/users.php',        [200],      null,         'Fatal error'],
    ['Backend',  '/backend/permissions.php',  [200],      null,         'Fatal error'],
    ['Backend',  '/backend/insurance.php',    [200],      null,         'Fatal error'],
    ['Backend',  '/backend/logs.php',         [200],      null,         'Fatal error'],
    ['Backend',  '/backend/activity_log.php', [200],      null,         'Fatal error'],
    ['AJAX',     '/ajax/get_positionen.php',  [200],      null,         'Fatal error'],
];

function hc_get(string $url): array {
    $ctx = stream_context_create(['http' => [
        'timeout' => 8, 'ignore_errors' => true, 'max_redirects' => 0,
        'header'  => 'Cookie: ' . ($_SERVER['HTTP_COOKIE'] ?? ''),
    ], 'ssl' => ['verify_peer' => false]]);
    $start = microtime(true);
    $body  = @file_get_contents($url, false, $ctx);
    $ms    = round((microtime(true) - $start) * 1000);
    $code  = 0;
    if (isset($http_response_header)) {
        preg_match('/HTTP\/\S+ (\d+)/', $http_response_header[0] ?? '', $m);
        $code = intval($m[1] ?? 0);
    }
    return ['body' => $body ?: '', 'code' => $code, 'ms' => $ms];
}

$results = [];
$total = $passed = $failed = 0;

foreach ($checks as [$cat, $path, $expectedCodes, $mustContain, $mustNot]) {
    $r = hc_get($baseUrl . $path);
    $ok = true;
    $detail = 'HTTP ' . $r['code'];

    if (!in_array($r['code'], $expectedCodes)) {
        $ok = false;
        $detail = "HTTP {$r['code']} (erwartet " . implode('/', $expectedCodes) . ")";
    } elseif ($mustContain && stripos($r['body'], $mustContain) === false) {
        $ok = false;
        $detail = "Inhalt '$mustContain' fehlt";
    } elseif ($mustNot && stripos($r['body'], $mustNot) !== false) {
        $ok = false;
        preg_match('/(' . preg_quote($mustNot, '/') . '[^\n]{0,80})/i', $r['body'], $m);
        $detail = htmlspecialchars(substr($m[1] ?? $mustNot, 0, 100));
    }

    $results[] = ['cat' => $cat, 'path' => $path, 'ok' => $ok, 'detail' => $detail, 'ms' => $r['ms']];
    $total++; $ok ? $passed++ : $failed++;
}

$pct = $total > 0 ? round($passed / $total * 100) : 0;
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Valu-Basic Health Check</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Segoe UI',sans-serif;background:#0f1117;color:#e0e0e0;padding:1.5rem}
h1{color:#f0a500;margin-bottom:.25rem;font-size:1.4rem}
.sub{color:#666;font-size:.85rem;margin-bottom:1.5rem}
.summary{display:flex;gap:1rem;margin-bottom:1.5rem;flex-wrap:wrap}
.stat{background:#1e2030;border-radius:10px;padding:.75rem 1.5rem;text-align:center}
.stat .num{font-size:1.6rem;font-weight:700;font-family:monospace}
.stat .lbl{font-size:.75rem;color:#888}
.ok-num{color:#10b981}.err-num{color:#ef4444}.tot-num{color:#aaa}.pct-num{color:#f0a500}
.progress{background:#1e2030;border-radius:6px;height:8px;margin-bottom:1.5rem;overflow:hidden}
.progress-fill{height:100%;background:linear-gradient(90deg,#10b981,#06b6d4);border-radius:6px}
.section{margin-bottom:1.5rem}
.section-title{font-size:.8rem;font-weight:700;color:#666;letter-spacing:.1em;text-transform:uppercase;padding:.4rem 0;border-bottom:1px solid #1e2030;margin-bottom:.5rem}
.row{display:flex;align-items:center;gap:.75rem;padding:.55rem .75rem;border-radius:8px;font-size:.85rem;margin-bottom:2px}
.row:hover{background:#1a1a2a}
.row.err{background:rgba(239,68,68,.07)}
.icon{width:20px;text-align:center;flex-shrink:0}
.path{font-family:monospace;flex:1;color:#aaa}
.path.err{color:#f87171}
.detail{font-family:monospace;font-size:.75rem;color:#666;max-width:300px;text-align:right}
.detail.err{color:#fca5a5}
.ms-col{font-family:monospace;font-size:.75rem;color:#444;min-width:50px;text-align:right}
.refresh{background:#1e2030;border:1px solid #333;color:#eee;padding:.4rem .9rem;border-radius:8px;cursor:pointer;font-size:.85rem;margin-bottom:1rem}
.refresh:hover{background:#2a2d40}
@media print {
  body { background:#fff; color:#000; padding:.5rem; }
  .refresh { display:none; }
  .row.err { background:#ffe0e0 !important; }
  .path { color:#333 !important; }
  .detail { color:#555 !important; }
  .ms-col { color:#777 !important; }
  .stat { border:1px solid #ddd; }
  .ok-num { color:#10b981 !important; }
  .err-num { color:#ef4444 !important; }
}
</style>
</head>
<body>
<h1>🩺 Valu-Basic Health Check</h1>
<p class="sub"><?= $baseUrl ?> · <?= date('d.m.Y H:i:s') ?></p>
<button class="refresh" onclick="location.reload()">↺ Neu prüfen</button>
<button class="refresh" onclick="window.print()" style="margin-left:.5rem">🖨 Drucken</button>
<div class="summary">
  <div class="stat"><div class="num ok-num"><?= $passed ?></div><div class="lbl">OK</div></div>
  <div class="stat"><div class="num err-num"><?= $failed ?></div><div class="lbl">Fehler</div></div>
  <div class="stat"><div class="num tot-num"><?= $total ?></div><div class="lbl">Gesamt</div></div>
  <div class="stat"><div class="num pct-num"><?= $pct ?>%</div><div class="lbl">Bestanden</div></div>
</div>
<div class="progress"><div class="progress-fill" style="width:<?= $pct ?>%"></div></div>
<?php
$cats = array_unique(array_column($results, 'cat'));
foreach ($cats as $cat):
    $cr = array_filter($results, fn($r) => $r['cat'] === $cat);
    $cok = count(array_filter($cr, fn($r) => $r['ok']));
?>
<div class="section">
  <div class="section-title"><?= $cat ?> &nbsp; <?= $cok ?>/<?= count($cr) ?></div>
  <?php foreach ($cr as $r): ?>
  <div class="row <?= $r['ok'] ? '' : 'err' ?>">
    <span class="icon"><?= $r['ok'] ? '✅' : '❌' ?></span>
    <span class="path <?= $r['ok'] ? '' : 'err' ?>"><?= htmlspecialchars($r['path']) ?></span>
    <span class="detail <?= $r['ok'] ? '' : 'err' ?>"><?= $r['detail'] ?></span>
    <span class="ms-col"><?= $r['ms'] ?>ms</span>
  </div>
  <?php endforeach; ?>
</div>
<?php endforeach; ?>
</body></html>
