<?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 staff WHERE staff_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'=>'Staff not found.']); exit; }

    try{ $stmt=$pdo->prepare('DELETE FROM staff WHERE staff_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: staff is referenced by related records.']); exit; } throw $e; }

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


