<?php
// FIX: Protected script against public enumeration
$admin_user = 'admin';
$admin_pass = 'Cyber@Panel@2026';

// FIX: FastCGI / PHP-FPM Admin Lockout
if (!isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['HTTP_AUTHORIZATION'])) {
    if (preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
        $credentials = explode(':', base64_decode($matches[1]), 2);
        if (count($credentials) === 2) {
            list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = $credentials;
        }
    }
}

if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] !== $admin_user || $_SERVER['PHP_AUTH_PW'] !== $admin_pass) {
    header('WWW-Authenticate: Basic realm="Diagnostics"');
    header('HTTP/1.0 401 Unauthorized');
    exit('Unauthorized access.');
}

ini_set('display_errors', 1);
error_reporting(E_ALL);

header('Content-Type: text/plain');
echo "--- MaxMind Geo-IP Diagnostics (Manual Mode) ---\n\n";

// --- MANUAL AUTOLOADER ---
spl_autoload_register(function ($class) {
    $prefix = 'MaxMind\\Db\\';
    $base_dir = __DIR__ . '/maxmind-lib/src/MaxMind/Db/';
    
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) return;
    
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    
    if (file_exists($file)) require $file;
});
// -------------------------

$db_path = __DIR__ . '/GeoLite2-Country.mmdb';

// 1. Check Database
if (!file_exists($db_path)) {
    die("[FAIL] Database file NOT FOUND at: $db_path\n");
}
echo "[PASS] Database file found.\n";

// 2. Check Library
if (!class_exists('\MaxMind\Db\Reader')) {
    die("[FAIL] Could not load the manual library. Ensure you uploaded the 'maxmind-lib' folder correctly.\n");
}
echo "[PASS] MaxMind Reader class is loaded manually.\n";

// 3. Test Lookup
try {
    $reader = new \MaxMind\Db\Reader($db_path);
    $test_ip = '8.8.8.8'; 
    $record = $reader->get($test_ip);
    
    if (!empty($record['country']['iso_code'])) {
        echo "[PASS] Successfully resolved IP $test_ip to Country: " . $record['country']['iso_code'] . "\n";
        echo "\nSUCCESS! Your local Geo-IP routing is fully operational.";
    }
    $reader->close();
} catch (Exception $e) {
    echo "[ERROR] " . $e->getMessage() . "\n";
}
?>