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

// Access control: admin or teacher only
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

// Flash helpers
function set_flash($type, $msg) { $_SESSION['flash'] = ['type'=>$type, 'msg'=>$msg]; }
function get_flash() { $f = $_SESSION['flash'] ?? null; unset($_SESSION['flash']); return $f; }

// Utility: count teachers already assigned in a room on a date for current exam
function countInRoom($roomId, $date) {
    if (!$roomId) return 0;
    global $pdo, $selected_exam_id;
    $s = $pdo->prepare("SELECT COUNT(*) FROM exam_room_duties WHERE exam_id=? AND room_id=? AND (duty_date <=> ?)");
    $s->execute([$selected_exam_id, $roomId, $date]);
    return (int)$s->fetchColumn();
}

// Config
$MAX_CONCURRENT_DUTIES = 1; // per teacher per slot window
$MORNING_START = '09:00:00';
$MORNING_END   = '12:00:00';
$AFTERNOON_START = '13:00:00';
$AFTERNOON_END   = '16:00:00';

// Ensure required tables exist (idempotent)
try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS exam_rooms (
            id INT AUTO_INCREMENT PRIMARY KEY,
            exam_id INT NOT NULL,
            room_name VARCHAR(100) NOT NULL,
            capacity INT DEFAULT 0,
            max_teachers INT DEFAULT NULL,
            building VARCHAR(100),
            floor VARCHAR(50),
            notes TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (exam_id) REFERENCES exams(id) ON DELETE CASCADE,
            UNIQUE KEY uniq_exam_room (exam_id, room_name)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
    // Add max_teachers column if it doesn't exist
    $stmt = $pdo->query("SHOW COLUMNS FROM exam_rooms LIKE 'max_teachers'");
    $column_exists = $stmt->rowCount() > 0;
    if (!$column_exists) {
        $pdo->exec("ALTER TABLE exam_rooms ADD COLUMN max_teachers INT DEFAULT NULL");
    }

    $pdo->exec("
        CREATE TABLE IF NOT EXISTS exam_room_duties (
            id INT AUTO_INCREMENT PRIMARY KEY,
            exam_id INT NOT NULL,
            room_id INT NULL,
            teacher_id INT NOT NULL,
            duty_role ENUM('invigilator','reserve','assistant') DEFAULT 'invigilator',
            duty_date DATE,
            start_time TIME,
            end_time TIME,
            order_index INT DEFAULT 0,
            remarks TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (exam_id) REFERENCES exams(id) ON DELETE CASCADE,
            FOREIGN KEY (room_id) REFERENCES exam_rooms(id) ON DELETE CASCADE,
            FOREIGN KEY (teacher_id) REFERENCES teachers(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
    // Add order_index column if it doesn't exist
    $stmt = $pdo->query("SHOW COLUMNS FROM exam_room_duties LIKE 'order_index'");
    $column_exists = $stmt->rowCount() > 0;
    if (!$column_exists) {
        $pdo->exec("ALTER TABLE exam_room_duties ADD COLUMN order_index INT DEFAULT 0");
    }
    $pdo->exec("ALTER TABLE exam_room_duties MODIFY room_id INT NULL");
} catch (Exception $e) {
    set_flash('danger', 'টেবিল প্রস্তুত করতে সমস্যা: '.$e->getMessage());
}

// Fetch dropdown data
$exams = $pdo->query("SELECT id, name, exam_date, start_time, end_time FROM exams ORDER BY exam_date DESC, id DESC")->fetchAll();
$teachers = $pdo->query("SELECT id, first_name, last_name, designation, employee_id FROM teachers WHERE status = 'active' ORDER BY first_name, last_name")->fetchAll();

// helpers
define('TAB_BULK', 'bulk_matrix');
define('TAB_TEACHER', 'teacher_dates');
define('TAB_ATTEND', 'attendance_sheet');
define('TAB_ROOMS', 'rooms_setup');
function tName($t) { return trim(($t['first_name'] ?? '').' '.($t['last_name'] ?? '')); }
function redirect_to($url) { header("Location: $url"); exit; }

// Selected exam
$selected_exam_id = isset($_GET['exam_id']) ? (int)$_GET['exam_id'] : 0;
if (!$selected_exam_id && !empty($exams)) $selected_exam_id = (int)$exams[0]['id'];
$current_exam = null; foreach ($exams as $ex) { if ((int)$ex['id'] === $selected_exam_id) { $current_exam=$ex; break; } }

// Allowed dates from exam_subjects
$allowed_dates = [];
if ($selected_exam_id) {
    $stmt = $pdo->prepare("SELECT DISTINCT exam_date FROM exam_subjects WHERE exam_id = ? AND exam_date IS NOT NULL ORDER BY exam_date");
    $stmt->execute([$selected_exam_id]);
    $allowed_dates = array_map(function($r){ return $r['exam_date']; }, $stmt->fetchAll());
}

// Selected tab/date/teacher
$tab = $_GET['tab'] ?? TAB_BULK;
$selected_date = $_GET['date'] ?? '';
if (!empty($allowed_dates) && ($selected_date === '' || !in_array($selected_date, $allowed_dates, true))) {
    $preferred = $current_exam['exam_date'] ?? '';
    $selected_date = in_array($preferred, $allowed_dates, true) ? $preferred : $allowed_dates[0];
}
$current_teacher_id = isset($_GET['teacher_id']) ? (int)$_GET['teacher_id'] : 0;

// Rooms for exam
$rooms = [];
if ($selected_exam_id) {
    $stmt = $pdo->prepare("SELECT * FROM exam_rooms WHERE exam_id = ? ORDER BY room_name");
    $stmt->execute([$selected_exam_id]);
    $rooms = $stmt->fetchAll();
}

// Build duty state map for fast UI prefill
$slotState = ['m'=>[], 'a'=>[]];
if ($selected_exam_id && !empty($allowed_dates)) {
    $in = implode(',', array_fill(0, count($allowed_dates), '?'));
    $params = array_merge([$selected_exam_id], $allowed_dates);
    $stmt = $pdo->prepare("SELECT teacher_id, duty_date, start_time, end_time, room_id FROM exam_room_duties WHERE exam_id = ? AND duty_date IN ($in)");
    $stmt->execute($params);
    while ($row = $stmt->fetch()) {
        $tid = (int)$row['teacher_id'];
        $d = $row['duty_date'];
        $st = $row['start_time'] ?: '00:00:00';
        $en = $row['end_time'] ?: '23:59:59';
        // Overlap with morning window
        $overlapM = !($en <= $MORNING_START || $st >= $MORNING_END);
        if ($overlapM) {
            if (!isset($slotState['m'][$tid])) $slotState['m'][$tid] = [];
            $slotState['m'][$tid][$d] = $row['room_id'];
        }
        // Overlap with afternoon window
        $overlapA = !($en <= $AFTERNOON_START || $st >= $AFTERNOON_END);
        if ($overlapA) {
            if (!isset($slotState['a'][$tid])) $slotState['a'][$tid] = [];
            $slotState['a'][$tid][$d] = $row['room_id'];
        }
    }
}

// Save handlers
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $selected_exam_id) {
    $action = $_POST['action'] ?? '';
    // persist selected date on post, if provided
    if (!empty($_POST['date'])) { $selected_date = $_POST['date']; }

    try {
        if ($action === 'bulk_save') {
            $duty_role = $_POST['duty_role'] ?? 'invigilator';
            $dates = isset($_POST['dates']) && is_array($_POST['dates']) ? array_values(array_unique($_POST['dates'])) : [];
            $sel_m = isset($_POST['sel_m']) && is_array($_POST['sel_m']) ? $_POST['sel_m'] : [];
            $sel_a = isset($_POST['sel_a']) && is_array($_POST['sel_a']) ? $_POST['sel_a'] : [];
            $rooms_m = isset($_POST['rooms_m']) && is_array($_POST['rooms_m']) ? $_POST['rooms_m'] : [];
            $rooms_a = isset($_POST['rooms_a']) && is_array($_POST['rooms_a']) ? $_POST['rooms_a'] : [];

            if (empty($allowed_dates)) throw new Exception('রুটিনে কোনো তারিখ নেই');
            $valid_dates = array_values(array_intersect($dates, $allowed_dates));

            $pdo->beginTransaction();

            // capacity cache
            $roomLimitCache = [];
            $countInRoom = function($roomId, $date) use ($pdo, $selected_exam_id) {
                $s=$pdo->prepare("SELECT COUNT(*) FROM exam_room_duties WHERE exam_id=? AND room_id=? AND (duty_date <=> ?)");
                $s->execute([$selected_exam_id, $roomId, $date]);
                return (int)$s->fetchColumn();
            };

            // helpers
            $existsSlot = function($tid, $date, $slot) use ($pdo, $selected_exam_id, $MORNING_START, $MORNING_END, $AFTERNOON_START, $AFTERNOON_END) {
                $start = $slot==='m' ? $MORNING_START : $AFTERNOON_START;
                $end   = $slot==='m' ? $MORNING_END   : $AFTERNOON_END;
                $s=$pdo->prepare("SELECT id, room_id FROM exam_room_duties WHERE exam_id=? AND teacher_id=? AND (duty_date <=> ?) AND (COALESCE(start_time,'') <=> ?) AND (COALESCE(end_time,'') <=> ?) LIMIT 1");
                $s->execute([$selected_exam_id, $tid, $date, $start, $end]);
                return $s->fetch();
            };
            $findOverlapSlot = function($tid, $date, $start, $end) use ($pdo, $selected_exam_id) {
                $s=$pdo->prepare("SELECT id, room_id FROM exam_room_duties WHERE exam_id=? AND teacher_id=? AND (duty_date <=> ?) AND NOT (COALESCE(end_time,'23:59:59') <= ? OR COALESCE(start_time,'00:00:00') >= ?) LIMIT 1");
                $s->execute([$selected_exam_id, $tid, $date, $start, $end]);
                return $s->fetch();
            };
            $deleteSlot = function($tid, $date, $slot) use ($pdo, $selected_exam_id, $MORNING_START, $MORNING_END, $AFTERNOON_START, $AFTERNOON_END) {
                $start = $slot==='m' ? $MORNING_START : $AFTERNOON_START;
                $end   = $slot==='m' ? $MORNING_END   : $AFTERNOON_END;
                $s=$pdo->prepare("DELETE FROM exam_room_duties WHERE exam_id=? AND teacher_id=? AND (duty_date <=> ?) AND (COALESCE(start_time,'') <=> ?) AND (COALESCE(end_time,'') <=> ?)");
                $s->execute([$selected_exam_id, $tid, $date, $start, $end]);
            };
            $overlapCount = function($tid, $date, $start, $end) use ($pdo, $selected_exam_id) {
                $s=$pdo->prepare("SELECT COUNT(*) FROM exam_room_duties WHERE exam_id=? AND teacher_id=? AND (duty_date <=> ?) AND NOT (COALESCE(end_time,'23:59:59') <= ? OR COALESCE(start_time,'00:00:00') >= ?)");
                $s->execute([$selected_exam_id, $tid, $date, $start, $end]);
                return (int)$s->fetchColumn();
            };

            foreach ($teachers as $t) {
                $tid = (int)$t['id'];
                foreach ($valid_dates as $d) {
                    // Morning
                    if (isset($sel_m[$tid][$d])) {
                        $rid = isset($rooms_m[$tid][$d]) && $_POST['rooms_m'][$tid][$d] !== '' ? (int)$_rooms_m[$tid][$d] : null;
                        $start=$MORNING_START; $end=$MORNING_END;
                        $existing=$existsSlot($tid,$d,'m');
                        if ($existing) {
                            // update room if changed and capacity allows; room optional
                            $newRoom = $rid;
                            if ($newRoom) {
                                if (!array_key_exists($newRoom, $roomLimitCache)) {
                                    $s=$pdo->prepare("SELECT max_teachers FROM exam_rooms WHERE id=? AND exam_id=?");
                                    $s->execute([$newRoom, $selected_exam_id]);
                                    $roomLimitCache[$newRoom] = $s->fetchColumn();
                                }
                                $limit=$roomLimitCache[$newRoom];
                                if ($limit !== false && $limit !== null) {
                                    $inRoom=countInRoom($newRoom,$d);
                                    if ($inRoom >= (int)$limit) { $newRoom = null; }
                                }
                            }
                            $s=$pdo->prepare("UPDATE exam_room_duties SET room_id = ? WHERE id = ?");
                            $s->execute([$newRoom, $existing['id']]);
                        } else {
                            // If any overlapping duty exists for that date-window, update it to align with slot; else insert new
                            $over = $findOverlapSlot($tid, $d, $start, $end);
                            if ($over) {
                                // Snap to slot window and update room
                                $newRoom = $rid;
                                if ($newRoom) {
                                    if (!array_key_exists($newRoom, $roomLimitCache)) {
                                        $s=$pdo->prepare("SELECT max_teachers FROM exam_rooms WHERE id=? AND exam_id=?");
                                        $s->execute([$newRoom, $selected_exam_id]);
                                        $roomLimitCache[$newRoom] = $s->fetchColumn();
                                    }
                                    $limit=$roomLimitCache[$newRoom];
                                    if ($limit !== false && $limit !== null) {
                                        $inRoom=countInRoom($newRoom,$d);
                                        if ($inRoom >= (int)$limit) { $newRoom = null; }
                                    }
                                }
                                $s=$pdo->prepare("UPDATE exam_room_duties SET start_time=?, end_time=?, room_id=? WHERE id=?");
                                $s->execute([$start, $end, $newRoom, $over['id']]);
                            } else {
                                // create if no overlap beyond limit
                                if ($overlapCount($tid,$d,$start,$end) < $MAX_CONCURRENT_DUTIES) {
                                    // order index within room if any
                                    $order=0; if ($rid) { $s=$pdo->prepare("SELECT COALESCE(MAX(order_index), -1) + 1 FROM exam_room_duties WHERE exam_id=? AND room_id=?"); $s->execute([$selected_exam_id,$rid]); $order=(int)$s->fetchColumn(); }
                                    // capacity check
                                    if ($rid) {
                                        if (!array_key_exists($rid, $roomLimitCache)) {
                                            $s=$pdo->prepare("SELECT max_teachers FROM exam_rooms WHERE id=? AND exam_id=?");
                                            $s->execute([$rid, $selected_exam_id]);
                                            $roomLimitCache[$rid] = $s->fetchColumn();
                                        }
                                        $limit=$roomLimitCache[$rid];
                                        if ($limit !== false && $limit !== null) {
                                            $inRoom=countInRoom($rid,$d);
                                            if ($inRoom >= (int)$limit) { $rid = null; }
                                        }
                                    }
                                    $s=$pdo->prepare("INSERT INTO exam_room_duties (exam_id, room_id, teacher_id, duty_role, duty_date, start_time, end_time, order_index) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                                    $s->execute([$selected_exam_id, $rid, $tid, $duty_role, $d, $start, $end, $order]);
                                }
                            }
                        }
                    } else {
                        // Unchecked => delete slot
                        $deleteSlot($tid,$d,'m');
                    }

                    // Afternoon
                    if (isset($sel_a[$tid][$d])) {
                        $rid = isset($rooms_a[$tid][$d]) && $_POST['rooms_a'][$tid][$d] !== '' ? (int)$rooms_a[$tid][$d] : null;
                        $start=$AFTERNOON_START; $end=$AFTERNOON_END;
                        $existing=$existsSlot($tid,$d,'a');
                        if ($existing) {
                            $newRoom = $rid;
                            if ($newRoom) {
                                if (!array_key_exists($newRoom, $roomLimitCache)) {
                                    $s=$pdo->prepare("SELECT max_teachers FROM exam_rooms WHERE id=? AND exam_id=?");
                                    $s->execute([$newRoom, $selected_exam_id]);
                                    $roomLimitCache[$newRoom] = $s->fetchColumn();
                                }
                                $limit=$roomLimitCache[$newRoom];
                                if ($limit !== false && $limit !== null) {
                                    $inRoom=countInRoom($newRoom,$d);
                                    if ($inRoom >= (int)$limit) { $newRoom = null; }
                                }
                            }
                            $s=$pdo->prepare("UPDATE exam_room_duties SET room_id = ? WHERE id = ?");
                            $s->execute([$newRoom, $existing['id']]);
                        } else {
                            // If overlapping duty exists for this window, snap-update; else insert
                            $over = $findOverlapSlot($tid, $d, $start, $end);
                            if ($over) {
                                $newRoom = $rid;
                                if ($newRoom) {
                                    if (!array_key_exists($newRoom, $roomLimitCache)) {
                                        $s=$pdo->prepare("SELECT max_teachers FROM exam_rooms WHERE id=? AND exam_id=?");
                                        $s->execute([$newRoom, $selected_exam_id]);
                                        $roomLimitCache[$newRoom] = $s->fetchColumn();
                                    }
                                    $limit=$roomLimitCache[$newRoom];
                                    if ($limit !== false && $limit !== null) {
                                        $inRoom=countInRoom($newRoom,$d);
                                        if ($inRoom >= (int)$limit) { $newRoom = null; }
                                    }
                                }
                                $s=$pdo->prepare("UPDATE exam_room_duties SET start_time=?, end_time=?, room_id=? WHERE id=?");
                                $s->execute([$start, $end, $newRoom, $over['id']]);
                            } else {
                                if ($overlapCount($tid,$d,$start,$end) < $MAX_CONCURRENT_DUTIES) {
                                    $order=0; if ($rid) { $s=$pdo->prepare("SELECT COALESCE(MAX(order_index), -1) + 1 FROM exam_room_duties WHERE exam_id=? AND room_id=?"); $s->execute([$selected_exam_id,$rid]); $order=(int)$s->fetchColumn(); }
                                    if ($rid) {
                                        if (!array_key_exists($rid, $roomLimitCache)) {
                                            $s=$pdo->prepare("SELECT max_teachers FROM exam_rooms WHERE id=? AND exam_id=?");
                                            $s->execute([$rid, $selected_exam_id]);
                                            $roomLimitCache[$rid] = $s->fetchColumn();
                                        }
                                        $limit=$roomLimitCache[$rid];
                                        if ($limit !== false && $limit !== null) {
                                            $inRoom=countInRoom($rid,$d);
                                            if ($inRoom >= (int)$limit) { $rid = null; }
                                        }
                                    }
                                    $s=$pdo->prepare("INSERT INTO exam_room_duties (exam_id, room_id, teacher_id, duty_role, duty_date, start_time, end_time, order_index) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                                    $s->execute([$selected_exam_id, $rid, $tid, $duty_role, $d, $start, $end, $order]);
                                }
                            }
                        }
                    } else {
                        $deleteSlot($tid,$d,'a');
                    }
                }
            }

            $pdo->commit();
            // Show quick snapshot counts
            $snap = $pdo->prepare("SELECT duty_date, start_time, end_time, COUNT(*) c FROM exam_room_duties WHERE exam_id=? GROUP BY duty_date, start_time, end_time ORDER BY duty_date, start_time");
            $snap->execute([$selected_exam_id]);
            $rows = $snap->fetchAll();
            $parts = [];
            foreach ($rows as $r) { $parts[] = ($r['duty_date']?:'') . ' ' . ($r['start_time']?:'') . '-' . ($r['end_time']?:'') . ': '.$r['c']; }
            set_flash('success', 'বাল্ক ডিউটি সংরক্ষিত হয়েছে · ' . implode(' | ', $parts));
            redirect_to('room_duty.php?exam_id='.(int)$selected_exam_id.'&tab='.TAB_BULK.'&date='.urlencode($selected_date).'&saved=1');
        }
        elseif ($action === 'save_order') {
            // AJAX: save order within a room for a given slot and date
            $room_id = (int)($_POST['room_id'] ?? 0);
            $slot = $_POST['slot'] ?? '';
            $date = $_POST['date'] ?? '';
            $ids = $_POST['ids'] ?? [];
            if (is_string($ids)) {
                $decoded = json_decode($ids, true);
                if (is_array($decoded)) $ids = $decoded; else $ids = [];
            }
            try {
                if (!$selected_exam_id) throw new Exception('invalid exam');
                if (!$room_id) throw new Exception('invalid room');
                if (!in_array($date, $allowed_dates, true)) throw new Exception('invalid date');
                if (!in_array($slot, ['m','a'], true)) throw new Exception('invalid slot');
                if (!is_array($ids)) throw new Exception('invalid ids');
                $start = $slot==='m' ? $MORNING_START : $AFTERNOON_START;
                $end   = $slot==='m' ? $MORNING_END   : $AFTERNOON_END;
                $pdo->beginTransaction();
                $u = $pdo->prepare("UPDATE exam_room_duties SET order_index=? WHERE id=? AND exam_id=? AND room_id=? AND (duty_date <=> ?) AND (COALESCE(start_time,'') <=> ?) AND (COALESCE(end_time,'') <=> ?)");
                $i = 0;
                foreach ($ids as $id) {
                    $id = (int)$id;
                    $u->execute([$i, $id, $selected_exam_id, $room_id, $date, $start, $end]);
                    $i++;
                }
                $pdo->commit();
                header('Content-Type: application/json');
                echo json_encode(['ok'=>true]);
                exit;
            } catch (Throwable $e) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                header('Content-Type: application/json');
                http_response_code(400);
                echo json_encode(['ok'=>false, 'error'=>$e->getMessage()]);
                exit;
            }
        }
        elseif ($action === 'room_create') {
            // Create or update exam rooms
            $names = isset($_POST['room_name']) && is_array($_POST['room_name']) ? $_POST['room_name'] : [];
            $caps  = isset($_POST['capacity']) && is_array($_POST['capacity']) ? $_POST['capacity'] : [];
            $maxs  = isset($_POST['max_teachers']) && is_array($_POST['max_teachers']) ? $_POST['max_teachers'] : [];
            $ids   = isset($_POST['room_id']) && is_array($_POST['room_id']) ? $_POST['room_id'] : [];
            if (!$selected_exam_id) throw new Exception('পরীক্ষা নির্বাচন করুন');
            $pdo->beginTransaction();
            // Upsert each row
            foreach ($names as $i=>$nm) {
                $nm = trim((string)$nm);
                if ($nm==='') continue;
                $cap = isset($caps[$i]) ? (int)$caps[$i] : 0;
                $mx  = isset($maxs[$i]) && $maxs[$i]!=='' ? (int)$maxs[$i] : null;
                $rid = isset($ids[$i]) ? (int)$ids[$i] : 0;
                if ($rid>0) {
                    $u=$pdo->prepare("UPDATE exam_rooms SET room_name=?, capacity=?, max_teachers=? WHERE id=? AND exam_id=?");
                    $u->execute([$nm, $cap, $mx, $rid, $selected_exam_id]);
                } else {
                    $ins=$pdo->prepare("INSERT INTO exam_rooms (exam_id, room_name, capacity, max_teachers) VALUES (?,?,?,?)");
                    $ins->execute([$selected_exam_id, $nm, $cap, $mx]);
                }
            }
            // Optional: delete unchecked rows
            if (!empty($_POST['delete_ids'])) {
                $delIds = array_filter(array_map('intval', explode(',', $_POST['delete_ids'])));
                if ($delIds) {
                    $in = implode(',', array_fill(0, count($delIds), '?'));
                    $params = array_merge([$selected_exam_id], $delIds);
                    $pdo->prepare("DELETE FROM exam_rooms WHERE exam_id=? AND id IN ($in)")->execute($params);
                }
            }
            $pdo->commit();
            set_flash('success', 'রুম লিস্ট সংরক্ষিত হয়েছে');
            redirect_to('room_duty.php?exam_id='.(int)$selected_exam_id.'&tab='.TAB_ROOMS.'&date='.urlencode($selected_date));
        }
        elseif ($action === 'teacher_save') {
            $duty_role = $_POST['duty_role'] ?? 'invigilator';
            $teacher_id = (int)($_POST['teacher_id'] ?? 0);
            $dates = isset($_POST['dates']) && is_array($_POST['dates']) ? array_values(array_unique($_POST['dates'])) : [];
            $dates_m = isset($_POST['dates_m']) && is_array($_POST['dates_m']) ? $_POST['dates_m'] : [];
            $dates_a = isset($_POST['dates_a']) && is_array($_POST['dates_a']) ? $_POST['dates_a'] : [];
            $room_m = isset($_POST['room_m']) && is_array($_POST['room_m']) ? $_POST['room_m'] : [];
            $room_a = isset($_POST['room_a']) && is_array($_POST['room_a']) ? $_POST['room_a'] : [];
            if (!$teacher_id) throw new Exception('শিক্ষক নির্বাচন করুন');
            if (empty($allowed_dates)) throw new Exception('রুটিনে কোনো তারিখ নেই');
            $valid_dates = array_values(array_intersect($dates, $allowed_dates));

            $pdo->beginTransaction();
            $roomLimitCache = [];
            $existsSlot = function($tid, $date, $slot) use ($pdo, $selected_exam_id, $MORNING_START, $MORNING_END, $AFTERNOON_START, $AFTERNOON_END) {
                $start = $slot==='m' ? $MORNING_START : $AFTERNOON_START;
                $end   = $slot==='m' ? $MORNING_END   : $AFTERNOON_END;
                $s=$pdo->prepare("SELECT id, room_id FROM exam_room_duties WHERE exam_id=? AND teacher_id=? AND (duty_date <=> ?) AND (COALESCE(start_time,'') <=> ?) AND (COALESCE(end_time,'') <=> ?) LIMIT 1");
                $s->execute([$selected_exam_id, $tid, $date, $start, $end]);
                return $s->fetch();
            };
            $deleteSlot = function($tid, $date, $slot) use ($pdo, $selected_exam_id, $MORNING_START, $MORNING_END, $AFTERNOON_START, $AFTERNOON_END) {
                $start = $slot==='m' ? $MORNING_START : $AFTERNOON_START;
                $end   = $slot==='m' ? $MORNING_END   : $AFTERNOON_END;
                $s=$pdo->prepare("DELETE FROM exam_room_duties WHERE exam_id=? AND teacher_id=? AND (duty_date <=> ?) AND (COALESCE(start_time,'') <=> ?) AND (COALESCE(end_time,'') <=> ?)");
                $s->execute([$selected_exam_id, $tid, $date, $start, $end]);
            };
            $overlapCount = function($tid, $date, $start, $end) use ($pdo, $selected_exam_id) {
                $s=$pdo->prepare("SELECT COUNT(*) FROM exam_room_duties WHERE exam_id=? AND teacher_id=? AND (duty_date <=> ?) AND NOT (COALESCE(end_time,'23:59:59') <= ? OR COALESCE(start_time,'00:00:00') >= ?)");
                $s->execute([$selected_exam_id, $tid, $date, $start, $end]);
                return (int)$s->fetchColumn();
            };
            $countInRoom = function($roomId, $date) use ($pdo, $selected_exam_id) {
                $s=$pdo->prepare("SELECT COUNT(*) FROM exam_room_duties WHERE exam_id=? AND room_id=? AND (duty_date <=> ?)");
                $s->execute([$selected_exam_id, $roomId, $date]);
                return (int)$s->fetchColumn();
            };

            foreach ($valid_dates as $d) {
                // Morning
                if (in_array($d, $dates_m, true)) {
                    $rid = isset($room_m[$d]) && $room_m[$d] !== '' ? (int)$room_m[$d] : null;
                    $start=$MORNING_START; $end=$MORNING_END;
                    $existing=$existsSlot($teacher_id,$d,'m');
                    if ($existing) {
                        $newRoom = $rid;
                        if ($newRoom) {
                            if (!array_key_exists($newRoom, $roomLimitCache)) {
                                $s=$pdo->prepare("SELECT max_teachers FROM exam_rooms WHERE id=? AND exam_id=?");
                                $s->execute([$newRoom, $selected_exam_id]);
                                $roomLimitCache[$newRoom] = $s->fetchColumn();
                            }
                            $limit=$roomLimitCache[$newRoom];
                            if ($limit !== false && $limit !== null) {
                                $inRoom=$countInRoom($newRoom,$d);
                                if ($inRoom >= (int)$limit) { $newRoom = null; }
                            }
                        }
                        $s=$pdo->prepare("UPDATE exam_room_duties SET room_id = ? WHERE id = ?");
                        $s->execute([$newRoom, $existing['id']]);
                    } else {
                        if ($overlapCount($teacher_id,$d,$start,$end) < $MAX_CONCURRENT_DUTIES) {
                            $order=0; if ($rid) { $s=$pdo->prepare("SELECT COALESCE(MAX(order_index), -1) + 1 FROM exam_room_duties WHERE exam_id=? AND room_id=?"); $s->execute([$selected_exam_id,$rid]); $order=(int)$s->fetchColumn(); }
                            if ($rid) {
                                if (!array_key_exists($rid, $roomLimitCache)) {
                                    $s=$pdo->prepare("SELECT max_teachers FROM exam_rooms WHERE id=? AND exam_id=?");
                                    $s->execute([$rid, $selected_exam_id]);
                                    $roomLimitCache[$rid] = $s->fetchColumn();
                                }
                                $limit=$roomLimitCache[$rid];
                                if ($limit !== false && $limit !== null) {
                                    $inRoom=$countInRoom($rid,$d);
                                    if ($inRoom >= (int)$limit) { $rid = null; }
                                }
                            }
                            $s=$pdo->prepare("INSERT INTO exam_room_duties (exam_id, room_id, teacher_id, duty_role, duty_date, start_time, end_time, order_index) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                            $s->execute([$selected_exam_id, $rid, $teacher_id, $duty_role, $d, $start, $end, $order]);
                        }
                    }
                } else {
                    $deleteSlot($teacher_id,$d,'m');
                }

                // Afternoon
                if (in_array($d, $dates_a, true)) {
                    $rid = isset($room_a[$d]) && $room_a[$d] !== '' ? (int)$room_a[$d] : null;
                    $start=$AFTERNOON_START; $end=$AFTERNOON_END;
                    $existing=$existsSlot($teacher_id,$d,'a');
                    if ($existing) {
                        $newRoom = $rid;
                        if ($newRoom) {
                            if (!array_key_exists($newRoom, $roomLimitCache)) {
                                $s=$pdo->prepare("SELECT max_teachers FROM exam_rooms WHERE id=? AND exam_id=?");
                                $s->execute([$newRoom, $selected_exam_id]);
                                $roomLimitCache[$newRoom] = $s->fetchColumn();
                            }
                            $limit=$roomLimitCache[$newRoom];
                            if ($limit !== false && $limit !== null) {
                                $inRoom=$countInRoom($newRoom,$d);
                                if ($inRoom >= (int)$limit) { $newRoom = null; }
                            }
                        }
                        $s=$pdo->prepare("UPDATE exam_room_duties SET room_id = ? WHERE id = ?");
                        $s->execute([$newRoom, $existing['id']]);
                    } else {
                        if ($overlapCount($teacher_id,$d,$start,$end) < $MAX_CONCURRENT_DUTIES) {
                            $order=0; if ($rid) { $s=$pdo->prepare("SELECT COALESCE(MAX(order_index), -1) + 1 FROM exam_room_duties WHERE exam_id=? AND room_id=?"); $s->execute([$selected_exam_id,$rid]); $order=(int)$s->fetchColumn(); }
                            if ($rid) {
                                if (!array_key_exists($rid, $roomLimitCache)) {
                                    $s=$pdo->prepare("SELECT max_teachers FROM exam_rooms WHERE id=? AND exam_id=?");
                                    $s->execute([$rid, $selected_exam_id]);
                                    $roomLimitCache[$rid] = $s->fetchColumn();
                                }
                                $limit=$roomLimitCache[$rid];
                                if ($limit !== false && $limit !== null) {
                                    $inRoom=$countInRoom($rid,$d);
                                    if ($inRoom >= (int)$limit) { $rid = null; }
                                }
                            }
                            $s=$pdo->prepare("INSERT INTO exam_room_duties (exam_id, room_id, teacher_id, duty_role, duty_date, start_time, end_time, order_index) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                            $s->execute([$selected_exam_id, $rid, $teacher_id, $duty_role, $d, $start, $end, $order]);
                        }
                    }
                } else {
                    $deleteSlot($teacher_id,$d,'a');
                }
            }

            $pdo->commit();
            set_flash('success', 'ডিউটি সংরক্ষিত হয়েছে');
            redirect_to('room_duty.php?exam_id='.(int)$selected_exam_id.'&tab='.TAB_TEACHER.'&teacher_id='.(int)$teacher_id.'&date='.urlencode($selected_date).'&saved=1');
        }
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        set_flash('danger', 'ত্রুটি: '.$e->getMessage());
        redirect_to('room_duty.php?exam_id='.(int)$selected_exam_id.'&tab='.(isset($_POST['action']) && $_POST['action']==='teacher_save' ? TAB_TEACHER : TAB_BULK).'&date='.urlencode($selected_date));
    }
}

$flash = get_flash();

?>
<!DOCTYPE html>
<html lang="bn">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Exam Room Duty</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
  <link href="../assets/css/style.css" rel="stylesheet">
  <style>
    :root{--db:#0a1929;--db2:#0d2137;--db3:#11294a;--accent:#4fc3f7;--accent2:#29b6f6;--gold:#ffd700;--card-bg:#132f4c;--card-header:#1a3a5c;--text:#e0e6ed;--text-muted:#8899aa;--border:#1e4060}
    body{background:linear-gradient(135deg,#0a1929,#0d2137,#11294a);color:var(--text);font-family:'Hind Siliguri',sans-serif}
    .container-fluid{background:transparent}
    .sticky-header{position:sticky;top:0;z-index:10;background:var(--card-header)!important;color:var(--text)}
    .cell-wrap{display:flex;align-items:center;gap:.25rem;flex-wrap:wrap;justify-content:center}
    .minw-teacher{min-width:220px}
    .card{background:var(--card-bg);border:1px solid var(--border);border-radius:10px;box-shadow:0 4px 20px rgba(0,0,0,.3);overflow:hidden}
    .card-header{background:linear-gradient(135deg,var(--card-header),var(--db3));border-bottom:1px solid var(--border);color:var(--text);padding:10px 15px}
    .card-body{background:var(--card-bg)}
    .table{color:var(--text);margin-bottom:0}
    .table>:not(caption)>*>*{background:transparent;color:var(--text);border-color:var(--border)}
    .table-bordered>:not(caption)>*>*{border-color:var(--border)}
    .table-light{--bs-table-bg:var(--card-header)!important;--bs-table-color:var(--text)!important}
    .table-striped>tbody>tr:nth-of-type(odd){--bs-table-bg:rgba(255,255,255,.03)}
    .table-striped>tbody>tr:nth-of-type(even){--bs-table-bg:rgba(0,0,0,.1)}
    .table tbody tr:hover{background:rgba(79,195,247,.06)}
    .nav-tabs{border-bottom:1px solid var(--border);gap:4px}
    .nav-tabs .nav-link{background:var(--db3);border:1px solid var(--border);color:var(--text-muted);font-weight:500;border-radius:8px 8px 0 0;padding:6px 14px;transition:all .2s}
    .nav-tabs .nav-link.active{background:linear-gradient(135deg,var(--accent),var(--accent2));color:#fff;border-color:var(--accent);box-shadow:0 -2px 10px rgba(79,195,247,.3)}
    .nav-tabs .nav-link:hover:not(.active){color:var(--text);background:var(--card-header);border-color:var(--border)}
    .form-control,.form-select{background:var(--db2);border:1px solid var(--border);color:var(--text);border-radius:6px;padding:5px 10px;font-size:.82rem}
    .form-control:focus,.form-select:focus{background:var(--db3);border-color:var(--accent);box-shadow:0 0 0 3px rgba(79,195,247,.15);color:var(--text)}
    .form-check-input{background:var(--db2);border:2px solid var(--border);border-radius:4px!important}
    .form-check-input:checked{background:var(--accent);border-color:var(--accent);box-shadow:0 0 0 3px rgba(79,195,247,.2)}
    .form-check-label{color:var(--text);cursor:pointer}
    .btn-primary{background:linear-gradient(135deg,var(--accent),var(--accent2));border:none;color:#0a1929;font-weight:600;border-radius:6px;padding:5px 16px;transition:all .2s}
    .btn-primary:hover{box-shadow:0 4px 15px rgba(79,195,247,.4);transform:translateY(-1px)}
    .btn-outline-secondary{background:transparent;border:1px solid var(--border);color:var(--text-muted)}
    .btn-outline-secondary:hover{background:var(--card-header);border-color:var(--accent);color:var(--accent)}
    .btn-outline-danger{background:transparent;border:1px solid #e57373;color:#e57373}
    .btn-outline-danger:hover{background:#e57373;color:#fff}
    .alert{background:var(--card-bg);border:1px solid var(--border);border-left:4px solid;border-radius:8px;color:var(--text)}
    .alert-success{border-left-color:#4caf50}
    .alert-danger{border-left-color:#f44336}
    .alert-warning{border-left-color:#ff9800;background:var(--db3)}
    .alert-info{border-left-color:var(--accent);background:var(--db3)}
    .badge.bg-info{background:var(--accent)!important;color:#0a1929}
    .list-group{background:var(--card-bg);border:1px solid var(--border);border-radius:8px;overflow:hidden}
    .list-group-item{background:var(--card-bg);border-color:var(--border);color:var(--text);transition:all .2s}
    .list-group-item:hover{background:var(--card-header)}
    .list-group-item.active{background:linear-gradient(135deg,var(--accent),var(--accent2));border-color:var(--accent);color:#0a1929;font-weight:600}
    .list-group-item.active small{color:rgba(10,25,41,.8)!important}
    .text-muted{color:var(--text-muted)!important}
    .border{border-color:var(--border)!important}
    .border-top{border-top-color:var(--border)!important}
    .border-bottom{border-bottom-color:var(--border)!important}
    .border-start{border-left-color:var(--border)!important}
    .border-end{border-right-color:var(--border)!important}
    a:not(.btn):not(.nav-link):not(.list-group-item){color:var(--accent);transition:color .2s}
    a:not(.btn):not(.nav-link):not(.list-group-item):hover{color:#81d4fa;text-decoration:underline}
    h1,h2,h3,h4,h5,h6,.h4,.h5{color:var(--text)}
    .bg-light{background:var(--card-header)!important}
    .fw-bold,.fw-semibold{color:#fff}
    .form-text{color:var(--text-muted)!important}
    @media print {
      .no-print { display:none !important; }
      .card { border:0; }
      body{background:#fff;color:#000}
    }
    .dnd-tbody tr.dragging { opacity: .4; background:rgba(79,195,247,.1)!important; }
    .room-duty-page .form-check-input { margin-top: 0 !important; vertical-align: middle; }
    .room-duty-page .form-check-label { display: inline-flex; align-items: center; margin-bottom: 0; line-height: 1.2; }
    .room-duty-page .form-select.form-select-sm { padding-top: .25rem; padding-bottom: .25rem; line-height: 1.5; background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%234fc3f7' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E")!important;background-repeat:no-repeat!important;background-position:right .5rem center!important;background-size:12px!important;-webkit-appearance:none;appearance:none;padding-right:28px!important}
    .room-duty-page .d-flex.align-items-center.gap-1 .form-select.form-select-sm { align-self: center; }
    ::-webkit-scrollbar{width:6px;height:6px}
    ::-webkit-scrollbar-track{background:var(--db2);border-radius:3px}
    ::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}
    ::-webkit-scrollbar-thumb:hover{background:var(--accent)}
    ::selection{background:var(--accent);color:#0a1929}
  </style>
</head>
<body class="room-duty-page">
<div class="container-fluid py-3">
  <div class="d-flex align-items-center gap-2 mb-3">
    <h4 class="mb-0"><i class="fas fa-chalkboard-teacher"></i> পরীক্ষার রুম ডিউটি</h4>
    <div class="ms-auto d-flex align-items-center gap-2">
      <a href="../index.php" class="btn btn-sm btn-outline-secondary"><i class="fas fa-home"></i> হোম</a>
      <form method="get" class="d-flex gap-2 mb-0">
        <input type="hidden" name="tab" value="<?= htmlspecialchars($tab) ?>">
        <select name="exam_id" class="form-select form-select-sm w-auto" onchange="this.form.submit()">
          <?php foreach ($exams as $ex): ?>
            <option value="<?= (int)$ex['id'] ?>" <?= ((int)$ex['id']===$selected_exam_id?'selected':'') ?>><?= htmlspecialchars($ex['name']) ?></option>
          <?php endforeach; ?>
        </select>
        <select name="date" class="form-select form-select-sm w-auto" onchange="this.form.submit()">
          <?php foreach ($allowed_dates as $d): ?>
            <option value="<?= htmlspecialchars($d) ?>" <?= ($d===$selected_date?'selected':'') ?>><?= htmlspecialchars($d) ?></option>
          <?php endforeach; ?>
        </select>
      </form>
    </div>
  </div>

  <?php if ($flash): ?>
    <div class="alert alert-<?= htmlspecialchars($flash['type']) ?> py-2"><?= htmlspecialchars($flash['msg']) ?></div>
  <?php endif; ?>

  <ul class="nav nav-tabs mb-3">
    <li class="nav-item"><a class="nav-link <?= $tab===TAB_BULK?'active':'' ?>" href="?exam_id=<?= (int)$selected_exam_id ?>&tab=<?= TAB_BULK ?>&date=<?= urlencode($selected_date) ?>">সকল শিক্ষক</a></li>
    <li class="nav-item"><a class="nav-link <?= $tab===TAB_TEACHER?'active':'' ?>" href="?exam_id=<?= (int)$selected_exam_id ?>&tab=<?= TAB_TEACHER ?>&date=<?= urlencode($selected_date) ?>">শিক্ষকভিত্তিক</a></li>
    <li class="nav-item"><a class="nav-link <?= $tab===TAB_ATTEND?'active':'' ?>" href="?exam_id=<?= (int)$selected_exam_id ?>&tab=<?= TAB_ATTEND ?>&date=<?= urlencode($selected_date) ?>">হাজিরা পত্র</a></li>
    <li class="nav-item"><a class="nav-link <?= $tab===TAB_ROOMS?'active':'' ?>" href="?exam_id=<?= (int)$selected_exam_id ?>&tab=<?= TAB_ROOMS ?>&date=<?= urlencode($selected_date) ?>">রুম নং তৈরী</a></li>
    <li class="nav-item"><a class="nav-link" href="manual_room_allocation.php?exam_id=<?= (int)$selected_exam_id ?>" target="_blank">ম্যানুয়াল রুম বন্টন</a></li>
  </ul>
  <?php if (empty($allowed_dates)): ?>
    <div class="alert alert-warning">এই পরীক্ষার রুটিনে কোনো তারিখ সংযোজিত নেই।</div>
  <?php else: ?>

  <?php if ($tab === TAB_BULK): ?>
    <form method="post" class="card">
      <div class="card-header d-flex align-items-center gap-2">
        <strong><i class="fas fa-th-large"></i> সকল শিক্ষক x তারিখ</strong>
        <div class="ms-auto d-flex align-items-center gap-2">
          <label class="mb-0">ভূমিকা:</label>
          <select name="duty_role" class="form-select form-select-sm w-auto">
            <option value="invigilator">মূল</option>
            <option value="assistant">সহকারী</option>
            <option value="reserve">রিজার্ভ</option>
          </select>
          <button class="btn btn-sm btn-primary"><i class="fas fa-save"></i> সেভ</button>
        </div>
      </div>
      <div class="card-body p-2">
        <input type="hidden" name="action" value="bulk_save">
        <input type="hidden" name="date" value="<?= htmlspecialchars($selected_date) ?>">
        <?php foreach ($allowed_dates as $d): ?>
          <input type="hidden" name="dates[]" value="<?= htmlspecialchars($d) ?>">
        <?php endforeach; ?>
        <div class="table-responsive">
          <table class="table table-bordered table-sm align-middle mb-0">
            <thead class="table-light sticky-header">
              <tr>
                <th class="minw-teacher">শিক্ষক</th>
                <?php foreach ($allowed_dates as $d): ?>
                  <th class="text-center">
                    <div class="fw-semibold"><?= htmlspecialchars($d) ?></div>
                  </th>
                <?php endforeach; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($teachers as $t): $tid=(int)$t['id']; ?>
                <tr>
                  <td>
                    <strong><?= htmlspecialchars(tName($t)) ?></strong>
                    <div class="text-muted small"><?= htmlspecialchars($t['designation'] ?? '') ?><?= $t['employee_id']? ' · '.htmlspecialchars($t['employee_id']) : '' ?></div>
                  </td>
                  <?php foreach ($allowed_dates as $d): 
                    $mChecked = (isset($slotState['m'][$tid]) && array_key_exists($d, $slotState['m'][$tid]));
                    $aChecked = (isset($slotState['a'][$tid]) && array_key_exists($d, $slotState['a'][$tid]));
                    $mRoom = $mChecked ? $slotState['m'][$tid][$d] : '';
                    $aRoom = $aChecked ? $slotState['a'][$tid][$d] : '';
                  ?>
                    <td>
                      <div class="cell-wrap">
                        <div class="d-flex align-items-center gap-1">
                          <input type="checkbox" class="form-check-input" name="sel_m[<?= $tid ?>][<?= htmlspecialchars($d) ?>]" value="1" <?= $mChecked?'checked':''; ?>>
                          <label class="form-check-label small">সকাল</label>
                          <select name="rooms_m[<?= $tid ?>][<?= htmlspecialchars($d) ?>]" class="form-select form-select-sm w-auto">
                            <option value="">রুম</option>
                            <?php foreach ($rooms as $r): ?>
                              <option value="<?= (int)$r['id'] ?>" <?= ($mRoom==(int)$r['id'])?'selected':''; ?>><?= htmlspecialchars($r['room_name']) ?></option>
                            <?php endforeach; ?>
                          </select>
                        </div>
                        <div class="d-flex align-items-center gap-1">
                          <input type="checkbox" class="form-check-input" name="sel_a[<?= $tid ?>][<?= htmlspecialchars($d) ?>]" value="1" <?= $aChecked?'checked':''; ?>>
                          <label class="form-check-label small">বিকাল</label>
                          <select name="rooms_a[<?= $tid ?>][<?= htmlspecialchars($d) ?>]" class="form-select form-select-sm w-auto">
                            <option value="">রুম</option>
                            <?php foreach ($rooms as $r): ?>
                              <option value="<?= (int)$r['id'] ?>" <?= ($aRoom==(int)$r['id'])?'selected':''; ?>><?= htmlspecialchars($r['room_name']) ?></option>
                            <?php endforeach; ?>
                          </select>
                        </div>
                      </div>
                    </td>
                  <?php endforeach; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </form>
  <?php elseif ($tab === TAB_ROOMS): ?>
    <!-- Rooms setup tab -->
    <form method="post" class="card">
      <div class="card-header d-flex align-items-center gap-2">
        <strong><i class="fas fa-door-closed"></i> রুম নং তৈরী</strong>
        <div class="ms-auto d-flex align-items-center gap-2 no-print">
          <button type="button" class="btn btn-sm btn-outline-secondary" onclick="addRoomRow()"><i class="fas fa-plus"></i> নতুন রুম</button>
          <button class="btn btn-sm btn-primary"><i class="fas fa-save"></i> সেভ</button>
        </div>
      </div>
      <div class="card-body">
        <input type="hidden" name="action" value="room_create">
        <input type="hidden" name="delete_ids" id="delete_ids" value="">
        <div class="table-responsive">
          <table class="table table-bordered align-middle mb-0" id="roomsTable">
            <thead class="table-light">
              <tr>
                <th style="width:48px" class="text-center">#</th>
                <th>রুম নাম্বার/নাম</th>
                <th style="width:140px">আসন</th>
                <th style="width:160px">টিচার সীমা</th>
                <th style="width:80px" class="text-center">অ্যাকশন</th>
              </tr>
            </thead>
            <tbody>
              <?php $ri=1; foreach ($rooms as $r): ?>
              <tr>
                <td class="text-center"><?= $ri++ ?></td>
                <td>
                  <input type="hidden" name="room_id[]" value="<?= (int)$r['id'] ?>">
                  <input type="text" class="form-control" name="room_name[]" value="<?= htmlspecialchars($r['room_name']) ?>" placeholder="যেমন: 101">
                </td>
                <td><input type="number" class="form-control" name="capacity[]" value="<?= (int)($r['capacity'] ?? 0) ?>" min="0"></td>
                <td><input type="number" class="form-control" name="max_teachers[]" value="<?= htmlspecialchars((string)($r['max_teachers'] ?? '')) ?>" min="0" placeholder="ঐচ্ছিক"></td>
                <td class="text-center no-print">
                  <button type="button" class="btn btn-sm btn-outline-danger" onclick="markDelete(this, <?= (int)$r['id'] ?>)"><i class="fas fa-trash"></i></button>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <div class="form-text mt-2">টিচার সীমা ফাঁকা রাখলে সীমাহীন ধরা হবে।</div>
      </div>
    </form>
    <template id="roomRowTpl">
      <tr>
        <td class="text-center">•</td>
        <td>
          <input type="hidden" name="room_id[]" value="0">
          <input type="text" class="form-control" name="room_name[]" placeholder="যেমন: 101">
        </td>
        <td><input type="number" class="form-control" name="capacity[]" value="0" min="0"></td>
        <td><input type="number" class="form-control" name="max_teachers[]" value="" min="0" placeholder="ঐচ্ছিক"></td>
        <td class="text-center no-print">
          <button type="button" class="btn btn-sm btn-outline-danger" onclick="markDelete(this, 0)"><i class="fas fa-trash"></i></button>
        </td>
      </tr>
    </template>
    <script>
      function addRoomRow(){
        const tpl=document.getElementById('roomRowTpl');
        const tbody=document.querySelector('#roomsTable tbody');
        tbody.appendChild(tpl.content.cloneNode(true));
      }
      function markDelete(btn, id){
        const tr=btn.closest('tr');
        if(id>0){
          const box=document.getElementById('delete_ids');
          const set=new Set((box.value||'').split(',').filter(Boolean).map(Number));
          set.add(id);
          box.value=[...set].join(',');
        }
        tr.remove();
      }
    </script>
  <?php elseif ($tab === TAB_TEACHER): ?>
    <div class="row">
      <div class="col-lg-4">
        <div class="card">
          <div class="card-header fw-semibold">শিক্ষক তালিকা</div>
          <div class="list-group list-group-flush" style="max-height:70vh;overflow:auto">
            <?php foreach ($teachers as $t): $tid=(int)$t['id']; ?>
              <a class="list-group-item list-group-item-action <?= ($tid===$current_teacher_id?'active':'') ?>" href="?exam_id=<?= (int)$selected_exam_id ?>&tab=<?= TAB_TEACHER ?>&teacher_id=<?= $tid ?>&date=<?= urlencode($selected_date) ?>">
                <?= htmlspecialchars(tName($t)) ?>
                <small class="text-muted d-block"><?= htmlspecialchars($t['designation'] ?? '') ?><?= $t['employee_id']? ' · '.htmlspecialchars($t['employee_id']) : '' ?></small>
              </a>
            <?php endforeach; ?>
          </div>
        </div>
      </div>
      <div class="col-lg-8">
        <div class="card">
          <div class="card-header d-flex align-items-center">
            <strong><i class="fas fa-calendar-check"></i> ডিউটি বন্টন</strong>
            <div class="ms-auto small text-muted">রুটিনের তারিখসমূহ</div>
          </div>
          <div class="card-body">
            <?php if (!$current_teacher_id): ?>
              <div class="alert alert-info py-2">বাম পাশ থেকে একজন শিক্ষক নির্বাচন করুন।</div>
            <?php else: ?>
              <form method="post">
                <input type="hidden" name="action" value="teacher_save">
                <input type="hidden" name="teacher_id" value="<?= (int)$current_teacher_id ?>">
                <input type="hidden" name="date" value="<?= htmlspecialchars($selected_date) ?>">
                <?php foreach ($allowed_dates as $d): ?>
                  <input type="hidden" name="dates[]" value="<?= htmlspecialchars($d) ?>">
                <?php endforeach; ?>

                <div class="row g-2">
                  <?php foreach ($allowed_dates as $d): 
                  $mChecked = (isset($slotState['m'][$current_teacher_id]) && array_key_exists($d, $slotState['m'][$current_teacher_id]));
                  $aChecked = (isset($slotState['a'][$current_teacher_id]) && array_key_exists($d, $slotState['a'][$current_teacher_id]));
                  $mRoom = $mChecked ? $slotState['m'][$current_teacher_id][$d] : '';
                  $aRoom = $aChecked ? $slotState['a'][$current_teacher_id][$d] : '';
                ?>
                    <div class="col-12 col-md-6">
                      <div class="border rounded p-2">
                        <div class="fw-bold mb-1"><?= htmlspecialchars($d) ?></div>
                        <div class="d-flex align-items-center flex-wrap gap-3">
                          <div class="d-flex align-items-center gap-1">
                            <input class="form-check-input" type="checkbox" name="dates_m[]" id="dm_<?= htmlspecialchars($d) ?>" value="<?= htmlspecialchars($d) ?>" <?= $mChecked?'checked':''; ?>>
                            <label class="form-check-label small" for="dm_<?= htmlspecialchars($d) ?>">সকাল</label>
                            <select name="room_m[<?= htmlspecialchars($d) ?>]" class="form-select form-select-sm w-auto">
                              <option value="">রুম</option>
                              <?php foreach ($rooms as $r): ?>
                                <option value="<?= (int)$r['id'] ?>" <?= ($mRoom==(int)$r['id'])?'selected':''; ?>><?= htmlspecialchars($r['room_name']) ?></option>
                              <?php endforeach; ?>
                            </select>
                          </div>
                          <div class="d-flex align-items-center gap-1">
                            <input class="form-check-input" type="checkbox" name="dates_a[]" id="da_<?= htmlspecialchars($d) ?>" value="<?= htmlspecialchars($d) ?>" <?= $aChecked?'checked':''; ?>>
                            <label class="form-check-label small" for="da_<?= htmlspecialchars($d) ?>">বিকাল</label>
                            <select name="room_a[<?= htmlspecialchars($d) ?>]" class="form-select form-select-sm w-auto">
                              <option value="">রুম</option>
                              <?php foreach ($rooms as $r): ?>
                                <option value="<?= (int)$r['id'] ?>" <?= ($aRoom==(int)$r['id'])?'selected':''; ?>><?= htmlspecialchars($r['room_name']) ?></option>
                              <?php endforeach; ?>
                            </select>
                          </div>
                        </div>
                      </div>
                    </div>
                  <?php endforeach; ?>
                </div>

                <div class="mt-3 d-flex align-items-center gap-2">
                  <label class="form-label mb-0">ভূমিকা:</label>
                  <select name="duty_role" class="form-select w-auto">
                    <option value="invigilator">মূল</option>
                    <option value="assistant">সহকারী</option>
                    <option value="reserve">রিজার্ভ</option>
                  </select>
                  <button class="btn btn-primary"><i class="fas fa-save"></i> সেভ</button>
                </div>

                <div class="form-text mt-2 text-muted">রুম না দিলেও ডিউটি সেভ হবে; পরে রুম সেট করতে পারবেন।</div>
              </form>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
  <?php else: ?>
    <!-- Attendance sheet tab -->
    <div class="card">
      <div class="card-header d-flex align-items-center">
        <strong><i class="fas fa-clipboard-check"></i> হাজিরা পত্র — তারিখ: <?= htmlspecialchars($selected_date) ?></strong>
        <div class="ms-auto">
          <a class="btn btn-sm btn-primary me-2" href="print_room_duties.php?exam_id=<?= (int)$selected_exam_id ?>&date=<?= urlencode($selected_date) ?>" target="_blank"><i class="fas fa-file-alt"></i> রিপোর্ট প্রিন্ট</a>
          <button class="btn btn-sm btn-outline-secondary" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট</button>
        </div>
      </div>
      <div class="card-body">
        <?php if (empty($rooms)): ?>
          <div class="alert alert-warning py-2">এই পরীক্ষার জন্য কোনো রুম সেট করা নেই।</div>
        <?php else: ?>
          <?php 
            $stmtSlot = $pdo->prepare("SELECT d.id, d.teacher_id, d.order_index, t.first_name, t.last_name, t.designation, t.photo
                                       FROM exam_room_duties d 
                                       JOIN teachers t ON t.id = d.teacher_id
                                       WHERE d.exam_id=? AND d.room_id=? AND (d.duty_date <=> ?) AND (COALESCE(d.start_time,'') <=> ?) AND (COALESCE(d.end_time,'') <=> ?)
                                       ORDER BY d.order_index, d.id");
          ?>
          <div class="alert alert-secondary py-2 no-print">
            টীকা: সারি ড্র্যাগ-ড্রপ করে রুম/স্লটের ভিতরে ক্রম ঠিক করুন, তারপর "ক্রম সংরক্ষণ" চাপুন।
          </div>
          <?php foreach ($rooms as $room): $rid=(int)$room['id']; ?>
            <div class="mb-4 border rounded">
              <div class="p-2 bg-light d-flex align-items-center">
                <strong>রুম: <?= htmlspecialchars($room['room_name']) ?></strong>
                <?php if (!empty($room['max_teachers'])): ?>
                  <span class="badge bg-info ms-2">সীমা: <?= (int)$room['max_teachers'] ?></span>
                <?php endif; ?>
              </div>
              <div class="row g-3 p-2">
                <?php foreach ([['key'=>'m','title'=>'সকাল','st'=>$MORNING_START,'en'=>$MORNING_END], ['key'=>'a','title'=>'বিকাল','st'=>$AFTERNOON_START,'en'=>$AFTERNOON_END]] as $slot): ?>
                  <div class="col-12 col-md-6">
                    <div class="border rounded h-100">
                      <div class="p-2 d-flex align-items-center">
                        <strong><?= $slot['title'] ?></strong>
                        <button class="btn btn-sm btn-primary ms-auto" type="button" onclick="saveOrder(<?= (int)$selected_exam_id ?>, <?= $rid ?>, '<?= $slot['key'] ?>')">
                          <i class="fas fa-save"></i> ক্রম সংরক্ষণ
                        </button>
                      </div>
                      <?php 
                        $stmtSlot->execute([$selected_exam_id, $rid, $selected_date, $slot['st'], $slot['en']]);
                        $rows = $stmtSlot->fetchAll();
                      ?>
                      <div class="table-responsive">
                        <table class="table table-bordered table-sm align-middle mb-0">
                          <thead class="table-light">
                            <tr>
                              <th style="width:36px">#</th>
                              <th style="width:64px">ছবি</th>
                              <th>নাম</th>
                              <th style="width:140px">পদবি</th>
                              <th style="width:150px">উপস্থিতির সময়</th>
                              <th style="width:160px">স্বাক্ষর</th>
                            </tr>
                          </thead>
                          <tbody class="dnd-tbody" data-room="<?= $rid ?>" data-slot="<?= $slot['key'] ?>">
                            <?php $i=1; foreach ($rows as $row): $fullName = trim(($row['first_name']??'').' '.($row['last_name']??'')); ?>
                              <tr draggable="true" data-id="<?= (int)$row['id'] ?>">
                                <td class="text-muted handle" style="cursor:move">⇅</td>
                                <td>
                                  <?php if (!empty($row['photo'])): ?>
                                    <img src="../<?= htmlspecialchars($row['photo']) ?>" alt="photo" style="width:56px;height:56px;object-fit:cover;border:1px solid #ddd;border-radius:4px;">
                                  <?php else: ?>
                                    <div class="d-flex align-items-center justify-content-center bg-light" style="width:56px;height:56px;border:1px solid #ddd;border-radius:4px;">
                                      <i class="fas fa-user text-muted"></i>
                                    </div>
                                  <?php endif; ?>
                                </td>
                                <td>
                                  <div class="fw-semibold"><?= htmlspecialchars($fullName) ?></div>
                                </td>
                                <td><?= htmlspecialchars($row['designation'] ?? '') ?></td>
                                <td></td>
                                <td></td>
                              </tr>
                            <?php $i++; endforeach; ?>
                            <?php if (empty($rows)): ?>
                              <tr><td colspan="6" class="text-center text-muted py-3">কোনো টিচার নেই</td></tr>
                            <?php endif; ?>
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                <?php endforeach; ?>
              </div>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>
  <?php endif; ?>

  <?php endif; ?>
</div>
<script>
// Simple drag & drop within tbody
(function(){
  let dragSrc=null;
  document.querySelectorAll('.dnd-tbody').forEach(function(tbody){
    tbody.addEventListener('dragstart', function(e){
      const tr=e.target.closest('tr');
      if (!tr) return; dragSrc=tr; tr.classList.add('dragging');
      e.dataTransfer.effectAllowed='move';
    });
    tbody.addEventListener('dragover', function(e){ e.preventDefault(); const tr=e.target.closest('tr'); if(!tr||tr===dragSrc) return; const rect=tr.getBoundingClientRect(); const after=(e.clientY-rect.top)>(rect.height/2); tr.parentNode.insertBefore(dragSrc, after? tr.nextSibling : tr); });
    tbody.addEventListener('drop', function(e){ e.preventDefault(); });
    tbody.addEventListener('dragend', function(e){ const tr=e.target.closest('tr'); if(tr) tr.classList.remove('dragging'); });
  });
})();

function saveOrder(examId, roomId, slot){
  const tbody = document.querySelector('.dnd-tbody[data-room="'+roomId+'"][data-slot="'+slot+'"]');
  if(!tbody) return;
  const ids=[...tbody.querySelectorAll('tr[data-id]')].map(tr=>tr.getAttribute('data-id'));
  const form=new FormData();
  form.append('action','save_order');
  form.append('exam_id', examId);
  form.append('room_id', roomId);
  form.append('slot', slot);
  form.append('date', '<?= htmlspecialchars($selected_date) ?>');
  form.append('ids', JSON.stringify(ids));
  fetch('', {method:'POST', body:form})
    .then(r=>r.json())
    .then(j=>{
      if(!j.ok){ alert('সংরক্ষণ ব্যর্থ: '+(j.error||'')); }
    }).catch(()=>alert('নেটওয়ার্ক সমস্যা'));
}
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
