<?php

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

$conn = getDBConnection();



// Set header to return JSON

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



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



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

$boundaries_json = $_POST['boundaries'] ?? '[]';



$boundaries = json_decode($boundaries_json, true);



if (empty($boundaries)) {

    $response['message'] = 'No boundaries provided';

    echo json_encode($response);

    $conn->close();

    exit;

}



// Begin transaction

$conn->begin_transaction();



try {

    // First, delete existing boundaries for this class

    $stmt = $conn->prepare("DELETE FROM grade_boundaries WHERE class_name = ?");

    $stmt->bind_param("s", $class_name);

    $stmt->execute();

    $stmt->close();



    // Insert new boundaries

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

    

    foreach ($boundaries as $boundary) {

        $grade = $boundary['grade'];

        $min_score = floatval($boundary['min_score']);

        $max_score = floatval($boundary['max_score']);

        $remark = trim($boundary['remark']);

        

        // Validate min/max

        if ($min_score > $max_score) {

            throw new Exception("Min score cannot be greater than max score for grade $grade");

        }

        

        $stmt->bind_param("ssdds", 

            $class_name, 

            $grade, 

            $min_score, 

            $max_score, 

            $remark

        );

        

        if (!$stmt->execute()) {

            throw new Exception("Error inserting grade $grade: " . $stmt->error);

        }

    }

    

    $stmt->close();

    

    // Commit transaction

    $conn->commit();

    

    $response['success'] = true;

    $response['message'] = 'Grade boundaries saved successfully';

    

} catch (Exception $e) {

    // Rollback transaction on error

    $conn->rollback();

    $response['message'] = 'Error: ' . $e->getMessage();

    error_log('save_grade_boundaries.php error: ' . $e->getMessage());

}



$conn->close();

echo json_encode($response);

exit;