<?php
// DIAGNOSTIC: Shows exactly what api_list_users.php is returning and why
header('Content-Type: application/json');
session_start();

$debug = [
    'timestamp' => date('Y-m-d H:i:s'),
    'session_check' => [
        'has_user_id' => isset($_SESSION['user_id']),
        'user_id_value' => $_SESSION['user_id'] ?? null,
    ]
];

// Test 1: Direct database query
if (file_exists(__DIR__ . '/db_config.php')) {
    require_once __DIR__ . '/db_config.php';
    
    if (isset($conn)) {
        $debug['conn_check'] = [
            'is_object' => is_object($conn),
            'has_query_method' => method_exists($conn, 'query'),
            'connect_error' => $conn->connect_error ?? null,
        ];
        
        // Try the exact query from api_list_users.php
        $query = 'SELECT id, username, email, IFNULL(name,\'\') as name, phone, age, gender, created_at FROM users ORDER BY id DESC';
        $debug['sql_query'] = $query;
        
        $result = @$conn->query($query);
        
        if ($result === false) {
            $debug['query_error'] = $conn->error;
        } else {
            $debug['query_success'] = true;
            $debug['num_rows'] = $result->num_rows;
            
            // Fetch and show users
            $users = [];
            while ($row = $result->fetch_assoc()) {
                $users[] = [
                    'id' => $row['id'],
                    'username' => $row['username'],
                    'email' => $row['email'],
                ];
            }
            $debug['fetched_users'] = $users;
        }
    } else {
        $debug['conn_error'] = '$conn is not set';
    }
}

// Test 2: What api_list_users.php actually returns
$api_url = 'http://' . $_SERVER['HTTP_HOST'] . '/emporio/api_list_users.php';
$api_response = @file_get_contents($api_url);
if ($api_response) {
    $debug['api_list_users_response'] = json_decode($api_response, true);
} else {
    $debug['api_call_failed'] = true;
}

echo json_encode($debug, JSON_PRETTY_PRINT);
?>
