<?php
// Comprehensive diagnostic for user management
session_start();

$diags = [];

// 1. Check DB connection
$diags['db_config_exists'] = file_exists(__DIR__ . '/db_config.php');
if (file_exists(__DIR__ . '/db_config.php')) {
    require_once __DIR__ . '/db_config.php';
    $diags['conn_object'] = is_object($conn ?? null);
    $diags['STORE_PLAINTEXT_PASSWORDS'] = $STORE_PLAINTEXT_PASSWORDS ?? false;
    
    if (isset($conn)) {
        $res = @$conn->query('SELECT COUNT(*) as cnt FROM users');
        if ($res) {
            $row = $res->fetch_assoc();
            $diags['user_count_in_db'] = $row['cnt'];
        }
    }
}

// 2. Check session
$diags['session_user_id'] = $_SESSION['user_id'] ?? null;
$diags['session_is_admin'] = $_SESSION['is_admin'] ?? false;
$diags['session_is_subadmin'] = $_SESSION['is_subadmin'] ?? false;

// 3. Check JSON files
$diags['users_json_exists'] = file_exists(__DIR__ . '/data/users.json');
if (file_exists(__DIR__ . '/data/users.json')) {
    $content = file_get_contents(__DIR__ . '/data/users.json');
    $decoded = json_decode($content, true);
    $diags['users_json_count'] = count($decoded ?? []);
}

$diags['admins_json_exists'] = file_exists(__DIR__ . '/data/admins.json');

// 4. Check API files
$apis = ['api_list_users.php', 'api_add_user.php', 'api_update_user.php'];
foreach ($apis as $api) {
    $path = __DIR__ . '/' . $api;
    $diags[$api . '_size'] = file_exists($path) ? filesize($path) : 'NOT FOUND';
}

// 5. Check JavaScript files
$diags['admin_users_actions_js_size'] = file_exists(__DIR__ . '/admin_users_actions.js') ? filesize(__DIR__ . '/admin_users_actions.js') : 'NOT FOUND';

header('Content-Type: application/json');
echo json_encode($diags, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
?>
