<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/bootstrap.php';
api_common_headers('application/json; charset=utf-8');

$required = ['pdo', 'pdo_sqlite', 'sqlite3', 'curl', 'openssl', 'json', 'session'];
$optional = ['fileinfo', 'mbstring', 'zip'];
$missing = [];
$optionalMissing = [];

foreach ($required as $extension) {
    if (!extension_loaded($extension)) {
        $missing[] = $extension;
    }
}

foreach ($optional as $extension) {
    if (!extension_loaded($extension)) {
        $optionalMissing[] = $extension;
    }
}

if (version_compare(PHP_VERSION, '7.4.0', '<')) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'status' => 'error',
        'php' => PHP_VERSION,
        'minimum_php' => '7.4.0',
        'missing_extensions' => $missing,
        'optional_missing_extensions' => $optionalMissing,
        'message' => 'PHP 7.4 or newer is required.'
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

if ($missing) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'status' => 'error',
        'php' => PHP_VERSION,
        'minimum_php' => '7.4.0',
        'missing_extensions' => $missing,
        'optional_missing_extensions' => $optionalMissing,
        'message' => 'Required PHP extensions are missing.'
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $pdo = db();
    echo json_encode([
        'success' => true,
        'status' => 'ok',
        'php' => PHP_VERSION,
        'minimum_php' => '7.4.0',
        'missing_extensions' => [],
        'optional_missing_extensions' => $optionalMissing,
        'database' => 'api/.db.db',
        'sqlite' => (bool) $pdo,
        'endpoints' => [
            'dns' => 'api/dns.php',
            'vpn' => 'api/vpns.php?list=1',
            'sports' => 'api/sports.php?config=1',
            'webview' => 'api/webview.php',
            'ip_info' => 'api/ip-info.php'
        ]
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'status' => 'error',
        'php' => PHP_VERSION,
        'minimum_php' => '7.4.0',
        'missing_extensions' => [],
        'optional_missing_extensions' => $optionalMissing,
        'message' => 'Panel health check failed.'
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
