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

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

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

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



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

    $response['message'] = 'Missing required parameters';

    echo json_encode($response);

    $conn->close();

    exit;

}



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

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

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

    echo json_encode($response);

    $conn->close();

    exit;

}



// Check if record exists

$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();



// Prepare value based on field type

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

    $value = trim($value);

    $param_type = "s";

} else {

    $value = floatval($value);

    // Validate numeric range

    if ($value < 0 || $value > 100) {

        $response['message'] = 'Score must be between 0 and 100';

        echo json_encode($response);

        $conn->close();

        exit;

    }

    $param_type = "d";

}



// Begin transaction

$conn->begin_transaction();



try {

    if ($exists) {

        // Update existing record

        $sql = "UPDATE grade_boundaries SET $field = ? WHERE class_name = ? AND grade = ?";

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

        

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

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

        } else {

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

        }

    } else {

        // Insert new record with defaults

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

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

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

        

        // Set defaults based on grade if not provided

        if ($min_score == 0 && $max_score == 0 && $remark == '') {

            switch($grade) {

                case 'A': $min_score = 90; $max_score = 100; $remark = 'EXCELLENT'; break;

                case 'B': $min_score = 80; $max_score = 89; $remark = 'VERY GOOD'; break;

                case 'C': $min_score = 70; $max_score = 79; $remark = 'GOOD'; break;

                case 'D': $min_score = 60; $max_score = 69; $remark = 'SATISFACTORY'; break;

                case 'E': $min_score = 50; $max_score = 59; $remark = 'PASS'; break;

                case 'W': $min_score = 0; $max_score = 49; $remark = 'WEAK'; break;

            }

        }

        

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

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

    }

    

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

        throw new Exception($stmt->error);

    }

    

    // Validate min/max consistency if both fields exist

    if ($field === 'min_score' || $field === 'max_score') {

        // Get the current values

        $check_stmt = $conn->prepare("SELECT min_score, max_score FROM grade_boundaries WHERE class_name = ? AND grade = ?");

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

        $check_stmt->execute();

        $check_result = $check_stmt->get_result();

        

        if ($check_row = $check_result->fetch_assoc()) {

            if ($check_row['min_score'] > $check_row['max_score']) {

                // Revert the change

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

            }

        }

        $check_stmt->close();

    }

    

    $conn->commit();

    $response['success'] = true;

    $response['message'] = 'Grade boundary updated';

    

} catch (Exception $e) {

    $conn->rollback();

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

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

}



$stmt->close();

$conn->close();

echo json_encode($response);

exit;