<?php

require_once '../../../config.php';

$conn = getDBConnection();



$class_name = $_POST['class_name'] ?? 'ALL';

$grade = $_POST['grade'] ?? '';

$field = $_POST['field'] ?? '';

$value = $_POST['value'] ?? '';



if (empty($grade) || empty($field)) {

    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);

    $conn->close();

    exit;

}



// Validate field

$allowed_fields = ['min_score', 'max_score', 'remark'];

if (!in_array($field, $allowed_fields)) {

    echo json_encode(['success' => false, 'message' => 'Invalid field']);

    $conn->close();

    exit;

}



// Check if boundary exists for this class and grade

$stmt = $conn->prepare("SELECT id FROM grade_boundaries WHERE class_name = ? AND grade = ?");

$stmt->bind_param("ss", $class_name, $grade);

$stmt->execute();

$result = $stmt->get_result();

$exists = $result->num_rows > 0;

$stmt->close();



if ($field === 'remark') {

    // Remark is a string — trim only; HTML-encoding done at output time

    $value = trim((string) $value);

} else {

    // min_score and max_score are floats

    $value = floatval($value);

}



if ($exists) {

    // Update existing

    $stmt = $conn->prepare("UPDATE grade_boundaries SET $field = ? WHERE class_name = ? AND grade = ?");

    $bindType = ($field === 'remark') ? 'sss' : 'dss';

    $stmt->bind_param($bindType, $value, $class_name, $grade);

} else {

    // Insert new - we need default values for other fields

    $min_score = ($field === 'min_score') ? $value : 0;

    $max_score = ($field === 'max_score') ? $value : 0;

    $remark = ($field === 'remark') ? $value : '';

    

    $stmt = $conn->prepare("INSERT INTO grade_boundaries (class_name, grade, min_score, max_score, remark) VALUES (?, ?, ?, ?, ?)");

    $stmt->bind_param("sddss", $class_name, $grade, $min_score, $max_score, $remark);

}



if ($stmt->execute()) {

    echo json_encode(['success' => true, 'message' => 'Grade boundary updated']);

} else {

    echo json_encode(['success' => false, 'message' => 'Error updating grade boundary: ' . $conn->error]);

}



$stmt->close();

$conn->close();

