<?php
include('db_connection.php');

$user_level = isset($_GET['user_level']) ? (int)$_GET['user_level'] : null;
$teacher_id = isset($_GET['teacher_id']) ? (int)$_GET['teacher_id'] : null;
$student_id = isset($_GET['student_id']) ? (int)$_GET['student_id'] : null;
$class_id = isset($_GET['class_id']) ? trim($_GET['class_id']) : null;
$test_id = isset($_GET['test_id']) ? trim($_GET['test_id']) : null;
$subject_id = isset($_GET['subject_id']) ? trim($_GET['subject_id']) : null;

if ($user_level === null || ($user_level !== 3 && $teacher_id === null && $student_id === null)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient parameters.']);
    exit();
}

try {
    $query = "
        SELECT 
            g.id,
            g.grade,
            s.name AS subject_name,
            t.name AS test_name,
            e.username AS student_name,
            g.date
        FROM grades g
        JOIN subjects s ON g.subject_id = s.id
        JOIN tests t ON g.test_id = t.id
        JOIN emails_v e ON g.student_id = e.id
    ";

    $conditions = [];

    if ($user_level === 2 && $teacher_id !== null) {
        $conditions[] = "g.teacher_id = :teacher_id";
    } elseif ($user_level === 1 && $student_id !== null) {
        $conditions[] = "g.student_id = :student_id";
    }
    if (!empty($class_id)) {
        $conditions[] = "g.class_id = :class_id";
    }
    if (!empty($test_id)) {
        $conditions[] = "g.test_id = :test_id";
    }
    if (!empty($subject_id)) {
        $conditions[] = "g.subject_id = :subject_id";
    }

    if (!empty($conditions)) {
        $query .= " WHERE " . implode(" AND ", $conditions);
    }
    $query .= " ORDER BY g.date DESC";

    $stmt = $pdo->prepare($query);

    if ($user_level === 2 && $teacher_id !== null) {
        $stmt->bindParam(':teacher_id', $teacher_id, PDO::PARAM_INT);
    }
    if ($user_level === 1 && $student_id !== null) {
        $stmt->bindParam(':student_id', $student_id, PDO::PARAM_INT);
    }
    if (!empty($class_id)) {
        $stmt->bindParam(':class_id', $class_id, PDO::PARAM_INT);
    }
    if (!empty($test_id)) {
        $stmt->bindParam(':test_id', $test_id, PDO::PARAM_INT);
    }
    if (!empty($subject_id)) {
        $stmt->bindParam(':subject_id', $subject_id, PDO::PARAM_INT);
    }

    $stmt->execute();
    $grades = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['success' => true, 'grades' => $grades]);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
