<?php
// ════════════════════════════════════════════════════════
// USER MANAGEMENT API - DEBUG VERSION
// ════════════════════════════════════════════════════════

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Debug: Check if files exist
$debug = [
    'step' => 1,
    'message' => 'Starting debug',
    'file_checks' => [
        'config/db.php exists' => file_exists(__DIR__ . '/config/db.php'),
        'config/helpers.php exists' => file_exists(__DIR__ . '/config/helpers.php'),
    ],
    'current_dir' => __DIR__,
    'request_method' => $_SERVER['REQUEST_METHOD'],
    'request_uri' => $_SERVER['REQUEST_URI'],
];

// Try to require files
try {
    require_once __DIR__ . '/config/db.php';
    $debug['step'] = 2;
    $debug['message'] = 'db.php loaded successfully';
} catch (Exception $e) {
    echo json_encode([
        'error' => 'Failed to load db.php',
        'message' => $e->getMessage(),
        'debug' => $debug
    ]);
    exit();
}

try {
    require_once __DIR__ . '/config/helpers.php';
    $debug['step'] = 3;
    $debug['message'] = 'helpers.php loaded successfully';
} catch (Exception $e) {
    echo json_encode([
        'error' => 'Failed to load helpers.php',
        'message' => $e->getMessage(),
        'debug' => $debug
    ]);
    exit();
}

// Check if verifyToken function exists
if (!function_exists('verifyToken')) {
    echo json_encode([
        'error' => 'verifyToken function not found',
        'debug' => $debug,
        'available_functions' => get_defined_functions()['user']
    ]);
    exit();
}

$debug['step'] = 4;
$debug['message'] = 'All files loaded, verifyToken exists';

// Get authorization token
$headers = getallheaders();
$token = isset($headers['Authorization']) ? str_replace('Bearer ', '', $headers['Authorization']) : null;

$debug['has_token'] = !empty($token);
$debug['token_preview'] = $token ? substr($token, 0, 20) . '...' : 'none';

if (!$token) {
    http_response_code(401);
    echo json_encode([
        'error' => 'Unauthorized - No token provided',
        'debug' => $debug
    ]);
    exit();
}

// Verify token and get current user
try {
    $currentUser = verifyToken($token);
    $debug['step'] = 5;
    $debug['message'] = 'Token verified';
    $debug['current_user'] = $currentUser;
} catch (Exception $e) {
    echo json_encode([
        'error' => 'Token verification failed',
        'message' => $e->getMessage(),
        'debug' => $debug
    ]);
    exit();
}

if (!$currentUser) {
    http_response_code(401);
    echo json_encode([
        'error' => 'Unauthorized - Invalid token',
        'debug' => $debug
    ]);
    exit();
}

// Check user role
$debug['step'] = 6;
$debug['user_role'] = $currentUser['role'];

if (!in_array($currentUser['role'], ['super_admin', 'admin'])) {
    http_response_code(403);
    echo json_encode([
        'error' => 'Forbidden - Admin access required',
        'debug' => $debug
    ]);
    exit();
}

// Try to query database
try {
    $debug['step'] = 7;
    $debug['message'] = 'Attempting database query';
    
    $stmt = $pdo->query("
        SELECT id, name, email, phone, role, is_active, created_at 
        FROM users 
        ORDER BY created_at DESC
    ");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $debug['step'] = 8;
    $debug['message'] = 'Query successful';
    $debug['user_count'] = count($users);
    
    echo json_encode([
        'success' => true,
        'users' => $users,
        'debug' => $debug
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'error' => 'Database query failed',
        'message' => $e->getMessage(),
        'debug' => $debug
    ]);
}
?>
