<?php
include 'db_connection.php'; // Include the PDO connection file

// Check if request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit();
}

// Retrieve and validate input data
$teacher_id = isset($_POST['teacher_id']) ? (int)$_POST['teacher_id'] : null;
$student_id = isset($_POST['student_id']) ? (int)$_POST['student_id'] : null;
$class_id = isset($_POST['class_id']) ? (int)$_POST['class_id'] : null;
$test_id = isset($_POST['test_id']) ? (int)$_POST['test_id'] : null;
$subject_id = isset($_POST['subject_id']) ? (int)$_POST['subject_id'] : null;
$grade = isset($_POST['grade']) ? trim($_POST['grade']) : null;
$date = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');

if (!$teacher_id || !$student_id || !$test_id || !$subject_id || !$grade) {
    echo json_encode(['success' => false, 'message' => 'Nav aizpildīti visi lauki!']);
    exit();
}

try {
    $checkStmt = $pdo->prepare("
        SELECT COUNT(*) as count
        FROM grades
        WHERE student_id = :student_id AND test_id = :test_id AND subject_id = :subject_id
    ");
    $checkStmt->bindParam(':student_id', $student_id, PDO::PARAM_INT);
    $checkStmt->bindParam(':test_id', $test_id, PDO::PARAM_INT);
    $checkStmt->bindParam(':subject_id', $subject_id, PDO::PARAM_INT);
    $checkStmt->execute();
    $result = $checkStmt->fetch(PDO::FETCH_ASSOC);

    if ($result['count'] > 0) {
        echo json_encode(['success' => false, 'message' => 'Skolniekam jau ir vērtējums norādītajā pārbaudes darbā!']);
        exit();
    }

    $stmt = $pdo->prepare("
        INSERT INTO grades (teacher_id, student_id, class_id, test_id, subject_id, grade, date)
        VALUES (:teacher_id, :student_id, :class_id, :test_id, :subject_id, :grade, :date)
    ");

    $stmt->bindParam(':teacher_id', $teacher_id, PDO::PARAM_INT);
    $stmt->bindParam(':student_id', $student_id, PDO::PARAM_INT);
    $stmt->bindParam(':class_id', $class_id, PDO::PARAM_INT); // Optional
    $stmt->bindParam(':test_id', $test_id, PDO::PARAM_INT);
    $stmt->bindParam(':subject_id', $subject_id, PDO::PARAM_INT);
    $stmt->bindParam(':grade', $grade, PDO::PARAM_STR);
    $stmt->bindParam(':date', $date, PDO::PARAM_STR);

    $stmt->execute();

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