<?php
// get_user_profile.php
// Autors: Kārlis Mālnieks
require_once 'db_connection.php'; // Pievienojam datubāzes savienojumu

// Pārbaudām, vai lietotājs ir pieslēdzies
if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'User is not logged in.',
    ]);
    exit();
}

// Iegūstam lietotāja ID no sesijas
$userId = $_SESSION['user_id'];

try {
    // SQL vaicājums, lai iegūtu lietotāja datus
    $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();

    // Iegūstam rezultātus
    $user = $query->fetch(PDO::FETCH_ASSOC);

    // Atgriežam datus JSON formātā
    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) {
    // Kļūdu apstrāde
    error_log("Database error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'An error occurred while fetching user data.',
    ]);
}
?>
