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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';

// Initialize custom exam names in session if not exists
if (!isset($_SESSION['custom_exam_names'])) {
    $_SESSION['custom_exam_names'] = [];
}

// Handle exam name management
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Create new exam name
    if (isset($_POST['create_exam_name'])) {
        $new_exam_name = trim($_POST['new_exam_name']);
        if (!empty($new_exam_name)) {
            // Add to session array if not already exists
            if (!in_array($new_exam_name, $_SESSION['custom_exam_names'])) {
                $_SESSION['custom_exam_names'][] = $new_exam_name;
            }
            $success_message = "পরীক্ষার নাম সফলভাবে যোগ করা হয়েছে! এখন থেকে এটি ড্রপডাউনে ব্যবহার করতে পারবেন।";
        } else {
            $error_message = "পরীক্ষার নাম খালি হতে পারবে না";
        }
    }
    
    // Delete custom exam name
    if (isset($_POST['delete_exam_name'])) {
        $delete_exam_name = trim($_POST['delete_exam_name']);
        if (!empty($delete_exam_name) && isset($_SESSION['custom_exam_names'])) {
            // Remove from session array
            $key = array_search($delete_exam_name, $_SESSION['custom_exam_names']);
            if ($key !== false) {
                unset($_SESSION['custom_exam_names'][$key]);
                // Re-index array
                $_SESSION['custom_exam_names'] = array_values($_SESSION['custom_exam_names']);
                $success_message = "পরীক্ষার নাম সফলভাবে মুছে ফেলা হয়েছে!";
            }
        }
    }
    
    // Clear all custom exam names
    if (isset($_POST['clear_all_custom_names'])) {
        $_SESSION['custom_exam_names'] = [];
        $success_message = "সব কাস্টম পরীক্ষার নাম সফলভাবে মুছে ফেলা হয়েছে!";
    }
    
    // Handle form submission for creating exam routine
    if (isset($_POST['create_routine'])) {
        // Determine exam name from dropdown/custom
        $exam_name_select = $_POST['exam_name_select'] ?? '';
        $exam_name_custom = trim($_POST['exam_name_custom'] ?? '') ?: null;
        $exam_name = ($exam_name_select === 'custom') ? ($exam_name_custom ?: '') : $exam_name_select;

        $class_id = $_POST['class_id'];
        $session = $_POST['session'];
        $group_names = $_POST['group_names'] ?? []; // array of selected groups; may include empty string for General
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];
        $subjects_data = $_POST['subjects'] ?? [];
        // Custom institution fields
        $custom_institution_name = trim($_POST['custom_institution_name'] ?? '');
        $custom_institution_address = trim($_POST['custom_institution_address'] ?? '');

        if (empty($exam_name)) {
            $error_message = 'পরীক্ষার নাম নির্বাচন/লিখুন';
        }

        if (empty($error_message)) {
            try {
                $pdo->beginTransaction();

                // If no group selected or only empty provided, create a single general routine
                $target_groups = (is_array($group_names) && count($group_names) > 0) ? $group_names : [''];
                if (count($target_groups) === 1 && $target_groups[0] === '') {
                    $target_groups = [''];
                } else {
                    // remove empties and duplicates for safety
                    $target_groups = array_values(array_unique(array_filter($group_names, function($g){ return $g !== null; })));
                    if (empty($target_groups)) { $target_groups = ['']; }
                }

                foreach ($target_groups as $grp) {
                    $grp_name = ($grp === '') ? '' : $grp;
                    // Create main exam record per group
                    $stmt = $pdo->prepare("INSERT INTO exams (name, class_id, session, group_name, exam_date, start_time, end_time, description, status, custom_institution_name, custom_institution_address) VALUES (?, ?, ?, ?, ?, '09:00:00', '17:00:00', 'Routine created', 'scheduled', ?, ?)");
                    $stmt->execute([$exam_name, $class_id, $session, $grp_name, $start_date, $custom_institution_name, $custom_institution_address]);
                    $exam_id = $pdo->lastInsertId();

                    // Add subjects to exam
                    foreach ($subjects_data as $subject_data) {
                        if (!empty($subject_data['subject_id']) && !empty($subject_data['exam_date'])) {
                            $stmt = $pdo->prepare("INSERT INTO exam_subjects (exam_id, subject_id, max_marks, pass_marks, exam_date, start_time, end_time, marks) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                            $stmt->execute([
                                $exam_id,
                                $subject_data['subject_id'],
                                $subject_data['max_marks'] ?? 100,
                                $subject_data['pass_marks'] ?? 40,
                                $subject_data['exam_date'],
                                $subject_data['start_time'] ?? '10:00:00',
                                $subject_data['end_time'] ?? '13:00:00',
                                $subject_data['marks'] ?? ''
                            ]);
                        }
                    }
                }

                $pdo->commit();
                $success_message = "পরীক্ষার রুটিন সফলভাবে তৈরি করা হয়েছে!";
            } catch (Exception $e) {
                $pdo->rollBack();
                $error_message = "ত্রুটি: " . $e->getMessage();
            }
        }
    }
}

// Get data for dropdowns
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->fetchAll();
$sessions = $pdo->query("SELECT session_name FROM academic_sessions WHERE status = 'active' ORDER BY session_name DESC")->fetchAll();
$groups = $pdo->query("SELECT group_name, group_code FROM student_groups WHERE status = 'active' ORDER BY group_name")->fetchAll();

// Get system name for branding
$system_name = get_system_name($pdo);

// Get existing exam routines
$stmt = $pdo->query("
    SELECT DISTINCT e.*, c.name as class_name, c.section,
           COUNT(es.id) as subject_count
    FROM exams e
    JOIN classes c ON e.class_id = c.id
    LEFT JOIN exam_subjects es ON e.id = es.exam_id
    GROUP BY e.id, c.name, c.section
    ORDER BY e.exam_date DESC, e.created_at DESC
");
$routines = $stmt->fetchAll();

// Get subjects for dropdown
$subjects = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name")->fetchAll();

// Get existing exam names for the dropdown
$exam_names_stmt = $pdo->query("SELECT DISTINCT name FROM exams ORDER BY name");
$exam_names = $exam_names_stmt->fetchAll();

// Merge with custom exam names from session
if (isset($_SESSION['custom_exam_names']) && is_array($_SESSION['custom_exam_names'])) {
    foreach ($_SESSION['custom_exam_names'] as $custom_name) {
        // Check if custom name already exists in database names
        $exists = false;
        foreach ($exam_names as $exam_name) {
            if ($exam_name['name'] === $custom_name) {
                $exists = true;
                break;
            }
        }
        // Add custom name if it doesn't exist
        if (!$exists) {
            $exam_names[] = ['name' => $custom_name];
        }
    }
}

// Get site settings for logo preview
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'প্রতিষ্ঠানের নাম';
$site_address = $settings['site_address'] ?? 'ঠিকানা, ফোন: ০১৭xxxxxxxx';
$logo_image = $settings['logo_image'] ?? '';
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;
$logo_opacity = isset($settings['logo_opacity']) ? floatval($settings['logo_opacity']) : 0.9;
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>পরীক্ষার রুটিন - <?php echo htmlspecialchars($system_name); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --navy:   #1a1a2e;
            --purple: #7209b7;
            --teal:   #06d6a0;
            --orange: #fb8500;
            --pink:   #e63946;
            --green:  #006747;
            --card-radius: 14px;
        }
        * { box-sizing: border-box; }
        body {
            font-family: 'Hind Siliguri', sans-serif;
            background: #f0f2f8;
            color: #1a1a2e;
            font-size: 14px;
        }

        /* ── TOP BAR ── */
        .top-bar {
            background: linear-gradient(135deg, var(--navy) 0%, #2d1b69 100%);
            padding: 10px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 12px rgba(0,0,0,.35);
        }
        .top-bar .brand {
            color: #fff;
            font-weight: 700;
            font-size: 16px;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .top-bar .brand i { color: var(--teal); }
        .top-bar .breadcrumb-nav {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 13px;
            color: rgba(255,255,255,.7);
        }
        .top-bar .breadcrumb-nav a { color: var(--teal); text-decoration: none; }
        .top-bar .breadcrumb-nav a:hover { color: #fff; }
        .top-bar .breadcrumb-nav .sep { color: rgba(255,255,255,.4); }
        .top-bar .nav-links { display: flex; gap: 6px; }
        .top-bar .nav-links a {
            color: rgba(255,255,255,.8);
            text-decoration: none;
            font-size: 12px;
            padding: 4px 10px;
            border-radius: 20px;
            border: 1px solid rgba(255,255,255,.2);
            transition: all .2s;
        }
        .top-bar .nav-links a:hover {
            background: var(--teal);
            color: var(--navy);
            border-color: var(--teal);
        }

        /* ── STATS BAR ── */
        .stats-bar {
            background: linear-gradient(90deg, var(--purple) 0%, #3a0ca3 100%);
            padding: 8px 20px;
            display: flex;
            align-items: center;
            gap: 20px;
            flex-wrap: wrap;
        }
        .stat-pill {
            display: flex;
            align-items: center;
            gap: 6px;
            background: rgba(255,255,255,.15);
            border-radius: 20px;
            padding: 3px 12px;
            color: #fff;
            font-size: 12px;
            font-weight: 500;
        }
        .stat-pill i { font-size: 11px; }
        .stat-pill .num {
            font-weight: 700;
            font-size: 14px;
            color: var(--teal);
        }

        /* ── CARDS ── */
        .card-modern {
            border: none;
            border-radius: var(--card-radius);
            box-shadow: 0 4px 20px rgba(0,0,0,.08);
            overflow: hidden;
            transition: box-shadow .25s;
        }
        .card-modern:hover { box-shadow: 0 8px 30px rgba(0,0,0,.14); }
        .card-header-gradient {
            padding: 12px 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #fff;
        }
        .card-header-gradient h6, .card-header-gradient h5 {
            margin: 0;
            font-weight: 600;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 7px;
        }
        .gh-navy   { background: linear-gradient(135deg, var(--navy) 0%, #2d1b69 100%); }
        .gh-purple { background: linear-gradient(135deg, var(--purple) 0%, #3a0ca3 100%); }
        .gh-teal   { background: linear-gradient(135deg, #0a9e7a 0%, var(--teal) 100%); }
        .gh-orange { background: linear-gradient(135deg, #e07000 0%, var(--orange) 100%); }
        .gh-pink   { background: linear-gradient(135deg, var(--pink) 0%, #c1121f 100%); }
        .gh-green  { background: linear-gradient(135deg, var(--green) 0%, #00a86b 100%); }

        /* ── FORM SIDEBAR ── */
        .sidebar-sticky {
            position: sticky;
            top: 12px;
            max-height: calc(100vh - 80px);
            overflow-y: auto;
            scrollbar-width: thin;
            scrollbar-color: var(--purple) #e0e0e0;
        }
        .sidebar-sticky::-webkit-scrollbar { width: 5px; }
        .sidebar-sticky::-webkit-scrollbar-thumb { background: var(--purple); border-radius: 4px; }

        .form-label {
            font-size: 12px;
            font-weight: 600;
            color: #444;
            margin-bottom: 3px;
        }
        .form-control, .form-select {
            font-size: 13px;
            border-radius: 8px;
            border: 1.5px solid #dde1f0;
            padding: 5px 10px;
            transition: border-color .2s, box-shadow .2s;
        }
        .form-control:focus, .form-select:focus {
            border-color: var(--purple);
            box-shadow: 0 0 0 3px rgba(114,9,183,.12);
        }
        .mb-2 { margin-bottom: 8px !important; }
        .mb-3 { margin-bottom: 12px !important; }

        /* ── SUBJECT ROWS ── */
        .subject-row {
            background: #f8f9ff;
            border: 1px solid #e8eaf6;
            border-radius: 10px;
            padding: 8px 10px;
            margin-bottom: 6px;
        }
        .subject-row .row { --bs-gutter-x: 6px; }
        .subject-row .form-control,
        .subject-row .form-select {
            font-size: 12px;
            padding: 4px 8px;
        }

        /* ── EXAM NAME BADGES ── */
        .exam-name-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            background: linear-gradient(135deg, var(--navy), #2d1b69);
            color: #fff;
            border-radius: 20px;
            padding: 4px 12px;
            font-size: 12px;
            font-weight: 500;
            margin: 3px;
        }
        .exam-name-badge.custom-badge {
            background: linear-gradient(135deg, var(--purple), #3a0ca3);
        }
        .exam-name-badge .del-btn {
            background: rgba(255,255,255,.2);
            border: none;
            color: #fff;
            border-radius: 50%;
            width: 18px;
            height: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 10px;
            padding: 0;
            transition: background .2s;
        }
        .exam-name-badge .del-btn:hover { background: var(--pink); }

        /* ── ROUTINE CARDS ── */
        .routine-card {
            border: none;
            border-radius: var(--card-radius);
            box-shadow: 0 3px 14px rgba(0,0,0,.08);
            overflow: hidden;
            margin-bottom: 14px;
            transition: transform .2s, box-shadow .2s;
        }
        .routine-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 28px rgba(0,0,0,.13);
        }
        .routine-card-header {
            padding: 10px 14px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 6px;
        }
        .routine-card-header .title-block { display: flex; align-items: center; gap: 8px; }
        .routine-card-header .exam-title {
            font-weight: 700;
            font-size: 14px;
            color: #fff;
        }
        .routine-card-header .meta-badges { display: flex; gap: 5px; flex-wrap: wrap; }
        .meta-badge {
            font-size: 11px;
            font-weight: 600;
            padding: 2px 9px;
            border-radius: 12px;
            background: rgba(255,255,255,.2);
            color: #fff;
            border: 1px solid rgba(255,255,255,.3);
        }
        .meta-badge.teal   { background: var(--teal);   color: var(--navy); border-color: var(--teal); }
        .meta-badge.orange { background: var(--orange); color: #fff;        border-color: var(--orange); }
        .meta-badge.pink   { background: var(--pink);   color: #fff;        border-color: var(--pink); }

        /* ── ACTION BUTTONS ── */
        .action-bar {
            padding: 8px 14px;
            background: #f8f9ff;
            border-bottom: 1px solid #eef0f8;
            display: flex;
            align-items: center;
            gap: 5px;
            flex-wrap: wrap;
        }
        .btn-pill {
            border-radius: 20px;
            padding: 4px 10px;
            font-size: 12px;
            font-weight: 500;
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            transition: all .2s;
            text-decoration: none;
        }
        .btn-pill:hover { transform: translateY(-1px); box-shadow: 0 3px 10px rgba(0,0,0,.2); }
        .btn-pill-print   { background: linear-gradient(135deg, #3a0ca3, var(--purple)); color: #fff; }
        .btn-pill-edit    { background: linear-gradient(135deg, #e07000, var(--orange)); color: #fff; }
        .btn-pill-attend  { background: linear-gradient(135deg, var(--green), #00a86b);  color: #fff; }
        .btn-pill-seat    { background: linear-gradient(135deg, #0077b6, #00b4d8);       color: #fff; }
        .btn-pill-delete  { background: linear-gradient(135deg, var(--pink), #c1121f);   color: #fff; }
        .btn-pill-force   { background: linear-gradient(135deg, #6c757d, #495057);       color: #fff; }
        .btn-pill-primary { background: linear-gradient(135deg, var(--purple), #3a0ca3); color: #fff; }
        .btn-pill-teal    { background: linear-gradient(135deg, #0a9e7a, var(--teal));   color: var(--navy); }

        /* ── ROUTINE TABLE ── */
        .routine-table {
            font-size: 12px;
            margin: 0;
        }
        .routine-table thead th {
            background: var(--navy);
            color: #fff;
            font-weight: 600;
            padding: 6px 10px;
            border: none;
            font-size: 12px;
        }
        .routine-table tbody tr:nth-child(even) { background: #f5f6ff; }
        .routine-table tbody td {
            padding: 5px 10px;
            border: 1px solid #e8eaf6;
            vertical-align: middle;
        }
        .routine-table tbody tr:hover { background: #eef0ff; }

        /* ── PREVIEW CARD ── */
        .preview-card {
            background: linear-gradient(135deg, #f8f9ff, #eef0ff);
            border: 1px dashed #c5cae9;
            border-radius: 10px;
            padding: 12px;
            text-align: center;
        }
        .preview-card h5 { font-size: 13px; font-weight: 700; color: var(--navy); margin: 4px 0 2px; }
        .preview-card p  { font-size: 11px; color: #666; margin: 0; }

        /* ── SUBMIT BUTTON ── */
        .btn-submit {
            background: linear-gradient(135deg, var(--purple), #3a0ca3);
            color: #fff;
            border: none;
            border-radius: 10px;
            padding: 10px;
            font-size: 14px;
            font-weight: 600;
            width: 100%;
            transition: all .25s;
        }
        .btn-submit:hover {
            background: linear-gradient(135deg, #3a0ca3, var(--purple));
            transform: translateY(-1px);
            box-shadow: 0 5px 18px rgba(114,9,183,.4);
            color: #fff;
        }

        /* ── ALERTS ── */
        .alert { border-radius: 10px; font-size: 13px; padding: 8px 14px; }

        /* ── EMPTY STATE ── */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #888;
        }
        .empty-state i { font-size: 48px; color: #c5cae9; margin-bottom: 12px; }

        /* ── SECTION DIVIDER ── */
        .section-divider {
            height: 3px;
            background: linear-gradient(90deg, var(--purple), var(--teal), var(--orange));
            border-radius: 2px;
            margin: 0 0 16px;
        }

        /* ── PRINT STYLES ── */
        @media print {
            .no-print { display: none !important; }
            .print-only { display: block !important; }
            body { font-size: 12px; background: #fff; }
            .routine-card { box-shadow: none; border: 1px solid #ccc; }
            .routine-table thead th { background: #333 !important; -webkit-print-color-adjust: exact; }
        }
        .print-only { display: none; }

        /* ── RESPONSIVE ── */
        @media (max-width: 768px) {
            .top-bar .nav-links { display: none; }
            .sidebar-sticky { position: static; max-height: none; }
        }
    </style>
</head>
<body>

<!-- ══ TOP BAR ══ -->
<div class="top-bar no-print">
    <a class="brand" href="../index.php">
        <i class="fas fa-graduation-cap"></i>
        <?php echo htmlspecialchars($system_name); ?>
    </a>
    <div class="breadcrumb-nav">
        <a href="../index.php"><i class="fas fa-home"></i> হোম</a>
        <span class="sep">/</span>
        <span style="color:#fff;">পরীক্ষার রুটিন</span>
    </div>
    <div class="nav-links">
        <a href="attendance.php"><i class="fas fa-clipboard-check"></i> হাজিরা</a>
        <a href="admit_card.php"><i class="fas fa-address-card"></i> এডমিট</a>
        <a href="seat_card.php"><i class="fas fa-id-card"></i> সীট কার্ড</a>
    </div>
</div>

<!-- ══ STATS BAR ══ -->
<div class="stats-bar no-print">
    <div class="stat-pill">
        <i class="fas fa-calendar-alt"></i>
        মোট রুটিন: <span class="num"><?php echo count($routines); ?></span>
    </div>
    <div class="stat-pill">
        <i class="fas fa-tags"></i>
        পরীক্ষার নাম: <span class="num"><?php echo count($exam_names); ?></span>
    </div>
    <div class="stat-pill">
        <i class="fas fa-book"></i>
        বিষয়: <span class="num"><?php echo count($subjects); ?></span>
    </div>
    <div class="stat-pill">
        <i class="fas fa-school"></i>
        ক্লাস: <span class="num"><?php echo count($classes); ?></span>
    </div>
</div>

<div class="container-fluid px-3 py-3">

    <!-- ══ EXAM NAME MANAGEMENT ══ -->
    <div class="card-modern mb-3 no-print">
        <div class="card-header-gradient gh-navy">
            <h6><i class="fas fa-tags"></i> পরীক্ষার নাম ম্যানেজমেন্ট</h6>
            <?php if (!empty($_SESSION['custom_exam_names'])): ?>
            <form method="POST" action="" class="d-inline">
                <input type="hidden" name="clear_all_custom_names" value="1">
                <button type="submit" class="btn-pill btn-pill-delete" style="font-size:11px;"
                        onclick="return confirm('সব কাস্টম পরীক্ষার নাম মুছে ফেলবেন?')">
                    <i class="fas fa-trash-alt"></i> সব মুছুন
                </button>
            </form>
            <?php endif; ?>
        </div>
        <div class="card-body p-3">
            <div class="row g-3 align-items-start">
                <div class="col-md-5">
                    <form method="POST" action="">
                        <div class="input-group input-group-sm">
                            <input type="text" class="form-control" name="new_exam_name"
                                   placeholder="নতুন পরীক্ষার নাম লিখুন" required>
                            <input type="hidden" name="create_exam_name" value="1">
                            <button class="btn btn-sm btn-pill-primary btn-pill" type="submit"
                                    style="border-radius:0 8px 8px 0;">
                                <i class="fas fa-plus"></i> যোগ করুন
                            </button>
                        </div>
                        <div class="form-text" style="font-size:11px;">
                            নতুন নাম যোগ করুন — ড্রপডাউনে ব্যবহার করতে পারবেন
                        </div>
                    </form>
                </div>
                <div class="col-md-7">
                    <div class="d-flex flex-wrap">
                        <?php foreach ($exam_names as $exam_name): ?>
                            <?php $isCustom = in_array($exam_name['name'], $_SESSION['custom_exam_names'] ?? []); ?>
                            <span class="exam-name-badge <?php echo $isCustom ? 'custom-badge' : ''; ?>">
                                <?php echo htmlspecialchars($exam_name['name']); ?>
                                <?php if ($isCustom): ?>
                                    <form method="POST" action="" class="d-inline">
                                        <input type="hidden" name="delete_exam_name"
                                               value="<?php echo htmlspecialchars($exam_name['name']); ?>">
                                        <button type="submit" class="del-btn"
                                                onclick="return confirm('এই নামটি মুছে ফেলবেন?')">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </span>
                        <?php endforeach; ?>
                        <?php if (empty($exam_names)): ?>
                            <span class="text-muted" style="font-size:12px;">কোন পরীক্ষার নাম নেই</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ══ MAIN LAYOUT ══ -->
    <div class="row g-3">

        <!-- ══ LEFT: CREATE FORM ══ -->
        <div class="col-md-4 no-print">
            <div class="sidebar-sticky">
                <div class="card-modern">
                    <div class="card-header-gradient gh-purple">
                        <h6><i class="fas fa-plus-circle"></i> নতুন পরীক্ষার রুটিন</h6>
                    </div>
                    <div class="card-body p-3">

                        <?php if ($success_message): ?>
                        <div class="alert alert-success alert-dismissible fade show py-2">
                            <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <?php endif; ?>
                        <?php if ($error_message): ?>
                        <div class="alert alert-danger alert-dismissible fade show py-2">
                            <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <?php endif; ?>

                        <form method="POST" action="">
                            <input type="hidden" name="create_routine" value="1">

                            <!-- Exam Name -->
                            <div class="mb-2">
                                <label for="exam_name_select" class="form-label">
                                    পরীক্ষার নাম <span class="text-danger">*</span>
                                </label>
                                <select class="form-select form-select-sm" id="exam_name_select"
                                        name="exam_name_select" required>
                                    <option value="">নির্বাচন করুন</option>
                                    <?php foreach ($exam_names as $exam_name): ?>
                                    <option value="<?php echo htmlspecialchars($exam_name['name']); ?>">
                                        <?php echo htmlspecialchars($exam_name['name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                    <option value="custom">অন্যান্য (নিচে লিখুন)</option>
                                </select>
                            </div>
                            <div class="mb-2 d-none" id="exam_name_custom_wrap">
                                <input type="text" class="form-control form-control-sm"
                                       id="exam_name_custom" name="exam_name_custom"
                                       placeholder="পরীক্ষার নাম লিখুন">
                            </div>

                            <!-- Institution -->
                            <div class="mb-2">
                                <label for="custom_institution_name" class="form-label">
                                    প্রতিষ্ঠানের নাম (কাস্টম)
                                </label>
                                <input type="text" class="form-control form-control-sm"
                                       id="custom_institution_name" name="custom_institution_name"
                                       placeholder="ডিফল্ট থেকে আলাদা হলে লিখুন">
                            </div>
                            <div class="mb-2">
                                <label for="custom_institution_address" class="form-label">
                                    প্রতিষ্ঠানের ঠিকানা (কাস্টম)
                                </label>
                                <input type="text" class="form-control form-control-sm"
                                       id="custom_institution_address" name="custom_institution_address"
                                       placeholder="ডিফল্ট থেকে আলাদা হলে লিখুন">
                            </div>

                            <!-- Logo Preview -->
                            <div class="preview-card mb-3">
                                <?php if ($logo_image): ?>
                                <img src="../<?php echo htmlspecialchars($logo_image); ?>" alt="Logo"
                                     style="max-height:<?php echo $logo_size; ?>px; opacity:<?php echo $logo_opacity; ?>;
                                            max-width:120px; object-fit:contain; margin-bottom:6px;">
                                <?php endif; ?>
                                <h5><?php echo htmlspecialchars($site_name); ?></h5>
                                <p><?php echo htmlspecialchars($site_address); ?></p>
                                <div style="font-size:10px; color:#888; margin-top:4px;">
                                    <i class="fas fa-info-circle"></i> সাইট সেটিংস থেকে নেওয়া হবে
                                </div>
                            </div>

                            <!-- Class + Session -->
                            <div class="row g-2 mb-2">
                                <div class="col-6">
                                    <label for="class_id" class="form-label">
                                        ক্লাস <span class="text-danger">*</span>
                                    </label>
                                    <select class="form-select form-select-sm" id="class_id"
                                            name="class_id" required
                                            onchange="loadSubjectsByClass(this.value)">
                                        <option value="">নির্বাচন করুন</option>
                                        <?php foreach ($classes as $class): ?>
                                        <option value="<?php echo $class['id']; ?>">
                                            <?php echo $class['name'] . ' - ' . $class['section']; ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-6">
                                    <label for="session" class="form-label">
                                        সেশন <span class="text-danger">*</span>
                                    </label>
                                    <select class="form-select form-select-sm" id="session"
                                            name="session" required>
                                        <option value="">নির্বাচন করুন</option>
                                        <?php foreach ($sessions as $session): ?>
                                        <option value="<?php echo $session['session_name']; ?>">
                                            <?php echo $session['session_name']; ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <!-- Group -->
                            <div class="mb-2">
                                <label for="group_names" class="form-label">
                                    গ্রুপ (একাধিক নির্বাচন করা যাবে)
                                </label>
                                <select class="form-select form-select-sm" id="group_names"
                                        name="group_names[]" multiple size="3">
                                    <option value="">সাধারণ</option>
                                    <?php foreach ($groups as $group): ?>
                                    <option value="<?php echo $group['group_name']; ?>">
                                        <?php echo $group['group_name'] . ' (' . $group['group_code'] . ')'; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <div class="form-text" style="font-size:10px;">
                                    Ctrl/Shift চেপে একাধিক নির্বাচন করুন
                                </div>
                            </div>

                            <!-- Dates -->
                            <div class="row g-2 mb-2">
                                <div class="col-6">
                                    <label for="start_date" class="form-label">
                                        শুরুর তারিখ <span class="text-danger">*</span>
                                    </label>
                                    <input type="date" class="form-control form-control-sm"
                                           id="start_date" name="start_date" required>
                                </div>
                                <div class="col-6">
                                    <label for="end_date" class="form-label">
                                        শেষের তারিখ <span class="text-danger">*</span>
                                    </label>
                                    <input type="date" class="form-control form-control-sm"
                                           id="end_date" name="end_date" required>
                                </div>
                            </div>

                            <!-- Subjects -->
                            <div class="mb-3">
                                <div class="d-flex align-items-center justify-content-between mb-2">
                                    <label class="form-label mb-0" style="color:var(--purple); font-weight:700;">
                                        <i class="fas fa-book"></i> বিষয়সমূহ
                                    </label>
                                    <button type="button" class="btn-pill btn-pill-teal"
                                            style="font-size:11px; padding:3px 10px;"
                                            onclick="addSubjectRow()">
                                        <i class="fas fa-plus"></i> যোগ করুন
                                    </button>
                                </div>
                                <div id="subjects-container">
                                    <div class="subject-row">
                                        <div class="row g-1 mb-1">
                                            <div class="col-7">
                                                <select class="form-select form-select-sm subject-select"
                                                        name="subjects[0][subject_id]">
                                                    <option value="">বিষয় নির্বাচন করুন</option>
                                                    <?php foreach ($subjects as $subject): ?>
                                                    <option value="<?php echo $subject['id']; ?>">
                                                        <?php echo $subject['name']; ?>
                                                    </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-5">
                                                <input type="date" class="form-control form-control-sm"
                                                       name="subjects[0][exam_date]">
                                            </div>
                                        </div>
                                        <div class="row g-1">
                                            <div class="col-4">
                                                <input type="time" class="form-control form-control-sm"
                                                       name="subjects[0][start_time]" value="10:00">
                                            </div>
                                            <div class="col-4">
                                                <input type="time" class="form-control form-control-sm"
                                                       name="subjects[0][end_time]" value="13:00">
                                            </div>
                                            <div class="col-4">
                                                <input type="text" class="form-control form-control-sm"
                                                       name="subjects[0][marks]" placeholder="নম্বর">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <button type="submit" class="btn-submit">
                                <i class="fas fa-save"></i> রুটিন তৈরি করুন
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- ══ RIGHT: ROUTINES LIST ══ -->
        <div class="col-md-8">

            <!-- Session messages -->
            <?php if (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success alert-dismissible fade show py-2 no-print">
                <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success_message']; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['success_message']); ?>
            <?php endif; ?>
            <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger alert-dismissible fade show py-2 no-print">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $_SESSION['error_message']; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['error_message']); ?>
            <?php endif; ?>

            <!-- Header row -->
            <div class="d-flex align-items-center justify-content-between mb-3 no-print">
                <div>
                    <h5 style="color:var(--navy); font-weight:700; margin:0;">
                        <i class="fas fa-calendar-alt" style="color:var(--purple);"></i>
                        পরীক্ষার রুটিনসমূহ
                    </h5>
                    <div class="section-divider mt-1" style="width:120px;"></div>
                </div>
                <div class="d-flex gap-2 flex-wrap">
                    <button class="btn-pill btn-pill-delete d-none" id="deleteSelectedBtn">
                        <i class="fas fa-trash"></i> নির্বাচিত মুছুন
                    </button>
                    <a href="delete_routine_page.php" class="btn-pill btn-pill-delete">
                        <i class="fas fa-trash"></i> রুটিন মুছুন
                    </a>
                    <button class="btn-pill btn-pill-primary" onclick="window.print()">
                        <i class="fas fa-print"></i> প্রিন্ট
                    </button>
                </div>
            </div>

            <?php if (empty($routines)): ?>
            <div class="card-modern">
                <div class="empty-state">
                    <i class="fas fa-calendar-times d-block"></i>
                    <p class="mt-2">কোন পরীক্ষার রুটিন পাওয়া যায়নি</p>
                    <small class="text-muted">বাম প্যানেল থেকে নতুন রুটিন তৈরি করুন</small>
                </div>
            </div>
            <?php else: ?>

            <?php
            // Color cycle for routine card headers
            $headerColors = ['gh-purple','gh-navy','gh-teal','gh-orange','gh-pink','gh-green'];
            $colorIdx = 0;
            foreach ($routines as $routine):
                $hc = $headerColors[$colorIdx % count($headerColors)];
                $colorIdx++;
            ?>
            <div class="routine-card">
                <!-- Card Header -->
                <div class="routine-card-header <?php echo $hc; ?>">
                    <div class="title-block">
                        <div class="form-check mb-0 no-print">
                            <input class="form-check-input routine-checkbox" type="checkbox"
                                   value="<?php echo $routine['id']; ?>"
                                   id="routine_<?php echo $routine['id']; ?>"
                                   style="margin-top:0;">
                        </div>
                        <span class="exam-title"><?php echo htmlspecialchars($routine['name']); ?></span>
                        <?php if (!empty($routine['custom_institution_name']) || !empty($routine['custom_institution_address'])): ?>
                        <span class="meta-badge orange"><i class="fas fa-star"></i> কাস্টম</span>
                        <?php endif; ?>
                    </div>
                    <div class="meta-badges">
                        <span class="meta-badge teal">
                            <i class="fas fa-school"></i>
                            <?php echo htmlspecialchars($routine['class_name'] . ' - ' . $routine['section']); ?>
                        </span>
                        <span class="meta-badge">
                            <i class="fas fa-calendar"></i>
                            <?php echo htmlspecialchars($routine['session']); ?>
                        </span>
                        <?php if ($routine['group_name']): ?>
                        <span class="meta-badge orange">
                            <i class="fas fa-users"></i>
                            <?php echo htmlspecialchars($routine['group_name']); ?>
                        </span>
                        <?php endif; ?>
                        <span class="meta-badge pink">
                            <i class="fas fa-book"></i>
                            <?php echo $routine['subject_count']; ?>টি বিষয়
                        </span>
                        <span class="meta-badge" style="font-size:10px; opacity:.7;">
                            #<?php echo $routine['id']; ?>
                        </span>
                    </div>
                </div>

                <!-- Print-only header -->
                <div class="print-only text-center py-2">
                    <h4><?php echo htmlspecialchars($routine['name']); ?></h4>
                    <p>ক্লাস: <?php echo htmlspecialchars($routine['class_name'] . ' - ' . $routine['section']); ?> |
                       সেশন: <?php echo htmlspecialchars($routine['session']); ?>
                       <?php if ($routine['group_name']): ?>
                       | গ্রুপ: <?php echo htmlspecialchars($routine['group_name']); ?>
                       <?php endif; ?>
                    </p>
                </div>

                <!-- Action Bar -->
                <div class="action-bar no-print">
                    <a href="routine_print.php?id=<?php echo $routine['id']; ?>"
                       class="btn-pill btn-pill-print" target="_blank"
                       title="প্রিন্ট করুন">
                        <i class="fas fa-print"></i> প্রিন্ট
                    </a>
                    <a href="edit_routine.php?id=<?php echo $routine['id']; ?>"
                       class="btn-pill btn-pill-edit" title="সম্পাদনা">
                        <i class="fas fa-edit"></i> সম্পাদনা
                    </a>
                    <a href="attendance.php?exam_id=<?php echo $routine['id']; ?>"
                       class="btn-pill btn-pill-attend" title="হাজিরা পত্র">
                        <i class="fas fa-clipboard-check"></i> হাজিরা
                    </a>
                    <a href="seat_card.php?exam_id=<?php echo $routine['id']; ?>"
                       class="btn-pill btn-pill-seat" title="সীট কার্ড">
                        <i class="fas fa-id-card"></i> সীট কার্ড
                    </a>
                    <button type="button" class="btn-pill btn-pill-delete delete-routine-btn"
                            data-id="<?php echo $routine['id']; ?>"
                            data-name="<?php echo htmlspecialchars($routine['name']); ?>"
                            title="মুছুন">
                        <i class="fas fa-trash"></i> মুছুন
                    </button>
                    <button type="button" class="btn-pill btn-pill-force force-delete-routine-btn"
                            data-id="<?php echo $routine['id']; ?>"
                            data-name="<?php echo htmlspecialchars($routine['name']); ?>"
                            title="জোর মুছুন">
                        <i class="fas fa-bolt"></i> জোর মুছুন
                    </button>
                </div>

                <!-- Subject Table -->
                <?php
                $stmt2 = $pdo->prepare("
                    SELECT es.*, s.name as subject_name, s.code as subject_code
                    FROM exam_subjects es
                    JOIN subjects s ON es.subject_id = s.id
                    WHERE es.exam_id = ?
                    ORDER BY es.exam_date, es.start_time
                ");
                $stmt2->execute([$routine['id']]);
                $routine_subjects = $stmt2->fetchAll();
                ?>
                <?php if (!empty($routine_subjects)): ?>
                <div class="px-3 pb-3 pt-2">
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered routine-table">
                            <thead>
                                <tr>
                                    <th style="width:110px;">তারিখ</th>
                                    <th>বিষয়</th>
                                    <th style="width:140px;">সময়</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $grouped_subjects = [];
                                foreach ($routine_subjects as $subject) {
                                    $date = $subject['exam_date'];
                                    if (!isset($grouped_subjects[$date])) {
                                        $grouped_subjects[$date] = [];
                                    }
                                    $grouped_subjects[$date][] = $subject;
                                }
                                foreach ($grouped_subjects as $date => $subjects):
                                    $first_subject = $subjects[0];
                                ?>
                                <tr>
                                    <td>
                                        <span style="font-weight:600; color:var(--purple);">
                                            <?php echo date('d/m/Y', strtotime($date)); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php
                                        $subject_names = [];
                                        foreach ($subjects as $subject) {
                                            $subject_names[] = htmlspecialchars($subject['subject_name']);
                                        }
                                        echo implode(' <span style="color:var(--orange);">/</span> ', $subject_names);
                                        ?>
                                    </td>
                                    <td style="color:var(--green); font-weight:500;">
                                        <?php echo date('h:i A', strtotime($first_subject['start_time'])); ?> –
                                        <?php echo date('h:i A', strtotime($first_subject['end_time'])); ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>

        </div><!-- /col-md-8 -->
    </div><!-- /row -->
</div><!-- /container-fluid -->

<!-- ══ EDIT SUBJECT MODAL ══ -->
<div class="modal fade" id="editSubjectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content" style="border-radius:14px; overflow:hidden;">
            <div class="modal-header gh-purple" style="border:none;">
                <h5 class="modal-title text-white">
                    <i class="fas fa-edit"></i> বিষয় সম্পাদনা
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-3">
                <form id="editSubjectForm">
                    <input type="hidden" id="edit_subject_id">
                    <div class="row g-2">
                        <div class="col-6">
                            <label class="form-label">তারিখ</label>
                            <input type="date" class="form-control form-control-sm" id="edit_exam_date">
                        </div>
                        <div class="col-6">
                            <label class="form-label">প্রাপ্ত নম্বর</label>
                            <input type="text" class="form-control form-control-sm" id="edit_marks">
                        </div>
                        <div class="col-6">
                            <label class="form-label">শুরুর সময়</label>
                            <input type="time" class="form-control form-control-sm" id="edit_start_time">
                        </div>
                        <div class="col-6">
                            <label class="form-label">শেষের সময়</label>
                            <input type="time" class="form-control form-control-sm" id="edit_end_time">
                        </div>
                        <div class="col-6">
                            <label class="form-label">রুম নম্বর</label>
                            <input type="text" class="form-control form-control-sm" id="edit_room_number">
                        </div>
                        <div class="col-6">
                            <label class="form-label">পরীক্ষক</label>
                            <input type="text" class="form-control form-control-sm" id="edit_invigilator">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer" style="border:none; background:#f8f9ff;">
                <button type="button" class="btn-pill btn-pill-force" data-bs-dismiss="modal">বন্ধ করুন</button>
                <button type="button" class="btn-pill btn-pill-primary update-subject-btn"
                        onclick="updateSubject()">
                    <i class="fas fa-save"></i> আপডেট করুন
                </button>
            </div>
        </div>
    </div>
</div>

<!-- ══ EDIT DATE MODAL ══ -->
<div class="modal fade" id="editDateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content" style="border-radius:14px; overflow:hidden;">
            <div class="modal-header gh-teal" style="border:none;">
                <h5 class="modal-title text-white">
                    <i class="fas fa-calendar-edit"></i> তারিখ সম্পাদনা
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-3">
                <form id="editDateForm">
                    <input type="hidden" id="edit_date_subject_id">
                    <div class="row g-2">
                        <div class="col-12">
                            <label class="form-label">তারিখ</label>
                            <input type="date" class="form-control form-control-sm" id="edit_date_exam_date">
                        </div>
                        <div class="col-6">
                            <label class="form-label">শুরুর সময়</label>
                            <input type="time" class="form-control form-control-sm" id="edit_date_start_time">
                        </div>
                        <div class="col-6">
                            <label class="form-label">শেষের সময়</label>
                            <input type="time" class="form-control form-control-sm" id="edit_date_end_time">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer" style="border:none; background:#f8f9ff;">
                <button type="button" class="btn-pill btn-pill-force" data-bs-dismiss="modal">বন্ধ করুন</button>
                <button type="button" class="btn-pill btn-pill-teal update-subject-date-btn"
                        onclick="updateSubjectDate()">
                    <i class="fas fa-save"></i> আপডেট করুন
                </button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // ── exam_name_select toggle ──
    document.addEventListener('DOMContentLoaded', function(){
        var sel = document.getElementById('exam_name_select');
        var customWrap = document.getElementById('exam_name_custom_wrap');
        var custom = document.getElementById('exam_name_custom');
        if (sel) {
            sel.addEventListener('change', function(){
                if (this.value === 'custom') {
                    customWrap.classList.remove('d-none');
                    custom.setAttribute('required', 'required');
                    custom.focus();
                } else {
                    customWrap.classList.add('d-none');
                    custom.removeAttribute('required');
                }
            });
        }
    });

    // ── updateSubject ──
    function updateSubject() {
        console.log('updateSubject function called');
        const subjectIdElement   = document.getElementById('edit_subject_id');
        const examDateElement    = document.getElementById('edit_exam_date');
        const startTimeElement   = document.getElementById('edit_start_time');
        const endTimeElement     = document.getElementById('edit_end_time');
        const marksElement       = document.getElementById('edit_marks');
        const roomNumberElement  = document.getElementById('edit_room_number');
        const invigilatorElement = document.getElementById('edit_invigilator');

        console.log('Subject ID Element:', subjectIdElement);
        console.log('Subject ID Value:', subjectIdElement ? subjectIdElement.value : 'N/A');
        console.log('Exam Date Value:', examDateElement ? examDateElement.value : 'N/A');
        console.log('Start Time Value:', startTimeElement ? startTimeElement.value : 'N/A');
        console.log('End Time Value:', endTimeElement ? endTimeElement.value : 'N/A');

        if (!subjectIdElement || !examDateElement || !startTimeElement || !endTimeElement || !marksElement || !roomNumberElement || !invigilatorElement) {
            console.error('One or more form elements are missing');
            alert('ত্রুটি: ফর্ম এলিমেন্ট খুঁজে পাওয়া যাচ্ছে না');
            return;
        }
        if (!subjectIdElement.value) {
            console.error('Subject ID is empty');
            alert('ত্রুটি: বিষয় আইডি খালি');
            return;
        }

        const formData = new FormData();
        formData.append('id',           subjectIdElement.value);
        formData.append('exam_date',    examDateElement.value);
        formData.append('start_time',   startTimeElement.value);
        formData.append('end_time',     endTimeElement.value);
        formData.append('marks',        marksElement.value);
        formData.append('room_number',  roomNumberElement.value);
        formData.append('invigilator',  invigilatorElement.value);

        for (let pair of formData.entries()) { console.log(pair[0] + ': ' + pair[1]); }

        fetch('update_subject.php', { method: 'POST', body: formData })
            .then(response => {
                if (!response.ok) throw new Error('Network response was not ok: ' + response.status);
                return response.json();
            })
            .then(data => {
                console.log('Update subject response:', data);
                if (data.success) { location.reload(); }
                else { alert('আপডেট করতে সমস্যা হয়েছে: ' + (data.message || '')); }
            })
            .catch(error => {
                console.error('Error updating subject:', error);
                alert('ত্রুটি: বিষয় আপডেট করতে সমস্যা হয়েছে: ' + error.message);
            });
    }

    // ── updateSubjectDate ──
    function updateSubjectDate() {
        console.log('updateSubjectDate function called');
        const subjectIdElement = document.getElementById('edit_date_subject_id');
        const examDateElement  = document.getElementById('edit_date_exam_date');
        const startTimeElement = document.getElementById('edit_date_start_time');
        const endTimeElement   = document.getElementById('edit_date_end_time');

        console.log('Date Subject ID Element:', subjectIdElement);
        console.log('Date Subject ID Value:', subjectIdElement ? subjectIdElement.value : 'N/A');
        console.log('Date Exam Date Value:', examDateElement ? examDateElement.value : 'N/A');
        console.log('Date Start Time Value:', startTimeElement ? startTimeElement.value : 'N/A');
        console.log('Date End Time Value:', endTimeElement ? endTimeElement.value : 'N/A');

        if (!subjectIdElement || !examDateElement || !startTimeElement || !endTimeElement) {
            console.error('One or more date form elements are missing');
            alert('ত্রুটি: ফর্ম এলিমেন্ট খুঁজে পাওয়া যাচ্ছে না');
            return;
        }
        if (!subjectIdElement.value) {
            console.error('Subject ID is empty for date update');
            alert('ত্রুটি: বিষয় আইডি খালি');
            return;
        }

        const formData = new FormData();
        formData.append('id',         subjectIdElement.value);
        formData.append('exam_date',  examDateElement.value);
        formData.append('start_time', startTimeElement.value);
        formData.append('end_time',   endTimeElement.value);

        for (let pair of formData.entries()) { console.log('Date form - ' + pair[0] + ': ' + pair[1]); }

        fetch('update_subject_date.php', { method: 'POST', body: formData })
            .then(response => {
                if (!response.ok) throw new Error('Network response was not ok: ' + response.status);
                return response.json();
            })
            .then(data => {
                console.log('Update subject date response:', data);
                if (data.success) { location.reload(); }
                else { alert('আপডেট করতে সমস্যা হয়েছে: ' + (data.message || '')); }
            })
            .catch(error => {
                console.error('Error updating subject date:', error);
                alert('ত্রুটি: বিষয়ের তারিখ আপডেট করতে সমস্যা হয়েছে: ' + error.message);
            });
    }

    let subjectRowCount = 1;
    let currentClassSubjects = [];

    function loadSubjectsByClass(classId) {
        const url = classId
            ? `get_subjects_by_class.php?class_id=${encodeURIComponent(classId)}`
            : 'get_subjects_by_class.php';

        fetch(url)
            .then(r => r.json())
            .then(subjects => {
                currentClassSubjects = subjects;
                document.querySelectorAll('.subject-select').forEach(sel => {
                    const prevVal = sel.value;
                    rebuildSubjectSelect(sel, subjects, prevVal);
                });
            })
            .catch(err => console.error('বিষয় লোড করতে সমস্যা:', err));
    }

    function rebuildSubjectSelect(selectEl, subjects, selectedValue) {
        selectEl.innerHTML = '<option value="">বিষয় নির্বাচন করুন</option>';
        subjects.forEach(s => {
            const opt = document.createElement('option');
            opt.value = s.id;
            opt.textContent = s.name + (s.code ? ' (' + s.code + ')' : '');
            if (String(s.id) === String(selectedValue)) opt.selected = true;
            selectEl.appendChild(opt);
        });
    }

    function addSubjectRow() {
        const container = document.getElementById('subjects-container');
        const newRow = document.createElement('div');
        newRow.className = 'subject-row';

        let optionsHtml = '<option value="">বিষয় নির্বাচন করুন</option>';
        if (currentClassSubjects.length > 0) {
            currentClassSubjects.forEach(s => {
                optionsHtml += `<option value="${s.id}">${s.name}${s.code ? ' (' + s.code + ')' : ''}</option>`;
            });
        } else {
            <?php foreach ($subjects as $subject): ?>
            optionsHtml += `<option value="<?php echo $subject['id']; ?>"><?php echo addslashes($subject['name']); ?></option>`;
            <?php endforeach; ?>
        }

        newRow.innerHTML = `
            <div class="row g-1 mb-1">
                <div class="col-6">
                    <select class="form-select form-select-sm subject-select"
                            name="subjects[${subjectRowCount}][subject_id]">
                        ${optionsHtml}
                    </select>
                </div>
                <div class="col-5">
                    <input type="date" class="form-control form-control-sm"
                           name="subjects[${subjectRowCount}][exam_date]">
                </div>
                <div class="col-1 d-flex align-items-center">
                    <button type="button" class="btn btn-sm btn-outline-danger p-0 px-1"
                            style="border-radius:50%; font-size:11px; line-height:1.4;"
                            onclick="removeSubjectRow(this)">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="row g-1">
                <div class="col-4">
                    <input type="time" class="form-control form-control-sm"
                           name="subjects[${subjectRowCount}][start_time]" value="10:00">
                </div>
                <div class="col-4">
                    <input type="time" class="form-control form-control-sm"
                           name="subjects[${subjectRowCount}][end_time]" value="13:00">
                </div>
                <div class="col-4">
                    <input type="text" class="form-control form-control-sm"
                           name="subjects[${subjectRowCount}][marks]" placeholder="নম্বর">
                </div>
            </div>
        `;
        container.appendChild(newRow);
        subjectRowCount++;
    }

    function removeSubjectRow(button) {
        button.closest('.subject-row').remove();
    }

    // ── DOMContentLoaded ──
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM loaded, initializing event listeners');

        const checkboxes = document.querySelectorAll('.routine-checkbox');
        const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');

        checkboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const checkedCount = document.querySelectorAll('.routine-checkbox:checked').length;
                if (deleteSelectedBtn) {
                    if (checkedCount > 0) { deleteSelectedBtn.classList.remove('d-none'); }
                    else { deleteSelectedBtn.classList.add('d-none'); }
                }
            });
        });

        document.addEventListener('click', function(e) {
            console.log('Document click event triggered, target:', e.target);

            // Regular delete button
            if (e.target.closest('.delete-routine-btn')) {
                console.log('Regular delete button detected');
                e.preventDefault();
                const button = e.target.closest('.delete-routine-btn');
                console.log('Delete button clicked');

                const routineId   = button.dataset.id;
                const routineName = button.dataset.name;
                console.log('Deleting routine ID: ' + routineId + ', Name: ' + routineName);

                let forceDelete = false;
                const normalConfirm = confirm(`আপনি কি নিশ্চিত যে "${routineName}" পরীক্ষার রুটিনটি মুছে ফেলতে চান? এটি সম্পূর্ণ রুটিন এবং সমস্ত সাবজেক্ট মুছে ফেলবে।`);
                if (!normalConfirm) { console.log('User cancelled regular delete'); return; }

                if (confirm(`রুটিনটি মুছে ফেলতে সমস্যা হলে আপনি কি জোর করে মুছে ফেলতে চান?`)) {
                    forceDelete = true;
                    console.log('User requested force delete');
                }

                const formData = new FormData();
                formData.append('id', routineId);
                if (forceDelete) { formData.append('force', '1'); }
                console.log('Sending delete request with force flag:', forceDelete);

                fetch('delete_routine.php', { method: 'POST', body: formData })
                    .then(response => {
                        console.log('Raw response:', response);
                        if (!response.ok) throw new Error('Network response was not ok: ' + response.status + ' ' + response.statusText);
                        console.log('Response received:', response);
                        return response.json();
                    })
                    .then(data => {
                        console.log('Data received:', data);
                        if (data.success) { alert('পরীক্ষার রুটিন সফলভাবে মুছে ফেলা হয়েছে'); window.location.href = 'routine.php'; }
                        else { alert('মুছে ফেলতে সমস্যা হয়েছে: ' + data.message); }
                    })
                    .catch(error => { console.error('Error:', error); alert('ত্রুটি: ' + error.message); });
            }

            // Force delete button
            else if (e.target.closest('.force-delete-routine-btn')) {
                console.log('Force delete button detected');
                e.preventDefault();
                const button = e.target.closest('.force-delete-routine-btn');
                console.log('Force delete button clicked');

                const routineId   = button.dataset.id;
                const routineName = button.dataset.name;
                console.log('Force deleting routine ID: ' + routineId + ', Name: ' + routineName);

                const normalConfirm = confirm(`আপনি কি নিশ্চিত যে "${routineName}" পরীক্ষার রুটিনটি জোর করে মুছে ফেলতে চান? এটি সমস্ত সম্পর্কিত ডেটা মুছে ফেলবে।`);
                if (!normalConfirm) { console.log('User cancelled force delete'); return; }

                const formData = new FormData();
                formData.append('id', routineId);
                formData.append('force', '1');
                console.log('Sending force delete request');

                fetch('delete_routine.php', { method: 'POST', body: formData })
                    .then(response => {
                        console.log('Raw response:', response);
                        if (!response.ok) throw new Error('Network response was not ok: ' + response.status + ' ' + response.statusText);
                        console.log('Response received:', response);
                        return response.json();
                    })
                    .then(data => {
                        console.log('Data received:', data);
                        if (data.success) { alert('পরীক্ষার রুটিন সফলভাবে মুছে ফেলা হয়েছে'); window.location.href = 'routine.php'; }
                        else { alert('মুছে ফেলতে সমস্যা হয়েছে: ' + data.message); }
                    })
                    .catch(error => { console.error('Error:', error); alert('ত্রুটি: ' + error.message); });
            }

            // Bulk delete button
            else if (e.target.closest('#deleteSelectedBtn')) {
                console.log('Bulk delete button detected');
                e.preventDefault();
                console.log('Bulk delete button clicked');

                const selectedCheckboxes = document.querySelectorAll('.routine-checkbox:checked');
                const selectedIds = Array.from(selectedCheckboxes).map(cb => cb.value);
                const selectedNames = Array.from(selectedCheckboxes).map(cb => {
                    const routineCard = cb.closest('.routine-card');
                    return routineCard.querySelector('.exam-title').textContent;
                });

                if (selectedIds.length === 0) { alert('অন্ততপক্ষে একটি রুটিন নির্বাচন করুন'); return; }
                console.log('Selected routines for bulk delete:', selectedIds);

                let forceDelete = false;
                const normalConfirm = confirm(`আপনি কি নিশ্চিত যে নিম্নলিখিত ${selectedIds.length}টি পরীক্ষার রুটিন মুছে ফেলতে চান?\n\n${selectedNames.join('\n')}`);
                if (!normalConfirm) { console.log('User cancelled bulk delete'); return; }

                if (confirm(`এই রুটিনগুলো মুছে ফেলতে সমস্যা হলে আপনি কি জোর করে মুছে ফেলতে চান?`)) {
                    forceDelete = true;
                    console.log('User requested force delete for bulk operation');
                }

                const formData = new FormData();
                formData.append('ids', selectedIds.join(','));
                if (forceDelete) { formData.append('force', '1'); }
                console.log('Sending bulk delete request with force flag:', forceDelete);

                fetch('delete_routine.php', { method: 'POST', body: formData })
                    .then(response => {
                        console.log('Raw bulk response:', response);
                        if (!response.ok) throw new Error('Network response was not ok: ' + response.status + ' ' + response.statusText);
                        console.log('Bulk delete response received:', response);
                        return response.json();
                    })
                    .then(data => {
                        console.log('Bulk delete data received:', data);
                        if (data.success) { alert(`${selectedIds.length}টি পরীক্ষার রুটিন সফলভাবে মুছে ফেলা হয়েছে`); window.location.href = 'routine.php'; }
                        else { alert('মুছে ফেলতে সমস্যা হয়েছে: ' + data.message); }
                    })
                    .catch(error => { console.error('Error:', error); alert('ত্রুটি: ' + error.message); });
            }
        });

        // Edit subject functionality
        const editButtons = document.querySelectorAll('.edit-subject-btn');
        editButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                console.log('Edit button clicked, subject ID:', this.dataset.id);
                const subjectId = this.dataset.id;
                if (!subjectId) { console.error('Invalid subject ID'); alert('ত্রুটি: বিষয় আইডি খুঁজে পাওয়া যাচ্ছে না'); return; }
                console.log('Loading subject data for ID:', subjectId);

                fetch(`get_subject_details.php?id=${subjectId}`)
                    .then(response => {
                        console.log('Received response from server:', response);
                        if (!response.ok) throw new Error('Network response was not ok: ' + response.status);
                        return response.json();
                    })
                    .then(data => {
                        console.log('Received subject data:', data);
                        if (data.error) throw new Error(data.error);
                        document.getElementById('edit_subject_id').value   = data.id;
                        document.getElementById('edit_exam_date').value    = data.exam_date;
                        document.getElementById('edit_start_time').value   = data.start_time;
                        document.getElementById('edit_end_time').value     = data.end_time;
                        document.getElementById('edit_room_number').value  = data.room_number || '';
                        document.getElementById('edit_invigilator').value  = data.invigilator || '';
                        document.getElementById('edit_marks').value        = data.marks || '';
                        console.log('Successfully populated form fields');
                        const modal = new bootstrap.Modal(document.getElementById('editSubjectModal'));
                        modal.show();
                    })
                    .catch(error => { console.error('Error loading subject data:', error); alert('ত্রুটি: বিষয়ের তথ্য লোড করতে সমস্যা হয়েছে: ' + error.message); });
            });
        });

        // Edit date functionality
        const editDateButtons = document.querySelectorAll('.edit-date-btn');
        editDateButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                console.log('Edit date button clicked, subject ID:', this.dataset.id);
                const subjectId = this.dataset.id;
                if (!subjectId) { console.error('Invalid subject ID for date editing'); alert('ত্রুটি: বিষয় আইডি খুঁজে পাওয়া যাচ্ছে না'); return; }
                console.log('Loading subject data for date editing, ID:', subjectId);

                fetch(`get_subject_details.php?id=${subjectId}`)
                    .then(response => {
                        console.log('Received response from server for date editing:', response);
                        if (!response.ok) throw new Error('Network response was not ok: ' + response.status);
                        return response.json();
                    })
                    .then(data => {
                        console.log('Received subject data for date editing:', data);
                        if (data.error) throw new Error(data.error);
                        document.getElementById('edit_date_subject_id').value  = data.id;
                        document.getElementById('edit_date_exam_date').value   = data.exam_date;
                        document.getElementById('edit_date_start_time').value  = data.start_time;
                        document.getElementById('edit_date_end_time').value    = data.end_time;
                        console.log('Successfully populated date form fields');
                        const modal = new bootstrap.Modal(document.getElementById('editDateModal'));
                        modal.show();
                    })
                    .catch(error => { console.error('Error loading subject data for date editing:', error); alert('ত্রুটি: বিষয়ের তথ্য লোড করতে সমস্যা হয়েছে: ' + error.message); });
            });
        });

    });
</script>
</body>
</html>
