<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');

try {
    $id = (int)($_POST['hall_setting_id'] ?? 0);
    if ($id <= 0) { echo json_encode(['status'=>'error','message'=>'hall_setting_id is required']); exit; }

    $stmtB = $pdo->prepare('SELECT * FROM hall_settings WHERE hall_setting_id=?');
    $stmtB->execute([$id]);
    $before = $stmtB->fetch(PDO::FETCH_ASSOC);
    if (!$before) { echo json_encode(['status'=>'error','message'=>'Setting not found']); exit; }

    $fields = [
        'rows_count','columns_count','seating_method','bench_capacity','max_students','row_labeling','internal_invigilators_required','external_invigilators_required','aisle_every_n_cols','aisle_every_n_rows','layout_image_path','layout_seat_points'
    ];
    $sets=[]; $vals=[];
    $input = $_POST;
    // Auto-calc max_students if not provided but derivable
    if ((!isset($input['max_students']) || $input['max_students'] === '')
        && isset($input['rows_count']) && isset($input['columns_count']) && isset($input['bench_capacity'])
        && $input['rows_count'] !== '' && $input['columns_count'] !== '' && $input['bench_capacity'] !== '') {
        $input['max_students'] = (int)$input['rows_count'] * (int)$input['columns_count'] * (int)$input['bench_capacity'];
    }
    foreach ($fields as $f) {
        if (array_key_exists($f, $input)) { $sets[] = "$f = ?"; $vals[] = $input[$f]; }
    }
    if (!$sets) { echo json_encode(['status'=>'error','message'=>'No fields to update']); exit; }
    $vals[] = $id;
    $pdo->prepare('UPDATE hall_settings SET '.implode(',', $sets).' WHERE hall_setting_id=?')->execute($vals);

    $after = $pdo->prepare('SELECT * FROM hall_settings WHERE hall_setting_id=?');
    $after->execute([$id]);
    $afterRow = $after->fetch(PDO::FETCH_ASSOC);
    write_audit_log($pdo, ['module'=>'Hall Settings','action'=>'update','entity_table'=>'hall_settings','entity_id'=>$id,'before_data'=>$before,'after_data'=>$afterRow]);
    echo json_encode(['status'=>'success','message'=>'Hall setting updated']);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>


