<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');

try {
    $hall_id = (int)($_POST['id'] ?? 0);
    $college_id = (int)($_POST['college_id'] ?? 0);
    $hall_name = trim($_POST['hall_name'] ?? '');
    $block_name = trim($_POST['block_name'] ?? '');
    $capacity = (int)($_POST['capacity'] ?? 0);
    if ($hall_id <= 0) { echo json_encode(['status'=>'error','message'=>'ID required']); 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; }

    $updates = [];$params=[];
    if ($college_id > 0) { $updates[]='college_id=?'; $params[]=$college_id; }
    if ($hall_name !== '') { $updates[]='hall_name=?'; $params[]=$hall_name; }
    if ($block_name !== '') { $updates[]='block_name=?'; $params[]=$block_name; }
    if ($capacity > 0) { $updates[]='capacity=?'; $params[]=$capacity; }
    if (!$updates) { echo json_encode(['status'=>'error','message'=>'No fields to update']); exit; }
    $params[]=$hall_id;
    $sql='UPDATE halls SET '.implode(', ',$updates).' WHERE hall_id = ?';
    $pdo->prepare($sql)->execute($params);

    $stmt = $pdo->prepare('SELECT * FROM halls WHERE hall_id = ?');
    $stmt->execute([$hall_id]);
    $after = $stmt->fetch(PDO::FETCH_ASSOC);
    write_audit_log($pdo, [
        'module'=>'Timetable & Halls','action'=>'update','entity_table'=>'halls','entity_id'=>$hall_id,
        'before_data'=>$before,'after_data'=>$after,'message'=>'Hall updated'
    ]);
    echo json_encode(['status'=>'success','message'=>'Hall updated']);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>



