<?php
// Final verification script - checks all components
header('Content-Type: application/json');
session_start();
ob_clean();

$check = [
    'timestamp' => date('Y-m-d H:i:s'),
    'authenticated' => !empty($_SESSION['user_id']),
    'session_user_id' => $_SESSION['user_id'] ?? null,
    'session_is_admin' => $_SESSION['is_admin'] ?? false,
];

// Load db config
if (file_exists(__DIR__ . '/db_config.php')) {
    require_once __DIR__ . '/db_config.php';
    
    if (isset($conn) && !$conn->connect_error) {
        // Get user count
        $res = $conn->query('SELECT COUNT(*) as cnt FROM users');
        if ($res) {
            $row = $res->fetch_assoc();
            $check['total_users_in_db'] = (int)$row['cnt'];
        }
        
        // Get users list
        $res = $conn->query('SELECT id, username, email, password_hash FROM users LIMIT 3');
        if ($res) {
            $users = [];
            while ($r = $res->fetch_assoc()) {
                $password_len = strlen($r['password_hash']);
                $is_plain = $password_len < 40;  // Plain text is shorter than bcrypt
                $users[] = [
                    'id' => $r['id'],
                    'username' => $r['username'],
                    'email' => $r['email'],
                    'password_type' => $is_plain ? 'PLAIN TEXT' : 'HASHED',
                    'password_length' => $password_len
                ];
            }
            $check['sample_users'] = $users;
        }
        
        // Get admin count
        $res = $conn->query('SELECT COUNT(*) as cnt FROM admins');
        if ($res) {
            $row = $res->fetch_assoc();
            $check['admin_users_in_db'] = (int)$row['cnt'];
        }
        
        $check['db_status'] = 'CONNECTED';
        $check['STORE_PLAINTEXT_PASSWORDS'] = $STORE_PLAINTEXT_PASSWORDS ?? false;
    }
}

// Check API files exist
$check['api_list_users_exists'] = file_exists(__DIR__ . '/api_list_users.php');
$check['api_add_user_exists'] = file_exists(__DIR__ . '/api_add_user.php');
$check['api_update_user_exists'] = file_exists(__DIR__ . '/api_update_user.php');

// Check admin page exists
$check['admin_manage_users_exists'] = file_exists(__DIR__ . '/admin_manage_users.php');

echo json_encode($check, JSON_PRETTY_PRINT);
?>
