<?php
// BULLETPROOF MINIMAL API - Load users from DB with JSON fallback
ob_start();
ob_clean();
header('Content-Type: application/json; charset=utf-8');

$users = [];

// Load database config
$config_file = __DIR__ . '/db_config.php';
if (file_exists($config_file)) {
    include $config_file;
}

// Query database if connected
if (isset($conn) && is_object($conn) && !$conn->connect_error) {
    $query = 'SELECT id, username, email, IFNULL(name,"") as name, phone, age, gender, created_at FROM users ORDER BY id DESC';
    $result = $conn->query($query);
    
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $uid = (int)$row['id'];
            
            // Check admin status
            $admin_result = $conn->query("SELECT id FROM admins WHERE user_id = $uid LIMIT 1");
            $row['is_admin'] = ($admin_result && $admin_result->num_rows > 0);
            
            // Check subadmin status  
            $subadmin_result = $conn->query("SELECT user_id FROM subadmins WHERE user_id = $uid LIMIT 1");
            $row['is_subadmin'] = ($subadmin_result && $subadmin_result->num_rows > 0);
            
            $users[] = $row;
        }
    }
}

// If no users from DB, try JSON fallback
if (count($users) == 0) {
    $json_file = __DIR__ . '/data/users.json';
    if (file_exists($json_file)) {
        $json_data = @file_get_contents($json_file);
        if ($json_data) {
            $decoded = @json_decode($json_data, true);
            if (is_array($decoded)) {
                $users = $decoded;
            }
        }
    }
}

// Output result
$output = [
    'success' => count($users) > 0,
    'users' => $users,
    'count' => count($users)
];

echo json_encode($output, JSON_UNESCAPED_UNICODE);
exit;
?>
