<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');
try {
    $id=(int)($_POST['id']??0);
    $subject_id=(int)($_POST['subject_id']??0);
    $exam_type=trim($_POST['exam_type']??'');
    $max_marks=(int)($_POST['max_marks']??0);
    $pass_marks=(int)($_POST['pass_marks']??0);
    $min_marks=(int)($_POST['min_marks']??0);
    $errors=[]; if($id<=0)$errors[]='Invalid ID.'; if($subject_id<=0)$errors[]='Subject required.'; if(!in_array($exam_type,['Internal','Semester']))$errors[]='Invalid exam type.'; if($max_marks<=0)$errors[]='Max marks required.'; if($pass_marks<0||$pass_marks>$max_marks)$errors[]='Enter valid pass marks.'; if($min_marks<0||$min_marks>$pass_marks)$errors[]='Enter valid min marks.'; if($errors){ echo json_encode(['status'=>'error','message'=>$errors]); exit; }
    $before=null; try{ $b=$pdo->prepare('SELECT * FROM subject_assessment_settings WHERE setting_id=?'); $b->execute([$id]); $before=$b->fetch(PDO::FETCH_ASSOC);}catch(Throwable $e){}
    $stmt=$pdo->prepare('UPDATE subject_assessment_settings SET subject_id=?, exam_type=?, max_marks=?, pass_marks=?, min_marks=? WHERE setting_id=?');
    $stmt->execute([$subject_id,$exam_type,$max_marks,$pass_marks,$min_marks,$id]);
    write_audit_log($pdo, ['module'=>'Grading System','action'=>'update','entity_table'=>'subject_assessment_settings','entity_id'=>$id,'before_data'=>$before,'after_data'=>compact('subject_id','exam_type','max_marks','pass_marks','min_marks'),'message'=>'Assessment setting updated']);
    echo json_encode(['status'=>'success','message'=>'Assessment setting updated successfully.']);
} catch (Throwable $e){ http_response_code(500); echo json_encode(['status'=>'error','message'=>$e->getMessage()]); }
?>


