<?php
session_start();
require_once '../config/database.php';

// Auth check
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$req = ($_SERVER['REQUEST_METHOD']==='POST') ? $_POST : $_GET;

// Inputs
$exam_id = isset($req['exam_id']) ? trim($req['exam_id']) : '';
$subject_id = isset($req['subject_id']) ? trim($req['subject_id']) : '';
$room_number = isset($req['room_number']) ? trim($req['room_number']) : 'Room-1';
$rows = isset($req['rows']) ? max(1, (int)$req['rows']) : 6;
$cols = isset($req['cols']) ? max(1, (int)$req['cols']) : 6;
$template = isset($req['template']) ? $req['template'] : 'all_two';
$first_n_rows_one = isset($req['first_n_rows_one']) ? max(0, (int)$req['first_n_rows_one']) : 0;
$order_mode = isset($req['order_mode']) ? $req['order_mode'] : 'roll'; // roll|name|random
$seat_format = isset($req['seat_format']) ? $req['seat_format'] : 'seq'; // seq|rowcol|benchpos
$assign_model = isset($req['assign_model']) ? $req['assign_model'] : 'row'; // row|column|zigzag|diagonal
$do_save = isset($req['save_seats']);
$do_load = isset($req['load_plan']);
$auto_split = isset($req['auto_split']) ? true : false; // rule-based auto-split by roll ranges
$room_rules = isset($req['room_rules']) ? trim($req['room_rules']) : '';
$subject_roll_rules = isset($req['subject_roll_rules']) ? trim($req['subject_roll_rules']) : '';
$use_visual_layout = isset($req['use_visual_layout']); // Apply current visual grid to all rooms

$allowed_templates = ['all_two','all_one','alt_cols','alt_rows','checker','front_one_back_two','custom'];
$allowed_models = ['row','column','zigzag','diagonal'];

// Session key for room-wise roll upload map (independent of exam/subject if not selected)
$roll_map_session_key = ($exam_id && $subject_id) ? ('room_roll_map_'.($exam_id).'_'.($subject_id)) : 'room_roll_map_global';
$room_roll_map = (isset($_SESSION[$roll_map_session_key]) && is_array($_SESSION[$roll_map_session_key])) ? $_SESSION[$roll_map_session_key] : [];

// Handle room-wise roll upload/clear
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['clear_rolls']) && $roll_map_session_key) {
        unset($_SESSION[$roll_map_session_key]);
        $room_roll_map = [];
        $info_message = 'Room-wise roll mapping cleared.';
    }
    if (isset($_POST['upload_rolls']) && isset($_FILES['rolls_file']) && $_FILES['rolls_file']['error'] === UPLOAD_ERR_OK) {
        $tmp = $_FILES['rolls_file']['tmp_name'];
        $size = $_FILES['rolls_file']['size'];
        if ($size > 0 && $size < 2*1024*1024) {
            $content = @file_get_contents($tmp);
            $map = [];
            $lines = preg_split('/
?
/', (string)$content);
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '') continue;
                if (preg_match('/^(room|roll)/i', $line)) { continue; } // skip header
                // Support: "Room-1: 1,2,3" or CSV "Room-1,1" per line
                if (strpos($line, ':') !== false) {
                    [$room, $rest] = array_map('trim', explode(':', $line, 2));
                    if ($room === '') continue;
                    $rolls = preg_split('/\s*,\s*/', $rest);
                    foreach ($rolls as $rv) {
                        if ($rv === '') continue;
                        if (is_numeric($rv)) { $map[$room][] = (int)$rv; }
                    }
                } else {
                    $parts = array_map('trim', explode(',', $line));
                    if (count($parts) >= 2) {
                        $room = $parts[0]; $rv = $parts[1];
                        if ($room !== '' && is_numeric($rv)) { $map[$room][] = (int)$rv; }
                    }
                }
            }
            // Deduplicate and sort
            foreach ($map as $rm => &$arr) { $arr = array_values(array_unique(array_map('intval', $arr))); sort($arr, SORT_NUMERIC); }
            $_SESSION[$roll_map_session_key] = $map;
            $room_roll_map = $map;
            $info_message = 'Room-wise roll mapping uploaded.';
        }
    }

    // Single-room seat layout upload (CSV/TXT)
    if (isset($_POST['upload_layout']) && isset($_FILES['layout_file']) && $_FILES['layout_file']['error'] === UPLOAD_ERR_OK) {
        $tmp = $_FILES['layout_file']['tmp_name'];
        $size = $_FILES['layout_file']['size'];
        if ($size > 0 && $size < 2*1024*1024) {
            $content = @file_get_contents($tmp);
            $lines = preg_split('/
?
/', (string)$content);

            $triples = [];
            $maxR = 0; $maxC = 0; $hasTriples = false;
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '') continue;
                if (preg_match('/^(row|r)\s*,/i', $line)) { continue; } // skip header
                $t = array_map('trim', explode(',', $line));
                if (count($t) >= 3 && is_numeric($t[0]) && is_numeric($t[1]) && is_numeric($t[2])) {
                    $hasTriples = true;
                    $triples[] = [$t[0], $t[1], $t[2]];
                    $maxR = max($maxR, (int)$t[0]);
                    $maxC = max($maxC, (int)$t[1]);
                }
            }

            if ($hasTriples) {
                // Build from row,col,capacity triples (1-based indexing)
                $M = [];
                for ($r=0; $r<$maxR; $r++) { $M[$r] = array_fill(0, $maxC, 0); }
                foreach ($triples as $t) {
                    $r = max(1, (int)$t[0]) - 1;
                    $c = max(1, (int)$t[1]) - 1;
                    $cap = (int)$t[2];
                    if ($cap < 0) $cap = 0; if ($cap > 2) $cap = 2;
                    if ($r>=0 && $r<$maxR && $c>=0 && $c<$maxC) { $M[$r][$c] = $cap; }
                }
                $bench_matrix_uploaded = $M;
                // Apply uploaded layout: override rows/cols/template for single-room view
                $rows = $maxR; $cols = $maxC; $template = 'custom';
                // Stash into request-like structure so visual grid uses this matrix
                $req['bench'] = [];
                for ($r=0; $r<$rows; $r++) {
                    for ($c=0; $c<$cols; $c++) {
                        $req['bench'][$r][$c] = (int)$bench_matrix_uploaded[$r][$c];
                    }
                }
                $info_message = trim(($info_message ?? '').' সীট প্ল্যান আপলোড হয়েছে এবং প্রয়োগ করা হয়েছে।');
            } else {
                // Try matrix-per-line: e.g., "2,2,1,0" per row
                $M = [];
                $maxC2 = 0;
                foreach ($lines as $line) {
                    $line = trim($line);
                    if ($line === '') continue;
                    if (preg_match('/^(row|r|col|c)/i', $line)) { continue; }
                    $vals = array_values(array_filter(array_map('trim', explode(',', $line)), 'strlen'));
                    if (empty($vals)) continue;
                    $rowCaps = [];
                    foreach ($vals as $v) {
                        if (is_numeric($v)) {
                            $cap = (int)$v; if ($cap < 0) $cap = 0; if ($cap > 2) $cap = 2;
                            $rowCaps[] = $cap;
                        }
                    }
                    if (!empty($rowCaps)) { $M[] = $rowCaps; $maxC2 = max($maxC2, count($rowCaps)); }
                }
                if (!empty($M)) {
                    // Normalize to equal columns
                    foreach ($M as &$rowArr) {
                        if (count($rowArr) < $maxC2) { $rowArr = array_pad($rowArr, $maxC2, 0); }
                    }
                    $rows = count($M); $cols = $maxC2; $template = 'custom';
                    $req['bench'] = [];
                    for ($r=0; $r<$rows; $r++) {
                        for ($c=0; $c<$cols; $c++) {
                            $req['bench'][$r][$c] = (int)$M[$r][$c];
                        }
                    }
                    $info_message = trim(($info_message ?? '').' সীট প্ল্যান আপলোড হয়েছে এবং প্রয়োগ করা হয়েছে।');
                } else {
                    $error_message = 'আপলোড করা ফাইল থেকে সীট প্ল্যান পড়া যায়নি। অনুগ্রহ করে টেমপ্লেট অনুসরণ করুন।';
                }
            }
        }
    }

    // Single-room rolls list upload (one-column CSV of roll numbers)
    if (isset($_POST['upload_single_rolls']) && isset($_FILES['single_rolls_file']) && $_FILES['single_rolls_file']['error'] === UPLOAD_ERR_OK) {
        $tmp = $_FILES['single_rolls_file']['tmp_name'];
        $size = $_FILES['single_rolls_file']['size'];
        if ($size > 0 && $size < 2*1024*1024) {
            $content = @file_get_contents($tmp);
            $lines = preg_split('/
?
/', (string)$content);
            $rolls = [];
            $seen = [];
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '') continue;
                if (preg_match('/^(roll|student)/i', $line)) { continue; } // skip header
                // Allow comma-delimited but primarily expect first token as roll
                $parts = array_map('trim', explode(',', $line));
                $token = $parts[0] ?? '';
                if ($token !== '' && is_numeric($token)) {
                    $rv = (int)$token;
                    if (!isset($seen[$rv])) { $seen[$rv] = true; $rolls[] = $rv; }
                }
            }
            if (!empty($rolls)) {
                $roomKey = $room_number ?: 'Room-1';
                $map = isset($_SESSION[$roll_map_session_key]) && is_array($_SESSION[$roll_map_session_key]) ? $_SESSION[$roll_map_session_key] : [];
                $map[$roomKey] = $rolls; // store for current room
                $_SESSION[$roll_map_session_key] = $map;
                $room_roll_map = $map;
                $info_message = trim(($info_message ?? '').' এই রুমের রোল লিস্ট আপলোড হয়েছে।');
            } else {
                $error_message = 'রোল লিস্ট পড়া যায়নি। এক কলামে রোল নাম্বার দিন।';
            }
        }
    }
}

// Fetch exams for dropdown
$all_exams = $pdo->query("SELECT e.id, e.name, e.session, e.group_name, c.name AS class_name, c.section, e.created_at, e.class_id
                          FROM exams e
                          JOIN classes c ON e.class_id = c.id
                          ORDER BY e.created_at DESC")->fetchAll();

$exam_details = null;
$exam_subjects = [];
$students = [];
$subject_details = null;
$existing_rooms = [];

if ($exam_id) {
    // Exam details
    $stmt = $pdo->prepare("SELECT e.*, c.name AS class_name, c.section FROM exams e JOIN classes c ON e.class_id = c.id WHERE e.id = ?");
    $stmt->execute([$exam_id]);
    $exam_details = $stmt->fetch();

    // Subjects for exam
    $stmt = $pdo->prepare("SELECT es.*, s.name AS subject_name, s.code AS subject_code
                           FROM exam_subjects es JOIN subjects s ON es.subject_id = s.id
                           WHERE es.exam_id = ? ORDER BY es.exam_date, es.start_time");
    $stmt->execute([$exam_id]);
    $exam_subjects = $stmt->fetchAll();

    if ($subject_id) {
        foreach ($exam_subjects as $es) { if ((string)$es['subject_id'] === (string)$subject_id) { $subject_details = $es; break; } }
        // Previously used rooms for this exam+subject
        $stmt = $pdo->prepare("SELECT DISTINCT room_number FROM seat_arrangements WHERE exam_id = ? AND subject_id = ? AND room_number IS NOT NULL AND room_number <> '' ORDER BY room_number");
        $stmt->execute([$exam_id, $subject_id]);
        $existing_rooms = array_map(function($r){ return $r['room_number']; }, $stmt->fetchAll());
    }

    // Students list per exam class/session (respect group)
    if ($exam_details) {
        $sql = "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.group_name
                FROM students s
                WHERE s.class_id = ? AND s.session = ? AND s.status = 'active' ".
                ($exam_details['group_name'] ? "AND s.group_name = ?" : "AND (s.group_name IS NULL OR s.group_name = '')");
        $params = [$exam_details['class_id'], $exam_details['session']];
        if ($exam_details['group_name']) { $params[] = $exam_details['group_name']; }
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $students = $stmt->fetchAll();

        // Order students
        if ($order_mode === 'random') {
            shuffle($students);
        } elseif ($order_mode === 'name') {
            usort($students, function($a,$b){
                return strcasecmp(($a['first_name'].$a['last_name']), ($b['first_name'].$b['last_name']));
            });
        } else { // roll
            usort($students, function($a,$b){
                $ra = is_numeric($a['roll_number']) ? (int)$a['roll_number'] : PHP_INT_MAX;
                $rb = is_numeric($b['roll_number']) ? (int)$b['roll_number'] : PHP_INT_MAX;
                if ($ra === $rb) return strcasecmp($a['first_name'], $b['first_name']);
                return $ra <=> $rb;
            });
        }
    }
}

function build_template_matrix($rows, $cols, $template, $first_n_rows_one = 0) {
    $M = [];
    for ($r=0; $r<$rows; $r++) {
        $M[$r] = [];
        for ($c=0; $c<$cols; $c++) {
            $cap = 2; // default
            switch ($template) {
                case 'all_one': $cap = 1; break;
                case 'alt_cols': $cap = ($c % 2 === 0) ? 2 : 1; break;
                case 'alt_rows': $cap = ($r % 2 === 0) ? 2 : 1; break;
                case 'checker': $cap = (($r + $c) % 2 === 0) ? 2 : 1; break;
                case 'front_one_back_two': $cap = ($r < $first_n_rows_one) ? 1 : 2; break;
                case 'custom': $cap = 2; break; // will be overridden
                default: $cap = 2; // all_two
            }
            $M[$r][$c] = $cap;
        }
    }
    return $M;
}

function bench_order($rows, $cols, $model='row') {

    $order = [];
    switch ($model) {
        case 'column':
            for ($c=0; $c<$cols; $c++) {
                for ($r=0; $r<$rows; $r++) { $order[] = [$r,$c]; }
            }
            break;
        case 'zigzag': // snake per row
            for ($r=0; $r<$rows; $r++) {
                if ($r % 2 == 0) { for ($c=0; $c<$cols; $c++) { $order[] = [$r,$c]; } } 
                else { for ($c=$cols-1; $c>=0; $c--) { $order[] = [$r,$c]; } }
            }
            break;
        case 'diagonal':
            for ($s=0; $s <= $rows + $cols - 2; $s++) {
                for ($r=0; $r<$rows; $r++) {
                    $c = $s - $r;
                    if ($c>=0 && $c<$cols) { $order[] = [$r,$c]; }
                }
            }
            break;
        case 'row':
        default:
            for ($r=0; $r<$rows; $r++) {
                for ($c=0; $c<$cols; $c++) { $order[] = [$r,$c]; }
            }
    }
    return $order;
}

// Build single-room matrix (for visual editor)
$bench_matrix = build_template_matrix($rows, $cols, $template, $first_n_rows_one);
if (isset($req['bench']) && is_array($req['bench'])) {
    foreach ($req['bench'] as $r => $row) {
        foreach ($row as $c => $val) {
            $r_i = (int)$r; $c_i = (int)$c; $v = (int)$val;
            if ($r_i>=0 && $r_i<$rows && $c_i>=0 && $c_i<$cols && in_array($v, [0,1,2], true)) {
                $bench_matrix[$r_i][$c_i] = $v; // 0 = no bench, 1 or 2 = capacity
            }
        }
    }
}

$info_message = isset($info_message) ? $info_message : '';
$assignments_by_room = []; // room => [ [r,c,p,student] ]
$bench_matrix_by_room = []; // room => matrix
$unassigned_by_room = [];   // room => count
$total_capacity_per_room = 0;
$rooms = [];

if ($exam_id && $subject_id) {
    // Single-room mode
    $rooms = [$room_number ?: 'Room-1'];
    $bench_matrix_by_room[$rooms[0]] = $bench_matrix;
    $assignments_by_room[$rooms[0]] = [];

    // Build eligible students order
    $students_by_roll = [];
    foreach ($students as $s) {
        $rnum = is_numeric($s['roll_number']) ? (int)$s['roll_number'] : null;
        if ($rnum !== null) { $students_by_roll[$rnum] = $s; }
    }
    $current_room = $rooms[0];
    $eligible = [];
    if (!empty($room_roll_map) && isset($room_roll_map[$current_room]) && is_array($room_roll_map[$current_room])) {
        foreach ($room_roll_map[$current_room] as $roll) {
            if (isset($students_by_roll[$roll])) { $eligible[] = $students_by_roll[$roll]; }
        }
    } else {
        // Fallback to current $students order (roll/name/random)
        $eligible = $students;
    }

    $idx = 0; $total = count($eligible);
    $order = bench_order($rows, $cols, in_array($assign_model,$allowed_models,true)?$assign_model:'row');
    foreach ($order as [$r,$c]) {
        $cap = (int)$bench_matrix[$r][$c];
        if ($cap <= 0) { continue; }
        for ($p=1; $p<=$cap; $p++) {
            $student = ($idx < $total) ? $eligible[$idx++] : null;
            $assignments_by_room[$rooms[0]][] = [ 'r'=>$r, 'c'=>$c, 'p'=>$p, 'student'=>$student ];
        }
    }
    $cap_single = 0; foreach ($bench_matrix as $row) { foreach ($row as $v) { $cap_single += max(0, (int)$v); } }
    $total_capacity_per_room = $cap_single;
    $unassigned_by_room[$rooms[0]] = max(0, count($eligible) - $cap_single);
}

// Load plan from DB (single-room only)
if ($do_load && $exam_id && $subject_id) {
    $params = [$exam_id, $subject_id];
    $sql = "SELECT row_number, column_number, COUNT(*) AS cnt
            FROM seat_arrangements
            WHERE exam_id = ? AND subject_id = ?";
    if ($room_number !== '') { $sql .= " AND room_number = ?"; $params[] = $room_number; }
    $sql .= " GROUP BY row_number, column_number";
    $rowsInfo = $pdo->prepare($sql);
    $rowsInfo->execute($params);
    $caps = $rowsInfo->fetchAll();
    $maxR = 0; $maxC = 0;
    foreach ($caps as $rc) { $maxR = max($maxR, (int)$rc['row_number']); $maxC = max($maxC, (int)$rc['column_number']); }
    if ($maxR>0 && $maxC>0) {
        $rows = $maxR; $cols = $maxC;
        $bench_matrix = build_template_matrix($rows, $cols, 'all_two', 0);
        foreach ($caps as $rc) {
            $r = (int)$rc['row_number'] - 1; $c = (int)$rc['column_number'] - 1; $cap = min(2, (int)$rc['cnt']);
            if ($r>=0 && $c>=0) { $bench_matrix[$r][$c] = $cap; }
        }
        // Rebuild single-room assignments based on new matrix
        $bench_matrix_by_room[$rooms[0]] = $bench_matrix;
        $assignments_by_room[$rooms[0]] = [];
        $idx = 0; $total = count($students);
        $order = bench_order($rows, $cols, in_array($assign_model,$allowed_models,true)?$assign_model:'row');
        foreach ($order as [$r,$c]) {
            $cap = $bench_matrix[$r][$c];
            for ($p=1; $p<=$cap; $p++) {
                $student = ($idx < $total) ? $students[$idx++] : null;
                $assignments_by_room[$rooms[0]][] = [ 'r'=>$r, 'c'=>$c, 'p'=>$p, 'student'=>$student ];
            }
        }
    }
}

// Save to DB
$save_message = '';
$error_message = '';
if ($do_save && $exam_id && $subject_id && !empty($assignments_by_room)) {
    if (!$subject_details) {
        $stmt = $pdo->prepare("SELECT * FROM exam_subjects WHERE exam_id = ? AND subject_id = ? LIMIT 1");
        $stmt->execute([$exam_id, $subject_id]);
        $subject_details = $stmt->fetch();
    }
    if (!$subject_details) {
        $error_message = 'নির্বাচিত বিষয় পাওয়া যায়নি।';
    } else {
        try {
            $pdo->beginTransaction();
            if (!empty($rooms)) {
                $del = $pdo->prepare("DELETE FROM seat_arrangements WHERE exam_id = ? AND subject_id = ? AND room_number = ?");
                foreach ($rooms as $rm) { $del->execute([$exam_id, $subject_id, $rm]); }
            } else {
                $del = $pdo->prepare("DELETE FROM seat_arrangements WHERE exam_id = ? AND subject_id = ?");
                $del->execute([$exam_id, $subject_id]);
            }
            $seq = 1;
            $ins = $pdo->prepare("INSERT INTO seat_arrangements
                (exam_id, subject_id, student_id, room_number, seat_number, row_number, column_number, exam_date)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            foreach ($assignments_by_room as $rm => $assignments) {
                foreach ($assignments as $a) {
                    if (!$a['student']) continue;
                    $r1 = $a['r'] + 1; $c1 = $a['c'] + 1; $p = $a['p'];
                    // Seat number format
                    if ($seat_format === 'rowcol') {
                        $seat_no = 'R'.$r1.'-C'.$c1.'-P'.$p;
                    } elseif ($seat_format === 'benchpos') {
                        $cols_room = isset($bench_matrix_by_room[$rm][0]) ? count($bench_matrix_by_room[$rm][0]) : $cols;
                        $benchIndex = ($a['r'] * $cols_room) + $a['c'] + 1;
                        $seat_no = 'B'.$benchIndex.'-P'.$p;
                    } else { // seq
                        $seat_no = 'S-'.str_pad((string)$seq, 3, '0', STR_PAD_LEFT);
                    }
                    $ins->execute([
                        $exam_id,
                        $subject_id,
                        $a['student']['id'],
                        $rm,
                        $seat_no,
                        $r1,
                        $c1,
                        $subject_details['exam_date']
                    ]);
                    $seq++;
                }
            }
            $pdo->commit();
            $save_message = 'সীট প্ল্যান সংরক্ষণ করা হয়েছে।';
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = 'সংরক্ষণ ব্যর্থ: '.$e->getMessage();
        }
    }
}

?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ডাইনামিক সীট প্ল্যান</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        @media print { .no-print { display: none !important; } .print-only { display: block !important; } }
        .print-only { display: none; }
        .grid-editor { overflow:auto; }
        .bench-cell { min-width: 80px; min-height: 64px; border: 1px solid #ced4da; border-radius: 6px; padding: 6px; display:flex; align-items:center; justify-content:center; cursor:pointer; background:#f8f9fa; }
        .bench-cell.two { background:#e7f5ff; border-color:#74c0fc; }
        .bench-cell.one { background:#fff5f5; border-color:#faa2c1; }
        .bench-cell.none { background:#f1f3f5; border-color:#dee2e6; opacity:0.6; }
        .bench-cap { font-weight:700; }
        .bench-row { display:grid; grid-auto-flow:column; gap:8px; margin-bottom:8px; }
        .hall-preview { border:1px solid #dee2e6; border-radius:8px; padding:12px; background:#fff; }
        .preview-grid { display:grid; gap:10px; }
        .preview-bench { border:1.6px solid #000; border-radius:6px; padding:6px; background:#fdfdfd; }
        .seats { display:flex; gap:6px; }
        .seat-box { flex:1; border:1px dashed #555; border-radius:4px; min-height:36px; display:flex; align-items:center; justify-content:center; padding:2px 4px; font-weight:600; }
        .seat-empty { color:#aaa; }
        .small { font-size:12px; line-height:1.2; }
        .legend .badge { font-size:12px; }
        .room-title { font-weight:700; margin: 8px 0; }
        .room-block { border: 1px dashed #bbb; border-radius: 8px; padding: 10px; margin-bottom: 16px; background:#fcfcfc; }
        .help-text { font-size: 12px; color: #555; }
        .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; }
    </style>
</head>
<body class="bengali-text">
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary no-print">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম</a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="routine.php"><i class="fas fa-calendar"></i> রুটিন</a>
                <a class="nav-link" href="attendance.php"><i class="fas fa-clipboard-check"></i> হাজিরা</a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-lg-5">
                <div class="card no-print">
                    <div class="card-header"><i class="fas fa-table"></i> ডাইনামিক সীট প্ল্যান কনফিগারেশন</div>
                    <div class="card-body">
                        <?php if (!empty($save_message)): ?>
                            <div class="alert alert-success alert-dismissible fade show"><i class="fas fa-check-circle"></i> <?php echo h($save_message); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
                        <?php endif; ?>
                        <?php if (!empty($error_message)): ?>
                            <div class="alert alert-danger alert-dismissible fade show"><i class="fas fa-exclamation-triangle"></i> <?php echo h($error_message); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
                        <?php endif; ?>
                        <?php if (!empty($info_message)): ?>
                            <div class="alert alert-warning alert-dismissible fade show"><i class="fas fa-info-circle"></i> <?php echo h($info_message); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
                        <?php endif; ?>

                        <form method="POST" id="planForm" enctype="multipart/form-data">
                            <div class="row g-3">
                                <div class="col-12">
                                    <label class="form-label">পরীক্ষা নির্বাচন করুন</label>
                                    <select class="form-select" name="exam_id" required onchange="document.getElementById('planForm').submit()">
                                        <option value="">পরীক্ষা নির্বাচন করুন</option>
                                        <?php foreach ($all_exams as $exam): ?>
                                            <option value="<?php echo h($exam['id']); ?>" <?php echo ($exam_id == $exam['id']) ? 'selected' : ''; ?> >
                                                <?php echo h($exam['name'].' - '.$exam['class_name'].' ('.$exam['section'].')'.($exam['group_name']? ' - '.$exam['group_name'] : '')); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="col-12">
                                    <label class="form-label">বিষয়</label>
                                    <select class="form-select" name="subject_id" <?php echo $exam_id? '' : 'disabled'; ?> onchange="document.getElementById('planForm').submit()">
                                        <option value="">বিষয় নির্বাচন করুন</option>
                                        <?php foreach ($exam_subjects as $sub): ?>
                                            <option value="<?php echo h($sub['subject_id']); ?>" <?php echo ($subject_id == $sub['subject_id']) ? 'selected' : ''; ?> >
                                                <?php echo h($sub['subject_name']).' ('.h($sub['subject_code']).') - '.h($sub['exam_date']).' '.h($sub['start_time']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="autoSplit" name="auto_split" value="1" <?php echo $auto_split?'checked':''; ?> onchange="toggleRoomMode()">
                                        <label class="form-check-label" for="autoSplit">একাধিক রুমে অটো-স্প্লিট (Roll Range রুল / আপলোড)</label>
                                    </div>
                                </div>

                                <div id="singleRoomControls" style="<?php echo $auto_split? 'display:none;' : ''; ?>">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label">রুম</label>
                                            <input list="roomList" type="text" class="form-control" name="room_number" value="<?php echo h($room_number); ?>" placeholder="Room-1">
                                            <datalist id="roomList">
                                                <?php foreach ($existing_rooms as $rm): ?>
                                                    <option value="<?php echo h($rm); ?>"></option>
                                                <?php endforeach; ?>
                                            </datalist>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">সীট নম্বর ফরম্যাট</label>
                                            <select class="form-select" name="seat_format">
                                                <option value="seq" <?php echo $seat_format==='seq'?'selected':''; ?>>ক্রমিক: S-001, S-002...</option>
                                                <option value="rowcol" <?php echo $seat_format==='rowcol'?'selected':''; ?>>Row/Col/Pos: R1-C1-P1</option>
                                                <option value="benchpos" <?php echo $seat_format==='benchpos'?'selected':''; ?>>Bench/Pos: B1-P1</option>
                                            </select>
                                        </div>

                                        <div class="col-4">
                                            <label class="form-label">সারি (Rows)</label>
                                            <input type="number" class="form-control" name="rows" value="<?php echo (int)$rows; ?>" min="1" max="30" />
                                        </div>
                                        <div class="col-4">
                                            <label class="form-label">কলাম (Cols)</label>
                                            <input type="number" class="form-control" name="cols" value="<?php echo (int)$cols; ?>" min="1" max="30" />
                                        </div>
                                        <div class="col-4">
                                            <label class="form-label">অর্ডার</label>
                                            <select class="form-select" name="order_mode">
                                                <option value="roll" <?php echo $order_mode==='roll'?'selected':''; ?>>রোল</option>
                                                <option value="name" <?php echo $order_mode==='name'?'selected':''; ?>>নাম</option>
                                                <option value="random" <?php echo $order_mode==='random'?'selected':''; ?>>র‌্যান্ডম</option>
                                            </select>
                                        </div>

                                        <div class="col-md-6">
                                            <label class="form-label">টেমপ্লেট (১/২ সিট)</label>
                                            <select class="form-select" name="template" id="templateSelect" onchange="toggleTemplateOptions()">
                                                <option value="all_two" <?php echo $template==='all_two'?'selected':''; ?>>সব বেঞ্চ ২ সিট</option>
                                                <option value="all_one" <?php echo $template==='all_one'?'selected':''; ?>>সব বেঞ্চ ১ সিট</option>
                                                <option value="alt_cols" <?php echo $template==='alt_cols'?'selected':''; ?>>কলাম অনুযায়ী ২/১</option>
                                                <option value="alt_rows" <?php echo $template==='alt_rows'?'selected':''; ?>>সারি অনুযায়ী ২/১</option>
                                                <option value="checker" <?php echo $template==='checker'?'selected':''; ?>>চেকারবোর্ড ২/১</option>
                                                <option value="front_one_back_two" <?php echo $template==='front_one_back_two'?'selected':''; ?>>সামনে ১ সিট, পেছনে ২ সিট</option>
                                                <option value="custom" <?php echo $template==='custom'?'selected':''; ?>>কাস্টম</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">সীটিং মডেল</label>
                                            <select class="form-select" name="assign_model">
                                                <option value="row" <?php echo $assign_model==='row'?'selected':''; ?>>সারি</option>
                                                <option value="column" <?php echo $assign_model==='column'?'selected':''; ?>>কলাম</option>
                                                <option value="zigzag" <?php echo $assign_model==='zigzag'?'selected':''; ?>>ঝিকঝাক</option>
                                                <option value="diagonal" <?php echo $assign_model==='diagonal'?'selected':''; ?>>ডায়াগোনাল (কোনাকুনি)</option>
                                            </select>
                                        </div>
                                        <div class="col-12" id="frontRowsOpt" style="<?php echo ($template==='front_one_back_two')? '' : 'display:none'; ?>">
                                            <label class="form-label">সামনের কত সারি ১ সিট হবে?</label>
                                            <input type="number" class="form-control" name="first_n_rows_one" value="<?php echo (int)$first_n_rows_one; ?>" min="0" max="<?php echo (int)$rows; ?>" />
                                        </div>

                                        <div class="col-12">
                                            <div class="d-flex justify-content-between align-items-center mb-2">
                                                <div class="legend">
                                                    <span class="badge bg-info">২ সিট বেঞ্চ</span>
                                                    <span class="badge bg-danger">১ সিট বেঞ্চ</span>
                                                </div>
                                                <div class="btn-group">
                                                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="applyTemplate()"><i class="fas fa-magic"></i> টেমপ্লেট প্রয়োগ</button>
                                                    <button type="button" class="btn btn-sm btn-outline-dark" onclick="clearCustom()"><i class="fas fa-eraser"></i> ক্লিয়ার</button>
                                                </div>
                                            </div>
                                            <div class="grid-editor" id="gridEditor"></div>
                                        </div>

                                        <div class="col-12">
                                            <hr>
                                            <h6><i class="fas fa-file-upload"></i> রুমের রোল লিস্ট আপলোড (এক কলাম CSV)</h6>
                                            <div class="help-text">একই কলামে রোল নাম্বার দিন (প্রতি লাইনে একটি)। আপলোডের পর সিটিং মডেল অনুযায়ী অটো সেট হবে।</div>
                                            <div class="help-text"><pre class="mono small mb-1">Roll
101
102
103
...</pre></div>
                                            <div class="d-flex align-items-center gap-2 mt-2">
                                                <input class="form-control" type="file" name="single_rolls_file" accept=".csv,.txt">
                                                <button class="btn btn-outline-primary" type="submit" name="upload_single_rolls"><i class="fas fa-upload"></i> আপলোড</button>
                                                <a class="btn btn-outline-secondary" href="../bulk_upload/templates/room_rolls_template.csv" download><i class="fas fa-download"></i> টেমপ্লেট ডাউনলোড</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div id="autoSplitControls" style="<?php echo $auto_split? '' : 'display:none;'; ?>">
                                    <div class="row g-3">
                                        <div class="col-12">
                                            <label class="form-label">Room Rules (প্রতি লাইনে)</label>
                                            <textarea class="form-control mono" name="room_rules" rows="7" placeholder="Room-1:1-30:6x6:all_two:row
Room-2:31-60:6x6:checker:zigzag
Room-3:61-90:5x8:front_one_back_two:1:diagonal"><?php echo h($room_rules); ?></textarea>
                                            <div class="help-text mt-1">
                                                ফরম্যাট: Room:Start-End:RowsxCols:Template[:FrontRows][:Model]<br>
                                                - Template: all_two, all_one, alt_cols, alt_rows, checker, front_one_back_two, custom<br>
                                                - Model: row (সারি), column (কলাম), zigzag (ঝিকঝাক), diagonal (কোনাকুনি)
                                            </div>
                                        </div>
                                        <div class="col-12 mt-3">
                                            <label class="form-label">বিষয় ভিত্তিক রোল রেঞ্জ (ঐচ্ছিক)</label>
                                            <textarea class="form-control mono" name="subject_roll_rules" rows="4" placeholder="SubjectCode:Room-1:1-25&#10;SubjectCode:Room-2:26-50"><?php echo h($subject_roll_rules); ?></textarea>
                                            <div class="help-text mt-1">
                                                ফরম্যাট: <code>SubjectCode:Room:Start-End</code> (প্রতি লাইনে একটি)<br>
                                                যদি বর্তমান নির্বাচিত বিষয়ের কোডের জন্য কোনো নিয়ম পাওয়া যায়, তবে এটি উপরের সাধারণ নিয়মের রোল রেঞ্জকে ওভাররাইড করবে।
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="useVisual" name="use_visual_layout" value="1" <?php echo $use_visual_layout?'checked':''; ?>>
                                                <label class="form-check-label" for="useVisual">রুম-১ এর চিত্রভিত্তিক লেআউট সব রুমে প্রয়োগ করুন</label>
                                            </div>
                                            <div class="help-text">উপরে থাকা Rows/Cols/Template এবং গ্রিড এডিটর অনুযায়ী ১/২-সিট লেআউট সব রুমে কপি হবে।</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">সীট নম্বর ফরম্যাট</label>
                                            <select class="form-select" name="seat_format">
                                                <option value="seq" <?php echo $seat_format==='seq'?'selected':''; ?>>ক্রমিক: S-001, S-002...</option>
                                                <option value="rowcol" <?php echo $seat_format==='rowcol'?'selected':''; ?>>Row/Col/Pos: R1-C1-P1</option>
                                                <option value="benchpos" <?php echo $seat_format==='benchpos'?'selected':''; ?>>Bench/Pos: B1-P1</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">অর্ডার</label>
                                            <select class="form-select" name="order_mode">
                                                <option value="roll" <?php echo $order_mode==='roll'?'selected':''; ?>>রোল</option>
                                                <option value="name" <?php echo $order_mode==='name'?'selected':''; ?>>নাম</option>
                                                <option value="random" <?php echo $order_mode==='random'?'selected':''; ?>>র‌্যান্ডম</option>
                                            </select>
                                        </div>

                                        <div class="col-12">
                                            <hr>
                                            <h6><i class="fas fa-file-upload"></i> রুমভিত্তিক রোল আপলোড</h6>
                                            <div class="help-text">ফরম্যাট ১: Room-1: 1,2,3 (প্রতি লাইনে); ফরম্যাট ২ (CSV): Room-1,1</div>
                                            <div class="d-flex align-items-center gap-2 mt-2">
                                                <input class="form-control" type="file" name="rolls_file" accept=".csv,.txt">
                                                <button class="btn btn-outline-primary" type="submit" name="upload_rolls"><i class="fas fa-upload"></i> আপলোড</button>
                                                <?php if (!empty($room_roll_map)): ?>
                                                <button class="btn btn-outline-danger" type="submit" name="clear_rolls" onclick="return confirm('আপলোডেড রোল ম্যাপ ক্লিয়ার হবে, নিশ্চিত?')"><i class="fas fa-times"></i> ক্লিয়ার</button>
                                                <?php endif; ?>
                                            </div>
                                            <?php if (!empty($room_roll_map)): ?>
                                                <div class="small mt-2">
                                                    <?php foreach ($room_roll_map as $rm => $list): ?>
                                                        <div>Room <strong><?php echo h($rm); ?></strong>: <?php echo count($list); ?> রোল</div>
                                                    <?php endforeach; ?>
                                                    <div class="help-text">আপলোডেড রোল থাকলে রেঞ্জের বদলে সেটিই প্রাধান্য পাবে।</div>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-12 d-flex gap-2 mt-1">
                                    <button type="submit" class="btn btn-primary" name="generate"><i class="fas fa-play"></i> প্ল্যান জেনারেট</button>
                                    <button type="submit" class="btn btn-success" name="save_seats" <?php echo (!$exam_id||!$subject_id)?'disabled':''; ?>><i class="fas fa-save"></i> সেভ</button>
                                    <button type="submit" class="btn btn-outline-secondary" name="load_plan" <?php echo ($auto_split||!$exam_id||!$subject_id)?'disabled':''; ?>><i class="fas fa-cloud-download-alt"></i> লোড</button>
                                    <button type="button" class="btn btn-outline-dark" onclick="window.print()" <?php echo empty($assignments_by_room)?'disabled':''; ?>><i class="fas fa-print"></i> প্রিন্ট</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-lg-7">
                <div class="card">
                    <div class="card-header"><i class="fas fa-chalkboard"></i> হল লেআউট প্রিভিউ</div>
                    <div class="card-body hall-preview">
                        <?php if (!$exam_details): ?>
                            <div class="alert alert-info">একটি পরীক্ষা নির্বাচন করুন।</div>
                        <?php elseif (!$subject_id): ?>
                            <div class="alert alert-info">একটি বিষয় নির্বাচন করুন।</div>
                        <?php else: ?>
                            <div class="mb-2 small">
                                <strong><?php echo h($exam_details['name']); ?></strong> · ক্লাস: <?php echo h($exam_details['class_name'].' ('.$exam_details['section'].')'); ?> · সেশন: <?php echo h($exam_details['session']); ?>
                                <?php if ($exam_details['group_name']): ?> · গ্রুপ: <?php echo h($exam_details['group_name']); ?><?php endif; ?>
                                <?php if ($subject_details): ?>
                                    <br>বিষয়: <?php echo h($subject_details['subject_name'] ?? ''); ?> · তারিখ: <?php echo h($subject_details['exam_date'] ?? ''); ?>
                                <?php endif; ?>
                                <?php if (!$auto_split): ?>
                                    <br>রুম: <?php echo h($rooms[0] ?? ''); ?> · আসন ক্ষমতা: <?php echo (int)$total_capacity_per_room; ?> · মোট ছাত্র: <?php echo count($students); ?> · মডেল: <?php echo h($assign_model); ?>
                                <?php else: ?>
                                    <br>রুমসমূহ: <?php echo h(implode(', ', $rooms)); ?> · মোট ছাত্র: <?php echo count($students); ?><?php if ($use_visual_layout): ?> · ভিজ্যুয়াল লেআউট প্রযোজ্য<?php endif; ?>
                                <?php endif; ?>
                            </div>

                            <?php foreach ($assignments_by_room as $rm => $assignments): ?>
                                <div class="room-block">
                                    <div class="room-title">রুম: <?php echo h($rm); ?><?php if (isset($unassigned_by_room[$rm]) && $unassigned_by_room[$rm]>0): ?><span class="badge bg-warning ms-2">Unassigned: <?php echo (int)$unassigned_by_room[$rm]; ?></span><?php endif; ?></div>
                                    <?php $matrix = $bench_matrix_by_room[$rm]; $R = count($matrix); $C = count($matrix[0]); ?>
                                    <?php
                                    echo '<div class="preview-grid" style="grid-template-columns: repeat('.(int)$C.', 1fr);">';
                                    $map = [];
                                    foreach ($assignments as $a) {
                                        $key = $a['r'].':'.$a['c'];
                                        if (!isset($map[$key])) $map[$key] = [];
                                        $map[$key][] = $a;
                                    }
                                    for ($r=0; $r<$R; $r++) {
                                        for ($c=0; $c<$C; $c++) {
                                            $cap = $matrix[$r][$c];
                                            $key = $r.':'.$c;
                                            $list = isset($map[$key]) ? $map[$key] : [];
                                            if ((int)$cap === 0) {
                                                echo '<div class="preview-bench"><div class="d-flex justify-content-between small"><span>Row '.($r+1).', Col '.($c+1).'</span><span class="text-muted">off</span></div><div class="seats mt-1"><div class="seat-box seat-empty">নেই</div></div></div>';
                                            } else {
                                                echo '<div class="preview-bench">';
                                                echo '<div class="d-flex justify-content-between small"><span>Row '.($r+1).', Col '.($c+1).'</span><span class="text-muted">'.($cap==2?'2-seater':'1-seater').'</span></div>';
                                                echo '<div class="seats mt-1">';
                                                if ($cap == 2) {
                                                    for ($p=1;$p<=2;$p++) {
                                                        $slot = isset($list[$p-1]) ? $list[$p-1] : null;
                                                        if ($slot && $slot['student']) {
                                                            $s = $slot['student'];
                                                            $label = 'Roll '.h($s['roll_number']);
                                                            echo '<div class="seat-box">'.$label.'</div>';
                                                        } else {
                                                            echo '<div class="seat-box seat-empty">খালি</div>';
                                                        }
                                                    }
                                                } else {
                                                    $slot = isset($list[0]) ? $list[0] : null;
                                                    if ($slot && $slot['student']) {
                                                        $s = $slot['student'];
                                                        $label = 'Roll '.h($s['roll_number']);
                                                        echo '<div class="seat-box">'.$label.'</div>';
                                                    } else {
                                                        echo '<div class="seat-box seat-empty">খালি</div>';
                                                    }
                                                }
                                                echo '</div>';
                                                echo '</div>';
                                            }
                                        }
                                    }
                                    echo '</div>';
                                    ?>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const rowsInput = document.querySelector('input[name="rows"]');
        const colsInput = document.querySelector('input[name="cols"]');
        const templateSelect = document.getElementById('templateSelect');
        const gridEditor = document.getElementById('gridEditor');
        const autoSplit = document.getElementById('autoSplit');

        function toggleTemplateOptions(){
            if (!templateSelect) return;
            const v = templateSelect.value;
            const el = document.getElementById('frontRowsOpt');
            if (el) el.style.display = (v==='front_one_back_two') ? '' : 'none';
        }
        function toggleRoomMode(){
            const on = autoSplit.checked;
            const s = document.getElementById('singleRoomControls');
            const m = document.getElementById('autoSplitControls');
            if (s) s.style.display = on ? 'none' : '';
            if (m) m.style.display = on ? '' : 'none';
        }

        function createHidden(name, value){
            const i = document.createElement('input');
            i.type = 'hidden'; i.name = name; i.value = value; return i;
        }

        function renderEditor(){
            if (!gridEditor) return;
            const R = Math.max(1, parseInt(rowsInput.value||'1',10));
            const C = Math.max(1, parseInt(colsInput.value||'1',10));
            gridEditor.innerHTML = '';
            for (let r=0; r<R; r++){
                const row = document.createElement('div');
                row.className = 'bench-row';
                row.style.gridTemplateColumns = `repeat(${C}, 1fr)`;
                for (let c=0; c<C; c++){
                    const wrap = document.createElement('div');
                    wrap.className = 'bench-cell two';
                    wrap.dataset.r = r; wrap.dataset.c = c; wrap.dataset.cap = '2';
                    wrap.onclick = () => toggleCap(wrap);
                    wrap.innerHTML = '<span class="bench-cap">2</span>';
                    const name = `bench[${r}][${c}]`;
                    wrap.appendChild(createHidden(name, '2'));
                    row.appendChild(wrap);
                    // Apply initial classes
                    wrap.classList.toggle('two', true);
                    wrap.classList.toggle('one', false);
                    wrap.classList.toggle('none', false);
                }
                gridEditor.appendChild(row);
            }
            applyTemplate();
        }

        function toggleCap(cell){
            // Cycle 2 -> 1 -> 0 -> 2
            let cap = cell.dataset.cap || '2';
            if (cap === '2') cap = '1';
            else if (cap === '1') cap = '0';
            else cap = '2';
            cell.dataset.cap = cap;
            cell.querySelector('.bench-cap').textContent = cap;
            const input = cell.querySelector('input[type="hidden"]');
            input.value = cap;
            cell.classList.toggle('two', cap==='2');
            cell.classList.toggle('one', cap==='1');
            cell.classList.toggle('none', cap==='0');
        }

        function applyTemplate(){
            if (!gridEditor || !templateSelect) return;
            const R = gridEditor.children.length;
            if (R===0) return;
            const C = gridEditor.children[0].children.length;
            const tpl = templateSelect.value;
            const frontRowsEl = document.querySelector('input[name="first_n_rows_one"]');
            const firstRowsOne = frontRowsEl ? parseInt(frontRowsEl.value||'0',10) : 0;
            for (let r=0; r<R; r++){
                const row = gridEditor.children[r];
                for (let c=0; c<C; c++){
                    const cell = row.children[c];
                    let cap = '2';
                    switch(tpl){
                        case 'all_one': cap='1'; break;
                        case 'alt_cols': cap = (c%2===0)?'2':'1'; break;
                        case 'alt_rows': cap = (r%2===0)?'2':'1'; break;
                        case 'checker': cap = ((r+c)%2===0)?'2':'1'; break;
                        case 'front_one_back_two': cap = (r < firstRowsOne) ? '1' : '2'; break;
                        case 'custom': cap = cell.dataset.cap || '2'; break;
                        default: cap='2';
                    }
                    cell.dataset.cap = cap;
                    cell.querySelector('.bench-cap').textContent = cap;
                    const input = cell.querySelector('input[type="hidden"]');
                    input.value = cap;
                    cell.classList.toggle('two', cap==='2');
                    cell.classList.toggle('one', cap==='1');
                }
            }
        }

        function clearCustom(){
            if (!gridEditor) return;
            [...gridEditor.querySelectorAll('.bench-cell')].forEach(cell=>{
                cell.dataset.cap = '2';
                cell.querySelector('.bench-cap').textContent = '2';
                const hid = cell.querySelector('input[type="hidden"]');
                if (hid) hid.value = '2';
                cell.classList.add('two');
                cell.classList.remove('one');
            });
        }

        // Initialize
        renderEditor();
        toggleTemplateOptions();
        toggleRoomMode();
    </script>
</body>
</html>