<?php
require_once 'db_connection.php';

if (isset($_SESSION['user_id']) && isset($_SESSION['user_level'])) {
    $userId = $_SESSION['user_id'];

    try {
        $query = $pdo->prepare("
            SELECT 
                emails_v.id AS user_id,
                emails_v.username,
                emails_v.email,
                emails_v.level AS user_level,
                emails_v.class_id,
                emails_v.theme_id
            FROM emails_v
            WHERE emails_v.id = :userId
        ");
        $query->bindParam(':userId', $userId, PDO::PARAM_INT);
        $query->execute();

        $user = $query->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            echo json_encode([
                'success' => true,
                'user_id' => $user['user_id'],
                'username' => $user['username'],
                'email' => $user['email'],
                'user_level' => $user['user_level'],
                'class_id' => $user['class_id'],
                'theme_id' => $user['theme_id'] ?? 1,
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Lietotāja dati netika atrasti!'
            ]);
        }
    } catch (PDOException $e) {
        error_log("Error fetching user data: " . $e->getMessage());
        echo json_encode([
            'success' => false,
            'message' => 'Notika kļūme kamēr mēģinājām atgriezt datus!'
        ]);
    }
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Lietotājs nav ierakstijies!'
    ]);
}
?>
