<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');
try {
    $id = (int)($_POST['id'] ?? 0);
    $system_name = trim($_POST['system_name'] ?? '');
    $course_id = (int)($_POST['course_id'] ?? 0);
    $is_active = isset($_POST['is_active']) ? (int)($_POST['is_active'] ? 1 : 0) : 1;
    $errors = [];
    if ($id<=0) { $errors[] = 'Invalid ID.'; }
    if ($system_name === '') { $errors[] = 'System Name is required.'; }
    if ($course_id <= 0) { $errors[] = 'Course is required.'; }
    if ($errors) { echo json_encode(['status'=>'error','message'=>$errors]); exit; }

    $before=null; try{ $b=$pdo->prepare('SELECT * FROM grading_systems WHERE grading_system_id=?'); $b->execute([$id]); $before=$b->fetch(PDO::FETCH_ASSOC);}catch(Throwable $e){}

    $stmt = $pdo->prepare('UPDATE grading_systems SET system_name=?, course_id=?, is_active=? WHERE grading_system_id=?');
    $stmt->execute([$system_name,$course_id,$is_active,$id]);
    write_audit_log($pdo, ['module'=>'Grading System','action'=>'update','entity_table'=>'grading_systems','entity_id'=>$id,'before_data'=>$before,'after_data'=>compact('system_name','course_id','is_active'),'message'=>'Grading system updated']);
    echo json_encode(['status'=>'success','message'=>'Grading system updated successfully.']);
} catch (Throwable $e){ http_response_code(500); echo json_encode(['status'=>'error','message'=>$e->getMessage()]); }
?>


