<?php
// =============================================================================
// health.php — first-run health check.
//
// Runs the same probes debug.php does but presents them as a big green ✓ / red
// ✗ status list. Buyer-facing (admin-authenticated, no support token) so a
// new install can self-diagnose without pinging support first.
// =============================================================================
$page_title  = 'Health Check';
$page_active = 'health';
require __DIR__ . '/includes/page_header.php';

$panel_root = realpath(__DIR__);
$checks = [];

// ---- PHP + extensions ----
$checks[] = [
    'group' => 'PHP',
    'label' => 'PHP version ≥ 7.4',
    'ok'    => version_compare(PHP_VERSION, '7.4', '>='),
    'value' => PHP_VERSION,
];
foreach (['pdo_sqlite', 'sqlite3', 'openssl', 'curl', 'gd', 'mbstring', 'json'] as $ext) {
    $checks[] = [
        'group' => 'PHP extensions',
        'label' => $ext,
        'ok'    => extension_loaded($ext),
        'value' => extension_loaded($ext) ? 'loaded' : 'MISSING — install via cPanel → Select PHP Version, or php.ini',
    ];
}
$has_finfo = extension_loaded('fileinfo');
$checks[] = [
    'group' => 'PHP extensions',
    'label' => 'fileinfo (recommended, not required)',
    'ok'    => $has_finfo,
    'warn'  => !$has_finfo,   // yellow, not red — the panel has a getimagesize() fallback
    'value' => $has_finfo ? 'loaded' : 'missing — panel falls back to getimagesize() (works, but weaker check)',
];

// ---- ini limits ----
$post = ini_get('post_max_size');
$upl  = ini_get('upload_max_filesize');
$checks[] = ['group' => 'Upload limits', 'label' => 'post_max_size ≥ 10M', 'ok' => _size_at_least($post, 10 * 1024 * 1024), 'value' => $post];
$checks[] = ['group' => 'Upload limits', 'label' => 'upload_max_filesize ≥ 10M', 'ok' => _size_at_least($upl, 10 * 1024 * 1024), 'value' => $upl];

// ---- File permissions ----
$writable_paths = [
    ['data',                              'panel writes panel.db + panel.error.log here'],
    ['data/panel.db',                     'panel.db must be writable'],
    ['uploads',                           'buyer uploads (slideshow, VPN zip) land here'],
    ['uploads/slideshows',                'slideshow images'],
];
foreach ($writable_paths as [$rel, $desc]) {
    $p = __DIR__ . '/' . $rel;
    $exists = file_exists($p);
    $writable = $exists && is_writable($p);
    $checks[] = [
        'group' => 'File permissions',
        'label' => $rel,
        'ok'    => $writable,
        'value' => $exists ? ($writable ? 'writable' : 'not writable — chmod 775 needed') : 'missing',
        'note'  => $desc,
    ];
}

// ---- .htaccess + mod_rewrite ----
$ht = __DIR__ . '/.htaccess';
$checks[] = [
    'group' => 'Apache config',
    'label' => '.htaccess present',
    'ok'    => is_file($ht),
    'value' => is_file($ht) ? sprintf('%.1f KB', filesize($ht) / 1024) : 'MISSING — /auth, /add, etc. will 404',
];

// ---- Reseller variant sanity ----
$apk_const = __DIR__ . '/includes/apksec_constants.php';
$apk_ok = false;
if (is_file($apk_const)) {
    $content = file_get_contents($apk_const);
    $apk_ok = strpos($content, 'RESELLER VARIANT') !== false;
}
$checks[] = [
    'group' => 'Reseller sanity',
    'label' => 'apksec_constants.php is RESELLER VARIANT',
    'ok'    => $apk_ok,
    'value' => $apk_ok ? 'reseller' : 'WRONG variant — Quick URL Encrypt will produce broken literals',
];
$crypto = __DIR__ . '/includes/crypto.php';
$crypto_ok = false;
if (is_file($crypto)) {
    $crypto_ok = substr_count(file_get_contents($crypto), 'random_bytes(32)') === 0;
}
$checks[] = [
    'group' => 'Reseller sanity',
    'label' => 'crypto.php is RESELLER VARIANT (no 32-byte tail)',
    'ok'    => $crypto_ok,
    'value' => $crypto_ok ? 'no tail (reseller lib matches)' : 'WRONG variant — customer format detected',
];

// ---- addaplaylist auto-register ----
$aap = db_one('SELECT addaplaylist_panel_code FROM config WHERE id = 1');
$aap_code = trim((string)($aap['addaplaylist_panel_code'] ?? ''));
$checks[] = [
    'group' => 'addaplaylist',
    'label' => 'panel_code minted',
    'ok'    => $aap_code !== '',
    'value' => $aap_code !== '' ? $aap_code : 'EMPTY — auto-register failed (outbound cURL blocked?). Retry via cron/addaplaylist_register.php',
];

// ---- Outbound HTTPS ----
$out_ok = false;
$out_ms = null;
$out_note = 'skipped';
if (function_exists('curl_init')) {
    $t0 = microtime(true);
    $ch = curl_init('https://addaplaylist.com/');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true, CURLOPT_NOBODY => true,
        CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 8,
    ]);
    curl_exec($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $out_ms = (int)((microtime(true) - $t0) * 1000);
    $out_ok = $code >= 200 && $code < 500;
    $out_note = "HTTP $code in {$out_ms}ms";
}
$checks[] = [
    'group' => 'Network',
    'label' => 'Outbound HTTPS (test: addaplaylist.com)',
    'ok'    => $out_ok,
    'value' => $out_note,
];

// ---- Summary counts ----
$fail = 0; $warn = 0; $pass = 0;
foreach ($checks as $c) {
    if (!empty($c['warn']) && !$c['ok']) { $warn++; continue; }
    if ($c['ok']) $pass++; else $fail++;
}

function _size_at_least($ini_val, $needed_bytes) {
    $s = trim((string)$ini_val);
    if ($s === '') return false;
    $u = strtolower(substr($s, -1));
    $n = (int)$s;
    if ($u === 'g') $n *= 1024 * 1024 * 1024;
    elseif ($u === 'm') $n *= 1024 * 1024;
    elseif ($u === 'k') $n *= 1024;
    return $n >= $needed_bytes;
}
?>

<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 / Health Check
    </p>
    <h2 class="text-2xl font-bold text-white flex items-center gap-3">
        <i class="ph ph-stethoscope text-primary-400"></i> Health Check
    </h2>
</div>

<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-5">
    <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 (int)$pass; ?></p>
    </div>
    <div class="card p-4">
        <p class="text-[11px] text-dark-400 uppercase tracking-wider">Warnings</p>
        <p class="text-3xl font-bold" style="color:#f39c12"><?php echo (int)$warn; ?></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 (int)$fail; ?></p>
    </div>
</div>

<?php
// Group by group name for display
$grouped = [];
foreach ($checks as $c) $grouped[$c['group']][] = $c;
foreach ($grouped as $group => $rows):
?>
<div class="card mb-4">
    <div class="card-head"><h3><i class="ph ph-list-checks text-primary-400"></i> <?php echo h($group); ?></h3></div>
    <table class="compact w-full">
        <tbody>
        <?php foreach ($rows as $c):
            $status = !empty($c['warn']) && !$c['ok'] ? 'warn' : ($c['ok'] ? 'ok' : 'fail');
            $icon   = $status === 'ok' ? 'ph-check-circle' : ($status === 'warn' ? 'ph-warning-circle' : 'ph-x-circle');
            $color  = $status === 'ok' ? '#22c55e' : ($status === 'warn' ? '#f39c12' : '#ef4444');
        ?>
        <tr>
            <td style="width:32px" class="text-center"><i class="ph <?php echo $icon; ?> text-xl" style="color:<?php echo $color; ?>"></i></td>
            <td class="text-white font-medium"><?php echo h($c['label']); ?></td>
            <td class="mono text-xs text-dark-300"><?php echo h($c['value']); ?></td>
        </tr>
        <?php if (!empty($c['note'])): ?>
        <tr><td></td><td colspan="2" class="text-[11px] text-dark-500"><?php echo h($c['note']); ?></td></tr>
        <?php endif; ?>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endforeach; ?>

<div class="text-xs text-dark-500 mt-4">
    Generated <?php echo date('c'); ?> · Rerun anytime by refreshing this page.
</div>

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