<?php
// Advanced diagnostic - shows auth state and API response
header('Content-Type: application/json');
session_start();

$debug = [
    'timestamp' => date('Y-m-d H:i:s'),
    'session' => [
        'user_id' => $_SESSION['user_id'] ?? null,
        'is_admin' => $_SESSION['is_admin'] ?? null,
        'is_subadmin' => $_SESSION['is_subadmin'] ?? null,
        'username' => $_SESSION['username'] ?? null,
    ],
];

// Check database
if (file_exists(__DIR__ . '/db_config.php')) {
    require_once __DIR__ . '/db_config.php';
    
    if (isset($conn)) {
        // Check connection
        $debug['db'] = [
            'connected' => !$conn->connect_error,
            'error' => $conn->connect_error ?? null,
        ];
        
        // Try to fetch users
        $result = @$conn->query('SELECT id, username, email FROM users ORDER BY id DESC LIMIT 5');
        if ($result) {
            $users = [];
            while ($row = $result->fetch_assoc()) {
                $users[] = $row;
            }
            $debug['users_from_db'] = $users;
            $debug['user_count'] = count($users);
        } else {
            $debug['db_query_error'] = $conn->error;
        }
        
        // Check admins table
        $res = @$conn->query('SELECT user_id FROM admins LIMIT 5');
        if ($res && $res->num_rows > 0) {
            $admin_ids = [];
            while ($row = $res->fetch_assoc()) {
                $admin_ids[] = $row['user_id'];
            }
            $debug['admin_user_ids'] = $admin_ids;
        }
    }
}

// Test api_list_users response
$test_url = 'http://' . $_SERVER['HTTP_HOST'] . '/emporio/api_list_users.php';
$context = stream_context_create();
$api_response = @file_get_contents($test_url, false, $context);
if ($api_response) {
    $debug['api_list_users_response'] = json_decode($api_response, true);
}

echo json_encode($debug, JSON_PRETTY_PRINT);
?>
