<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
header('Content-Type: application/json');

try {
    require_once '../db.php';

    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['authenticated' => false]);
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT u.id, u.username, u.email, u.avatar_url, u.dark_mode, u.dyslexia_mode, u.theme_color, s.level, s.current_xp, s.health_points, s.companion_state 
        FROM users u 
        LEFT JOIN user_stats s ON u.id = s.user_id 
        WHERE u.id = :id
    ");
    $stmt->execute(['id' => $_SESSION['user_id']]);
    $user = $stmt->fetch();

    if ($user) {
        echo json_encode([
            'authenticated' => true,
            'user' => [
                'id' => (int)$user['id'],
                'username' => $user['username'],
                'email' => $user['email'],
                'avatar' => $user['avatar_url'],
                'dark_mode' => (int)($user['dark_mode'] ?? 0),
                'dyslexia_mode' => (int)($user['dyslexia_mode'] ?? 0),
                'theme_color' => $user['theme_color'] ?? 'indigo',
                'stats' => [
                    'level' => (int)($user['level'] ?? 1),
                    'current_xp' => (int)($user['current_xp'] ?? 0),
                    'health_points' => (int)($user['health_points'] ?? 100),
                    'companion_state' => $user['companion_state'] ?? 'happy'
                ]
            ]
        ]);
    } else {
        echo json_encode(['authenticated' => false]);
    }
} catch (Throwable $e) {
    echo json_encode(['authenticated' => false, 'error' => $e->getMessage()]);
}
?>