<?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);
    $hall_id = 0; if(is_array($input)&&isset($input['id'])){ $hall_id=(int)$input['id']; } elseif(isset($_POST['id'])){ $hall_id=(int)$_POST['id']; }
    if ($hall_id <= 0) { echo json_encode(['status'=>'error','message'=>'ID required']); exit; }

    // Check dependencies
    $dep = $pdo->prepare('SELECT COUNT(*) FROM hall_allocations WHERE hall_id = ?');
    $dep->execute([$hall_id]);
    if ((int)$dep->fetchColumn() > 0) { echo json_encode(['status'=>'error','message'=>'Cannot delete: hall has allocations']); exit; }

    $stmt = $pdo->prepare('SELECT * FROM halls WHERE hall_id = ?');
    $stmt->execute([$hall_id]);
    $before = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$before) { echo json_encode(['status'=>'error','message'=>'Not found']); exit; }

    try { $pdo->prepare('DELETE FROM halls WHERE hall_id = ?')->execute([$hall_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: hall is referenced by other records.']); exit; } throw $e; }
    write_audit_log($pdo, [
        'module'=>'Timetable & Halls','action'=>'delete','entity_table'=>'halls','entity_id'=>$hall_id,
        'before_data'=>$before,'message'=>'Hall deleted'
    ]);
    echo json_encode(['status'=>'success','message'=>'Hall deleted']);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status'=>'error','message'=>'Request failed. Please try again.']);
}
?>


