<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');
try { 
    $raw=file_get_contents('php://input'); $input=json_decode($raw,true); $id=0; 
    if(is_array($input)&&isset($input['id'])){ $id=(int)$input['id']; } elseif(isset($_POST['id'])){ $id=(int)$_POST['id']; }
    if($id<=0){ echo json_encode(['status'=>'error','message'=>'Invalid ID.']); exit; }
    $before=null; try{ $b=$pdo->prepare('SELECT * FROM grades WHERE grade_id=?'); $b->execute([$id]); $before=$b->fetch(PDO::FETCH_ASSOC);}catch(Throwable $e){}
    if(!$before){ http_response_code(404); echo json_encode(['status'=>'error','message'=>'Grade not found.']); exit; }

    // Attempt delete with dependency handling
    try{ $stmt=$pdo->prepare('DELETE FROM grades WHERE grade_id=?'); $stmt->execute([$id]); }
    catch(PDOException $e){ $info=$e->errorInfo??null; if(is_array($info)&&isset($info[1])&&(int)$info[1]===1451){ http_response_code(409); echo json_encode(['status'=>'error','message'=>'Cannot delete: grade is referenced by other records.']); exit; } throw $e; }

    write_audit_log($pdo, ['module'=>'Grading System','action'=>'delete','entity_table'=>'grades','entity_id'=>$id,'before_data'=>$before,'message'=>'Grade deleted']); 
    echo json_encode(['status'=>'success','message'=>'Grade deleted successfully.']); 
} catch (Throwable $e){ http_response_code(500); echo json_encode(['status'=>'error','message'=>'Request failed. Please try again.']); }
?>


