<?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';



// Default boundaries

$default_boundaries = [

    ['grade' => 'A', 'min_score' => 90, 'max_score' => 100, 'remark' => 'EXCELLENT'],

    ['grade' => 'B', 'min_score' => 80, 'max_score' => 89, 'remark' => 'VERY GOOD'],

    ['grade' => 'C', 'min_score' => 70, 'max_score' => 79, 'remark' => 'GOOD'],

    ['grade' => 'D', 'min_score' => 60, 'max_score' => 69, 'remark' => 'SATISFACTORY'],

    ['grade' => 'E', 'min_score' => 50, 'max_score' => 59, 'remark' => 'PASS'],

    ['grade' => 'W', 'min_score' => 0, 'max_score' => 49, 'remark' => 'WEAK']

];



// Begin transaction

$conn->begin_transaction();



try {

    // 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 default boundaries

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

    

    foreach ($default_boundaries as $boundary) {

        $stmt->bind_param("ssdds", 

            $class_name,

            $boundary['grade'],

            $boundary['min_score'],

            $boundary['max_score'],

            $boundary['remark']

        );

        

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

            throw new Exception("Error inserting default grade " . $boundary['grade'] . ": " . $stmt->error);

        }

    }

    

    $stmt->close();

    

    // Commit transaction

    $conn->commit();

    

    $response['success'] = true;

    $response['message'] = 'Grade boundaries reset to defaults';

    

} catch (Exception $e) {

    // Rollback transaction on error

    $conn->rollback();

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

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

}



$conn->close();

echo json_encode($response);

exit;