<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');

try {
    // Ensure new columns exist (idempotent)
    try { $pdo->query("SELECT aisle_every_n_cols, aisle_every_n_rows FROM hall_settings LIMIT 1"); }
    catch (Throwable $e) {
        try {
            $pdo->exec("ALTER TABLE hall_settings ADD COLUMN aisle_every_n_cols INT NULL DEFAULT 0 AFTER external_invigilators_required");
        } catch (Throwable $e2) {}
        try {
            $pdo->exec("ALTER TABLE hall_settings ADD COLUMN aisle_every_n_rows INT NULL DEFAULT 0 AFTER aisle_every_n_cols");
        } catch (Throwable $e3) {}
    }
    $hall_id = (int)($_POST['hall_id'] ?? 0);
    $rows_count = (int)($_POST['rows_count'] ?? 0);
    $columns_count = (int)($_POST['columns_count'] ?? 0);
    $seating_method = trim($_POST['seating_method'] ?? 'Parallel');
    $bench_capacity = isset($_POST['bench_capacity']) && $_POST['bench_capacity'] !== '' ? (int)$_POST['bench_capacity'] : null;
    $max_students = isset($_POST['max_students']) && $_POST['max_students'] !== '' ? (int)$_POST['max_students'] : null;
    $row_labeling = trim($_POST['row_labeling'] ?? 'Numeric');
    $internal_invigilators_required = (int)($_POST['internal_invigilators_required'] ?? 1);
    $external_invigilators_required = (int)($_POST['external_invigilators_required'] ?? 0);
    $aisle_every_n_cols = isset($_POST['aisle_every_n_cols']) && $_POST['aisle_every_n_cols']!=='' ? (int)$_POST['aisle_every_n_cols'] : 0;
    $aisle_every_n_rows = isset($_POST['aisle_every_n_rows']) && $_POST['aisle_every_n_rows']!=='' ? (int)$_POST['aisle_every_n_rows'] : 0;

    if ($hall_id <= 0 || $rows_count <= 0 || $columns_count <= 0) {
        echo json_encode(['status'=>'error','message'=>'hall_id, rows_count, columns_count are required']);
        exit;
    }

    if ($max_students === null && $bench_capacity !== null && $rows_count > 0 && $columns_count > 0) {
        $max_students = $rows_count * $columns_count * $bench_capacity;
    }
    $stmt = $pdo->prepare('INSERT INTO hall_settings (hall_id, 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) VALUES (?,?,?,?,?,?,?,?,?,?,?)');
    $stmt->execute([$hall_id,$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]);
    $id = (int)$pdo->lastInsertId();
    write_audit_log($pdo, ['module'=>'Hall Settings','action'=>'create','entity_table'=>'hall_settings','entity_id'=>$id,'after_data'=>$_POST]);
    echo json_encode(['status'=>'success','message'=>'Hall setting created','id'=>$id]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>


