<?php
// FIX: Protected script so attackers cannot insert dummy data
$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.');
}

require_once 'fingerprint_wrapper.php';

header('Content-Type: text/plain');
echo "--- Database Connection Test ---\n";

$pdo = get_db_connection();

if ($pdo) {
    echo "SUCCESS: Connected to the database successfully.\n";
    
    try {
        $stmt = $pdo->query("SHOW TABLES LIKE 'traffic_logs'");
        if ($stmt->rowCount() > 0) {
            echo "SUCCESS: Table 'traffic_logs' exists.\n";
        } else {
            echo "ERROR: Table 'traffic_logs' was NOT found.\n";
        }
        
        echo "Attempting test log insertion...\n";
        log_traffic('safe');
        echo "SUCCESS: Test data inserted into 'traffic_logs'.\n";
        
    } catch (Exception $e) {
        echo "QUERY ERROR: " . $e->getMessage() . "\n";
    }
} else {
    echo "FAILURE: Could not connect to the database.\n";
    echo "Check your \$config in fingerprint_wrapper.php.\n";
    
    try {
        $dsn = "mysql:host={$config['db_host']};dbname={$config['db_name']}";
        new PDO($dsn, $config['db_user'], $config['db_pass']);
    } catch (PDOException $e) {
        echo "\nRAW ERROR MESSAGE: " . $e->getMessage();
    }
}
?>