<?php

require_once 'db_connection.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'User is not logged in.',
    ]);
    exit();
}

$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,
            classes.class_name AS class
        FROM emails_v
        LEFT JOIN classes ON emails_v.class_id = classes.id
        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'],
            'class' => $user['class'] ?? 'None',
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'User data not found.',
        ]);
    }
} catch (PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while fetching user data.',
    ]);
}
?>
