<?php
// CLI/api/2.0/username_check.php
// This file checks if a username exists in the system

// Prevent direct web access to this script
if (!isset($_SERVER['HTTP_USER_AGENT']) || strpos($_SERVER['HTTP_USER_AGENT'], 'CCLS-CLI') === false) {
    header('HTTP/1.0 403 Forbidden');
    echo json_encode(['error' => 'Access denied']);
    exit;
}

// Initialize response
$response = [
    'exists' => false,
    'error' => null
];

// Check if username was provided
if (!isset($_POST['username']) || empty($_POST['username'])) {
    $response['error'] = 'Username is required';
    echo json_encode($response);
    exit;
}

$username = trim($_POST['username']);

// Check if username exists - Updated path for v2.0
$user_files = glob("../../../users/*.json");
$user_found = false;

foreach ($user_files as $file) {
    $user_data = json_decode(file_get_contents($file), true);
    
    if ($user_data['username'] === $username) {
        $user_found = true;
        break;
    }
}

$response['exists'] = $user_found;

// Return JSON response
header('Content-Type: application/json');
echo json_encode($response);
?>