<?php
session_start();

// Seat plan generator with customizable benches per row + graphical editor + seating patterns + custom heading/room/subject
// - Input rolls: one-column (kept in uploaded order)
// - Layout modes:
//   - uniform: Rows x Columns, each bench has fixed capacity (1 or 2)
//   - custom: per-row variable benches; each bench capacity 0/1/2 (0 = off/blank)
//   - graphical editor to arrange rows/benches and toggle capacities
// - Seating patterns (bench traversal order): row, column, zigzag, diagonal (two), spiral, etc.
// - Custom header fields: heading, room number, subject
// - Output: printable HTML + client-side PDF

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

// Inputs
$mode = isset($_POST['mode']) && in_array($_POST['mode'], ['uniform','custom'], true) ? $_POST['mode'] : 'uniform';
$rows = isset($_POST['rows']) ? max(1, (int)$_POST['rows']) : 6;
$cols = isset($_POST['cols']) ? max(1, (int)$_POST['cols']) : 6;
$bench_cap = isset($_POST['bench_cap']) ? max(1, min(2, (int)$_POST['bench_cap'])) : 2; // for uniform mode
$layout_text = isset($_POST['layout_text']) ? trim((string)$_POST['layout_text']) : '';
$allowed_patterns = ['row_lr','row_rl','col_tb','col_bt','zigzag_row','zigzag_col','diag_tl','diag_tr','spiral'];
$pattern = isset($_POST['pattern']) && in_array($_POST['pattern'], $allowed_patterns, true) ? $_POST['pattern'] : 'row_lr';

// Custom printable header fields
$custom_heading = isset($_POST['custom_heading']) ? trim((string)$_POST['custom_heading']) : '';
$room_no = isset($_POST['room_no']) ? trim((string)$_POST['room_no']) : '';
$subject_name = isset($_POST['subject_name']) ? trim((string)$_POST['subject_name']) : '';

$rolls = [];
$error = '';
$info = '';

$pattern_labels = [
    'row_lr' => 'সারি (বাঁ→ডানে)',
    'row_rl' => 'সারি (ডানে→বাঁ)',
    'col_tb' => 'কলাম (উপর→নিচ)',
    'col_bt' => 'কলাম (নিচ→উপর)',
    'zigzag_row' => 'ঝিকঝাক (সারি ভিত্তিক)',
    'zigzag_col' => 'ঝিকঝাক (কলাম ভিত্তিক)',
    'diag_tl' => 'ডায়াগনাল (বাম-উপর → ডান-নিচ)',
    'diag_tr' => 'কুনাকুনি (ডান-উপর → বাম-নিচ)',
    'spiral' => 'স্পাইরাল (বাহির→ভিতর)'
];

// Helper: parse custom layout from text
function parse_layout_text($text){
    // Each line is a row; comma-separated integers 0/1/2; different rows can have different bench counts
    $lines = preg_split('/\r?\n/', (string)$text);
    $layout = [];
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '') continue;
        $parts = preg_split('/\s*,\s*/', $line);
        $row = [];
        foreach ($parts as $p) {
            if ($p === '') continue;
            if (!is_numeric($p)) continue;
            $v = (int)$p; if ($v < 0) $v = 0; if ($v > 2) $v = 2; $row[] = $v;
        }
        if (!empty($row)) $layout[] = $row;
    }
    return $layout;
}

// Parse pasted roll text
if (!empty($_POST['rolls_text'])) {
    $lines = preg_split("/\r?\n/", (string)$_POST['rolls_text']);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '') continue;
        if (preg_match('/^(roll|student)/i', $line)) continue; // skip header
        $parts = array_map('trim', explode(',', $line));
        $token = $parts[0] ?? '';
        if ($token !== '') { $rolls[] = $token; }
    }
}

// Parse uploaded roll file (preferred)
if (isset($_POST['upload']) && 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);
        $lines = preg_split('/\r?\n/', (string)$content);
        $uploaded = [];
        foreach ($lines as $line) {
            $line = trim($line);
            if ($line === '') continue;
            if (preg_match('/^(roll|student)/i', $line)) continue; // skip header
            $parts = array_map('trim', explode(',', $line));
            $token = $parts[0] ?? '';
            if ($token !== '') { $uploaded[] = $token; }
        }
        if (!empty($uploaded)) {
            $rolls = $uploaded; // keep upload order
            $info = 'রোল লিস্ট আপলোড সফল হয়েছে।';
        } else { $error = 'ফাইল থেকে রোল পড়া যায়নি। এক কলামে রোল নম্বর দিন।'; }
    } else { $error = 'ফাইলটি খালি বা খুব বড়।'; }
}

// Custom layout via file upload (csv/txt) if provided
$custom_layout = [];
if ($mode === 'custom') {
    if (isset($_POST['use_layout_file']) && 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);
            $custom_layout = parse_layout_text($content);
            if (empty($custom_layout)) { $error = 'লেআউট ফাইল থেকে ডেটা পড়া যায়নি। 0/1/2 দিয়ে কমা-সেপারেটেড ফরম্যাট দিন।'; }
        } else { $error = 'লেআউট ফাইলটি খালি বা খুব বড়।'; }
    } elseif ($layout_text !== '') {
        $custom_layout = parse_layout_text($layout_text);
        if (empty($custom_layout) && $layout_text !== '') { $error = 'লেআউট টেক্সট থেকে কিছু পাওয়া যায়নি। 0/1/2 দিয়ে কমা-সেপারেটেড ফরম্যাট দিন।'; }
    }
}

// Build bench layout matrix for the current page model
$layout_matrix = [];
if ($mode === 'uniform') {
    for ($r=0; $r<$rows; $r++) { $rowArr = []; for ($c=0; $c<$cols; $c++) { $rowArr[] = $bench_cap; } $layout_matrix[] = $rowArr; }
} else {
    if (!empty($custom_layout)) { $layout_matrix = $custom_layout; }
    else { $layout_matrix = [[2,2,2,2,2],[2,2,2,2,2]]; }
}

// Helpers for patterns
function max_cols($layout){ $m = 0; foreach ($layout as $r){ $m = max($m, count($r)); } return $m; }
function add_slots_for(&$order, $r, $c, $cap){ $cap = max(0, (int)$cap); for ($p=1; $p<=$cap; $p++){ $order[] = [$r,$c,$p]; } }
function exists_bench($layout, $r, $c){ return isset($layout[$r]) && isset($layout[$r][$c]); }

function generate_order($layout, $pattern){
    $R = count($layout); $C = max_cols($layout); $order = [];
    switch ($pattern) {
        case 'row_lr':
            for ($r=0; $r<$R; $r++) { for ($c=0; $c<$C; $c++){ if (exists_bench($layout,$r,$c)) add_slots_for($order,$r,$c,$layout[$r][$c]); } }
            break;
        case 'row_rl':
            for ($r=0; $r<$R; $r++) { for ($c=$C-1; $c>=0; $c--){ if (exists_bench($layout,$r,$c)) add_slots_for($order,$r,$c,$layout[$r][$c]); } }
            break;
        case 'col_tb':
            for ($c=0; $c<$C; $c++) { for ($r=0; $r<$R; $r++){ if (exists_bench($layout,$r,$c)) add_slots_for($order,$r,$c,$layout[$r][$c]); } }
            break;
        case 'col_bt':
            for ($c=0; $c<$C; $c++) { for ($r=$R-1; $r>=0; $r--){ if (exists_bench($layout,$r,$c)) add_slots_for($order,$r,$c,$layout[$r][$c]); } }
            break;
        case 'zigzag_row':
            for ($r=0; $r<$R; $r++) {
                if ($r % 2 === 0) { for ($c=0; $c<$C; $c++){ if (exists_bench($layout,$r,$c)) add_slots_for($order,$r,$c,$layout[$r][$c]); } }
                else { for ($c=$C-1; $c>=0; $c--){ if (exists_bench($layout,$r,$c)) add_slots_for($order,$r,$c,$layout[$r][$c]); } }
            }
            break;
        case 'zigzag_col':
            for ($c=0; $c<$C; $c++) {
                if ($c % 2 === 0) { for ($r=0; $r<$R; $r++){ if (exists_bench($layout,$r,$c)) add_slots_for($order,$r,$c,$layout[$r][$c]); } }
                else { for ($r=$R-1; $r>=0; $r--){ if (exists_bench($layout,$r,$c)) add_slots_for($order,$r,$c,$layout[$r][$c]); } }
            }
            break;
        case 'diag_tl': // top-left to bottom-right diagonals
            for ($s=0; $s<=($R+$C-2); $s++) {
                for ($r=0; $r<$R; $r++) { $c = $s - $r; if ($c>=0 && $c<$C && exists_bench($layout,$r,$c)) add_slots_for($order,$r,$c,$layout[$r][$c]); }
            }
            break;
        case 'diag_tr': // top-right to bottom-left diagonals
            for ($s=0; $s<=($R+$C-2); $s++) {
                for ($r=0; $r<$R; $r++) { $c = ($C-1) - ($s - $r); if ($c>=0 && $c<$C && exists_bench($layout,$r,$c)) add_slots_for($order,$r,$c,$layout[$r][$c]); }
            }
            break;
        case 'spiral':
            $top=0; $bottom=$R-1; $left=0; $right=$C-1;
            while ($top <= $bottom && $left <= $right) {
                // top row
                for ($c=$left; $c<=$right; $c++) { if (exists_bench($layout,$top,$c)) add_slots_for($order,$top,$c,$layout[$top][$c]); }
                // right col
                for ($r=$top+1; $r<=$bottom; $r++) { if (exists_bench($layout,$r,$right)) add_slots_for($order,$r,$right,$layout[$r][$right]); }
                if ($top < $bottom) {
                    // bottom row
                    for ($c=$right-1; $c>=$left; $c--) { if (exists_bench($layout,$bottom,$c)) add_slots_for($order,$bottom,$c,$layout[$bottom][$c]); }
                }
                if ($left < $right) {
                    // left col
                    for ($r=$bottom-1; $r>$top; $r--) { if (exists_bench($layout,$r,$left)) add_slots_for($order,$r,$left,$layout[$r][$left]); }
                }
                $top++; $right--; $bottom--; $left++;
            }
            break;
        default:
            // fallback to row_lr
            for ($r=0; $r<$R; $r++) { for ($c=0; $c<$C; $c++){ if (exists_bench($layout,$r,$c)) add_slots_for($order,$r,$c,$layout[$r][$c]); } }
    }
    return $order;
}

// Compute total capacity per page
$capacity_per_page = 0; foreach ($layout_matrix as $r) { foreach ($r as $cap) { $capacity_per_page += max(0, (int)$cap); } }
$total_rolls = count($rolls);
$pages = 1; if ($capacity_per_page > 0) { $pages = max(1, (int)ceil($total_rolls / $capacity_per_page)); } else { if ($total_rolls > 0) { $error = trim($error.' লেআউটে মোট সিট 0।'); } }

$initial_layout_for_editor = ($mode==='custom') ? $layout_matrix : [];
$slots_order = generate_order($layout_matrix, $pattern);

?><!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Seat Plan (Roll Upload + Custom Layout + Graphic Editor + Patterns)</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* Global Bengali font */
        :root { --bs-font-sans-serif: 'Hind Siliguri','Noto Sans Bengali','SolaimanLipi',system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial,'Noto Sans',sans-serif; }
        html, body, .btn, .form-control, .form-select, .form-check-label, .nav-link, .card, .table, .alert, .modal, .badge, .dropdown-menu, .dropdown-item {
            font-family: 'Hind Siliguri','Noto Sans Bengali','SolaimanLipi',system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial,'Noto Sans',sans-serif !important;
        }
        @media print { .no-print { display: none !important; } .page { break-after: page; } body { margin: 8mm; } }
        .bench { border:1px solid #333; border-radius:6px; padding:6px; background:#fafafa; }
        .bench-head { display:flex; justify-content:space-between; font-size:12px; color:#6c757d; }
        .seats { display:flex; gap:6px; margin-top:6px; }
        .seat-box { flex:1; min-width:46px; min-height:42px; display:flex; align-items:center; justify-content:center; border:1px dashed #666; border-radius:4px; font-weight:600; }
        .seat-empty { color:#adb5bd; }
        .row-line { display:grid; gap:10px; margin-bottom:10px; }
        .page { padding: 12px; border: 1px solid #e9ecef; border-radius: 8px; margin-bottom: 16px; background: #fff; }
        .page h6 { margin-bottom: 10px; }
        .help-text { font-size: 12px; color:#6c757d; }
        /* Graphic editor */
        .editor-row { border:1px dashed #ced4da; border-radius:8px; padding:8px; margin-bottom:10px; background:#fff; }
        .editor-row-head { display:flex; justify-content:space-between; align-items:center; }
        .editor-benches { display:flex; gap:8px; flex-wrap:wrap; margin-top:8px; }
        .bench-btn { width:48px; height:40px; border-radius:6px; display:flex; align-items:center; justify-content:center; cursor:pointer; font-weight:700; border:1px solid #adb5bd; user-select:none; }
        .bench-btn.cap-0 { background:#f8f9fa; color:#adb5bd; border-style:dashed; }
        .bench-btn.cap-1 { background:#fff3cd; color:#856404; border-color:#ffeeba; }
        .bench-btn.cap-2 { background:#d1e7dd; color:#0f5132; border-color:#badbcc; }
    </style>
</head>
<body class="bg-light">
<div class="container py-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="m-0">ডাইনামিক সীটপ্ল্যান (গ্রাফিক এডিটার + প্যাটার্ন)</h4>
        <div class="no-print d-flex gap-2">
            <button type="button" class="btn btn-outline-secondary" onclick="window.print()">প্রিন্ট</button>
            <button type="button" class="btn btn-outline-primary" id="downloadPdfBtn">PDF ডাউনলোড</button>
        </div>
    </div>

    <?php if ($error): ?><div class="alert alert-danger no-print"><?php echo h($error); ?></div><?php endif; ?>
    <?php if ($info): ?><div class="alert alert-success no-print"><?php echo h($info); ?></div><?php endif; ?>

    <form method="post" enctype="multipart/form-data" class="no-print" id="seatForm">
        <div class="card mb-3">
            <div class="card-body">
                <div class="row g-3 align-items-end">
                    <div class="col-md-4">
                        <label class="form-label">লেআউট মোড</label>
                        <div class="d-flex gap-3">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="mode" id="modeUniform" value="uniform" <?php echo $mode==='uniform'?'checked':''; ?>>
                                <label class="form-check-label" for="modeUniform">Uniform (Rows x Columns)</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="mode" id="modeCustom" value="custom" <?php echo $mode==='custom'?'checked':''; ?>>
                                <label class="form-check-label" for="modeCustom">Custom (0/1/2 per bench)</label>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-2 uniform-only <?php echo $mode==='uniform'?'':'d-none'; ?>">
                        <label class="form-label">Rows</label>
                        <input type="number" class="form-control" name="rows" value="<?php echo (int)$rows; ?>" min="1" max="50" />
                    </div>
                    <div class="col-md-2 uniform-only <?php echo $mode==='uniform'?'':'d-none'; ?>">
                        <label class="form-label">Columns</label>
                        <input type="number" class="form-control" name="cols" value="<?php echo (int)$cols; ?>" min="1" max="50" />
                    </div>
                    <div class="col-md-4 uniform-only <?php echo $mode==='uniform'?'':'d-none'; ?>">
                        <label class="form-label">Bench capacity per cell</label>
                        <select class="form-select" name="bench_cap">
                            <option value="1" <?php echo $bench_cap===1?'selected':''; ?>>1 জন</option>
                            <option value="2" <?php echo $bench_cap===2?'selected':''; ?>>2 জন</option>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">সিটিং প্যাটার্ন</label>
                        <select class="form-select" name="pattern">
                            <option value="row_lr" <?php echo $pattern==='row_lr'?'selected':''; ?>>সারি (বাঁ→ডানে)</option>
                            <option value="row_rl" <?php echo $pattern==='row_rl'?'selected':''; ?>>সারি (ডানে→বাঁ)</option>
                            <option value="col_tb" <?php echo $pattern==='col_tb'?'selected':''; ?>>কলাম (উপর→নিচ)</option>
                            <option value="col_bt" <?php echo $pattern==='col_bt'?'selected':''; ?>>কলাম (নিচ→উপর)</option>
                            <option value="zigzag_row" <?php echo $pattern==='zigzag_row'?'selected':''; ?>>ঝিকঝাক (সারি ভিত্তিক)</option>
                            <option value="zigzag_col" <?php echo $pattern==='zigzag_col'?'selected':''; ?>>ঝিকঝাক (কলাম ভিত্তিক)</option>
                            <option value="diag_tl" <?php echo $pattern==='diag_tl'?'selected':''; ?>>ডায়াগনাল (বাম-উপর → ডান-নিচ)</option>
                            <option value="diag_tr" <?php echo $pattern==='diag_tr'?'selected':''; ?>>কুনাকুনি (ডান-উপর → বাম-নিচ)</option>
                            <option value="spiral" <?php echo $pattern==='spiral'?'selected':''; ?>>স্পাইরাল (বাহির→ভিতর)</option>
                        </select>
                        <div class="help-text mt-1">রোল বসানোর ক্রম এই প্যাটার্ন অনুযায়ী চলবে।</div>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">শিরোনাম</label>
                        <input type="text" class="form-control" name="custom_heading" value="<?php echo h($custom_heading); ?>" placeholder="সীট প্ল্যান - বার্ষিক পরীক্ষা" />
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">বিষয়</label>
                        <input type="text" class="form-control" name="subject_name" value="<?php echo h($subject_name); ?>" placeholder="যেমন: গণিত" />
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">রুম নং</label>
                        <input type="text" class="form-control" name="room_no" value="<?php echo h($room_no); ?>" placeholder="যেমন: 101" />
                    </div>

                    <div class="col-12 custom-only <?php echo $mode==='custom'?'':'d-none'; ?>">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">কাস্টম লেআউট (প্রতি লাইনে একটি সারি, কমা দিয়ে 0/1/2)</label>
                                <textarea class="form-control" name="layout_text" id="layout_text" rows="7" placeholder="উদাহরণ:\n2,2,1,0,2\n2,2,2,2,2,2\n1,2,1,2\n..."><?php echo h($layout_text !== '' ? $layout_text : ( $mode==='custom' ? implode("\n", array_map(function($r){return implode(',', $r);}, $initial_layout_for_editor)) : '' )); ?></textarea>
                                <div class="help-text mt-1">- 0 = বেঞ্চ অফ/ফাঁকা, 1 = একজন, 2 = দুইজন।<br>- সারি ভেদে বেঞ্চ সংখ্যা বদলাতে পারে (যেমন কোন সারিতে ৫টি, কোন সারিতে ৬টি)।</div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">গ্রাফিক এডিটার</label>
                                <div class="d-flex justify-content-between mb-2">
                                    <div class="btn-group btn-group-sm" role="group">
                                        <button type="button" class="btn btn-outline-secondary" id="addRowBtn">রো যোগ</button>
                                        <button type="button" class="btn btn-outline-secondary" id="importLayoutBtn">টেক্সট থেকে লোড</button>
                                        <button type="button" class="btn btn-outline-danger" id="clearLayoutBtn">ফাঁকা করুন</button>
                                    </div>
                                    <div class="help-text">বেঞ্চে ক্লিক করলে 0→1→2 চক্রে বদলাবে</div>
                                </div>
                                <div id="layoutEditor"></div>
                                <div class="help-text mt-2">প্রতি রো-তে +Bench/−Bench এবং রো ডিলিট করতে পারবেন।</div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">লেআউট ফাইল (CSV/TXT)</label>
                                <input type="file" class="form-control" name="layout_file" accept=".csv,.txt" />
                                <div class="form-text">Format: প্রতি লাইনে 0/1/2 কমা-সেপারেটেড</div>
                            </div>
                            <div class="col-md-6 d-flex align-items-end">
                                <button type="submit" name="use_layout_file" class="btn btn-outline-secondary">লেআউট ফাইল প্রয়োগ</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-3">
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">রোল ফাইল আপলোড (CSV/TXT, এক কলাম)</label>
                        <input type="file" class="form-control" name="rolls_file" accept=".csv,.txt" />
                    </div>
                    <div class="col-12">
                        <label class="form-label">অথবা সরাসরি এখানে পেস্ট করুন (লাইন প্রতি একটি রোল)</label>
                        <textarea class="form-control" name="rolls_text" rows="5" placeholder="উদাহরণ:\n1001\n1002\n1003\n..."><?php echo isset($_POST['rolls_text']) ? h($_POST['rolls_text']) : ''; ?></textarea>
                    </div>
                    <div class="col-12 d-flex gap-2">
                        <button type="submit" name="generate" class="btn btn-primary">জেনারেট</button>
                        <button type="submit" name="upload" class="btn btnSUCCESS">রোল আপলোড ও জেনারেট</button>
                        <a href="<?php echo h($_SERVER['PHP_SELF']); ?>" class="btn btn-outline-danger">রিসেট</a>
                    </div>
                    <div class="col-12 text-muted small">
                        - আপলোড করা রোলের ক্রমানুসার বজায় থাকবে। সিট বসানো হবে নির্বাচিত প্যাটার্ন অনুযায়ী।<br/>
                        - কাস্টম মোডে প্রতিটি বেঞ্চে 0/1/2 সিট ধরা হবে; 0 হলে বেঞ্চ দেখাবে কিন্তু সিট থাকবে না।
                    </div>
                </div>
            </div>
        </div>
    </form>

    <hr class="my-3"/>

    <div id="seatPlanWrapper">
        <?php if ($total_rolls === 0): ?>
            <div class="alert alert-info">রোল লিস্ট আপলোড/পেস্ট করে জেনারেট করুন।</div>
        <?php else: ?>
            <?php $globalIdx = 0; for ($p=0; $p<$pages; $p++): ?>
            <?php
                // Build per-page assignments map: [r][c][pos] => roll|null
                $pageAssign = [];
                foreach ($slots_order as $slot) {
                    [$r,$c,$pos] = $slot;
                    $val = ($globalIdx < $total_rolls) ? $rolls[$globalIdx++] : null;
                    if (!isset($pageAssign[$r])) $pageAssign[$r] = [];
                    if (!isset($pageAssign[$r][$c])) $pageAssign[$r][$c] = [];
                    $pageAssign[$r][$c][$pos] = $val;
                }
                $heading_text = $custom_heading !== '' ? $custom_heading : 'সীট প্ল্যান';
                $pattern_text = isset($pattern_labels[$pattern]) ? $pattern_labels[$pattern] : $pattern;
            ?>
            <div class="page" data-page-index="<?php echo $p+1; ?>">
                <div class="d-flex flex-column gap-1">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="m-0"><?php echo h($heading_text); ?></h5>
                        <div class="text-muted small">পেজ: <?php echo ($p+1).'/'.$pages; ?></div>
                    </div>
                    <div class="d-flex justify-content-between flex-wrap small text-muted">
                        <div>
                            <?php if ($subject_name!==''): ?>বিষয়: <?php echo h($subject_name); ?><?php endif; ?>
                            <?php if ($room_no!==''): ?><?php echo ($subject_name!=='') ? ' | ' : ''; ?>রুম: <?php echo h($room_no); ?><?php endif; ?>
                            <?php if ($pattern_text!==''): ?><?php echo (($subject_name!=='') || ($room_no!=='') ) ? ' | ' : ''; ?>প্যাটার্ন: <?php echo h($pattern_text); ?><?php endif; ?>
                        </div>
                        <div>মোট রোল: <?php echo (int)$total_rolls; ?></div>
                    </div>
                </div>
                <div class="mt-2">
                    <?php foreach ($layout_matrix as $rIndex => $rowBenches): ?>
                        <?php $benchCount = count($rowBenches); ?>
                        <div class="row-line" style="grid-template-columns: repeat(<?php echo (int)$benchCount; ?>, 1fr);">
                            <?php foreach ($rowBenches as $bIndex => $cap): ?>
                                <?php $cap = (int)$cap; if ($cap < 0) $cap = 0; if ($cap > 2) $cap = 2; ?>
                                <div class="bench">
                                    <div class="bench-head"><span>Row <?php echo $rIndex+1; ?>, Bench <?php echo $bIndex+1; ?></span><span><?php echo $cap===0?'off':($cap===1?'1-seater':'2-seater'); ?></span></div>
                                    <div class="seats">
                                        <?php if ($cap === 0): ?>
                                            <div class="seat-box seat-empty">ফাঁকা</div>
                                        <?php else: ?>
                                            <?php for ($pos=1; $pos<=$cap; $pos++): ?>
                                                <?php $val = $pageAssign[$rIndex][$bIndex][$pos] ?? null; ?>
                                                <div class="seat-box <?php echo $val===null?'seat-empty':''; ?>"><?php echo $val===null?'খালি':h($val); ?></div>
                                            <?php endfor; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endfor; ?>
        <?php endif; ?>
    </div>
</div>

<script>
    // Toggle sections based on mode radio
    (function(){
        function syncMode(){
            var mode = document.querySelector('input[name="mode"]:checked')?.value || 'uniform';
            document.querySelectorAll('.uniform-only').forEach(el=>{ el.classList.toggle('d-none', mode !== 'uniform'); });
            document.querySelectorAll('.custom-only').forEach(el=>{ el.classList.toggle('d-none', mode !== 'custom'); });
        }
        document.querySelectorAll('input[name="mode"]').forEach(r=>{ r.addEventListener('change', syncMode); });
        syncMode();
    })();

    // Graphic layout editor for custom mode
    (function(){
        const layoutText = document.getElementById('layout_text');
        const editorRoot = document.getElementById('layoutEditor');
        if (!editorRoot) return;

        // Initial layout from server
        const initial = <?php echo json_encode($initial_layout_for_editor, JSON_UNESCAPED_UNICODE); ?>;
        let layout = Array.isArray(initial) && initial.length ? initial.map(r => r.slice()) : [[2,2,2,2,2],[2,2,2,2,2]];

        function clamp(v){ v = parseInt(v||0); if (v<0) v=0; if (v>2) v=2; return v; }
        function nextCap(v){ v = clamp(v); return (v+1) % 3; }

        function render(){
            editorRoot.innerHTML = '';
            layout.forEach((row, rIdx) => {
                const rowEl = document.createElement('div');
                rowEl.className = 'editor-row';

                const head = document.createElement('div');
                head.className = 'editor-row-head';
                head.innerHTML = `<strong>Row ${rIdx+1}</strong>
                    <div class=\"btn-group btn-group-sm\" role=\"group\">
                        <button type=\"button\" class=\"btn btn-light\" data-act=\"add-bench\" data-r=\"${rIdx}\">+ Bench</button>
                        <button type=\"button\" class=\"btn btn-light\" data-act=\"remove-bench\" data-r=\"${rIdx}\">- Bench</button>
                        <button type=\"button\" class=\"btn btn-outline-danger\" data-act=\"remove-row\" data-r=\"${rIdx}\">রো ডিলিট</button>
                    </div>`;

                const benches = document.createElement('div');
                benches.className = 'editor-benches';
                row.forEach((cap, bIdx) => {
                    cap = clamp(cap);
                    const b = document.createElement('div');
                    b.className = 'bench-btn cap-' + cap;
                    b.textContent = String(cap);
                    b.dataset.r = rIdx;
                    b.dataset.b = bIdx;
                    b.title = 'Click to toggle 0→1→2';
                    b.addEventListener('click', () => {
                        const r = Number(b.dataset.r), c = Number(b.dataset.b);
                        layout[r][c] = nextCap(layout[r][c]);
                        syncTextarea();
                        render();
                    });
                    benches.appendChild(b);
                });

                rowEl.appendChild(head);
                rowEl.appendChild(benches);
                editorRoot.appendChild(rowEl);
            });
        }

        function syncTextarea(){
            const lines = layout.map(r => r.map(clamp).join(','));
            layoutText.value = lines.join('\n');
        }

        // Row/bench operations via event delegation
        editorRoot.addEventListener('click', (e) => {
            const btn = e.target.closest('button');
            if (!btn) return;
            const act = btn.dataset.act;
            const r = parseInt(btn.dataset.r);
            if (Number.isNaN(r)) return;
            if (act === 'add-bench') {
                layout[r].push(2);
            } else if (act === 'remove-bench') {
                if (layout[r].length > 0) layout[r].pop();
            } else if (act === 'remove-row') {
                layout.splice(r, 1);
            }
            if (layout.length === 0) layout.push([2,2,2,2,2]);
            syncTextarea();
            render();
        });

        // Toolbar buttons
        document.getElementById('addRowBtn')?.addEventListener('click', () => { layout.push([2,2,2,2,2]); syncTextarea(); render(); });
        document.getElementById('clearLayoutBtn')?.addEventListener('click', () => { layout = []; syncTextarea(); render(); });
        document.getElementById('importLayoutBtn')?.addEventListener('click', () => {
            const text = layoutText.value || '';
            const rows = text.split(/\r?\n/).map(l => l.trim()).filter(Boolean).map(l => l.split(/\s*,\s*/).map(v => { v=parseInt(v||0); if (v<0)v=0; if (v>2)v=2; return v; }));
            layout = rows.length ? rows : [[2,2,2,2,2]];
            syncTextarea();
            render();
        });

        // Ensure textarea always reflects current editor before submit
        document.getElementById('seatForm')?.addEventListener('submit', () => { syncTextarea(); });

        // Initial paint
        syncTextarea(); render();
    })();
</script>
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>
<script>
    // Download visible pages as a single PDF using html2canvas + jsPDF
    document.getElementById('downloadPdfBtn').addEventListener('click', async function(){
        const { jsPDF } = window.jspdf;
        const wrapper = document.getElementById('seatPlanWrapper');
        const pages = wrapper.querySelectorAll('.page');
        if (pages.length === 0) return;
        const pdf = new jsPDF('p', 'mm', 'a4');
        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();
        for (let i = 0; i < pages.length; i++) {
            const page = pages[i];
            const canvas = await html2canvas(page, { scale: 2 });
            const imgData = canvas.toDataURL('image/png');
            const imgProps = { w: pageWidth, h: (canvas.height * pageWidth) / canvas.width };
            if (i > 0) pdf.addPage();
            pdf.addImage(imgData, 'PNG', 0, 0, imgProps.w, Math.min(imgProps.h, pageHeight));
        }
        pdf.save('seat_plan.pdf');
    });
</script>
</body>
</html>