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

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once 'config.php';

// Debug version of getUserLevelFromToken
function getUserLevelFromTokenDebug($conn, $token) {
    if (!$token) {
        return ['level' => 'guest', 'debug' => 'No token provided'];
    }
    
    try {
        $stmt = $conn->prepare('SELECT user_level FROM users WHERE session_token = ?');
        $stmt->execute([$token]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($row) {
            return ['level' => $row['user_level'], 'debug' => 'User found'];
        } else {
            return ['level' => 'guest', 'debug' => 'Token not found in database'];
        }
    } catch (PDOException $e) {
        return ['level' => 'guest', 'debug' => 'Database error: ' . $e->getMessage()];
    }
}

// Simple debug endpoint
try {
    $conn = getDBConnection();
    
    if (!$conn) {
        echo json_encode(['success' => false, 'message' => 'Database connection failed']);
        exit;
    }
    
    $token = $_GET['token'] ?? '';
    $result = getUserLevelFromTokenDebug($conn, $token);
    
    echo json_encode([
        'success' => true,
        'token_provided' => !empty($token),
        'token_length' => strlen($token),
        'user_level' => $result['level'],
        'debug_info' => $result['debug'],
        'get_params' => $_GET
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine()
    ]);
}
?>