<?php
require_once 'db_connection.php';

header('Content-Type: application/json');

try {
    $level = $_GET['level'];
    $classId = isset($_GET['class_id']) ? $_GET['class_id'] : null;

    if (!$level) {
        echo json_encode(['success' => false, 'message' => 'Level parameter is required']);
        exit;
    }

    $query = "SELECT id, username, level FROM emails_v WHERE level = ?";
    $params = [$level];

    if ($classId) {
        $query .= " AND class_id = ?";
        $params[] = $classId;
    }

    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['success' => true, 'users' => $users]);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Error fetching users: ' . $e->getMessage()]);
}
