<?php

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

$conn = getDBConnection();



$response = ['success' => false, 'message' => ''];



$id = intval($_POST['id'] ?? 0);

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

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



if (!$id || !$field) {

    $response['message'] = 'Invalid parameters';

    echo json_encode($response);

    exit;

}



// Sanitize field name (allow only specific fields)

$allowed_fields = ['class_score_percent', 'exam_score_percent', 'max_class_score', 'max_exam_score', 'is_compulsory', 'display_order'];

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

    $response['message'] = 'Invalid field';

    echo json_encode($response);

    exit;

}



// Prepare the update query

$query = "UPDATE class_subjects SET $field = ? WHERE id = ?";

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



// Bind parameters based on field type

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

    $stmt->bind_param("si", $value, $id);

} else {

    // Numeric fields

    $value = floatval($value);

    $stmt->bind_param("di", $value, $id);

}



if ($stmt->execute()) {

    $response['success'] = true;

    $response['message'] = 'Updated successfully';

} else {

    $response['message'] = 'Database error: ' . $stmt->error;

}



$stmt->close();

$conn->close();



echo json_encode($response);