<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/access_control.php';
require_admin();

// Check if group_name column exists
$hasGroupCol = false;
try {
    $chk = $pdo->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='class_subjects' AND COLUMN_NAME='group_name'");
    $chk->execute();
    $hasGroupCol = $chk->fetchColumn() > 0;
} catch (Exception $e) {}

// === AJAX ===
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json; charset=utf-8');
    $act = $_POST['action'] ?? '';

    if ($act === 'get_groups') {
        try {
            $groups = [];
            // First try student_groups table
            try {
                $g = $pdo->query("SELECT group_name FROM student_groups WHERE status='active' ORDER BY group_name");
                $groups = $g->fetchAll(PDO::FETCH_COLUMN);
            } catch (Exception $e) {}
            // Fallback to class_subjects
            if (empty($groups) && $hasGroupCol) {
                try {
                    $g = $pdo->query("SELECT DISTINCT group_name FROM class_subjects WHERE group_name IS NOT NULL AND group_name != '' ORDER BY group_name");
                    $groups = $g->fetchAll(PDO::FETCH_COLUMN);
                } catch (Exception $e) {}
            }
            echo json_encode(['ok' => true, 'groups' => $groups, 'hasGroupCol' => $hasGroupCol]);
        } catch (Exception $e) {
            echo json_encode(['ok' => false, 'msg' => $e->getMessage()]);
        }
        exit();
    }

    if ($act === 'get_subjects') {
        $classId = (int)($_POST['class_id'] ?? 0);
        $groupName = trim($_POST['group_name'] ?? '');
        if (!$classId) { echo json_encode(['ok' => false, 'msg' => 'ক্লাস প্রয়োজন']); exit(); }

        try {
            // Always get ALL subjects for this class
            $stmt = $pdo->prepare("SELECT DISTINCT subject_id FROM class_subjects WHERE class_id=?");
            $stmt->execute([$classId]);
            $subjectIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

            if (empty($subjectIds)) {
                echo json_encode(['ok' => true, 'subjects' => [], 'group' => $groupName, 'hasGroupCol' => $hasGroupCol]);
                exit();
            }

            $ph = str_repeat('?,', count($subjectIds) - 1) . '?';
            $sStmt = $pdo->prepare("SELECT id, name, code FROM subjects WHERE id IN ($ph) AND status='active' ORDER BY name");
            $sStmt->execute($subjectIds);
            $subjects = $sStmt->fetchAll();

            // Teacher info (group-aware)
            $teachers = [];
            $teacherIds = [];
            if ($groupName !== '' && $hasGroupCol) {
                $tStmt = $pdo->prepare("SELECT cs.subject_id, cs.teacher_id, t.first_name AS tfn, t.last_name AS tln FROM class_subjects cs LEFT JOIN teachers t ON cs.teacher_id=t.id WHERE cs.class_id=? AND cs.group_name=? AND cs.subject_id IN ($ph)");
                $tStmt->execute(array_merge([$classId, $groupName], $subjectIds));
            } else {
                $tStmt = $pdo->prepare("SELECT cs.subject_id, cs.teacher_id, t.first_name AS tfn, t.last_name AS tln FROM class_subjects cs LEFT JOIN teachers t ON cs.teacher_id=t.id WHERE cs.class_id=? AND cs.subject_id IN ($ph)");
                $tStmt->execute(array_merge([$classId], $subjectIds));
            }
            foreach ($tStmt->fetchAll() as $row) {
                if ($row['teacher_id']) {
                    $teachers[$row['subject_id']] = $row['tfn'] . ' ' . $row['tln'];
                    $teacherIds[$row['subject_id']] = (int)$row['teacher_id'];
                }
            }

            $result = [];
            foreach ($subjects as $s) {
                $result[] = ['id' => (int)$s['id'], 'name' => $s['name'], 'code' => $s['code'], 'teacher' => $teachers[$s['id']] ?? '', 'teacher_id' => $teacherIds[$s['id']] ?? 0];
            }
            echo json_encode(['ok' => true, 'subjects' => $result, 'group' => $groupName, 'hasGroupCol' => $hasGroupCol]);
        } catch (Exception $e) {
            echo json_encode(['ok' => false, 'msg' => $e->getMessage()]);
        }
        exit();
    }

    if ($act === 'remove_subject') {
        $csId = (int)($_POST['cs_id'] ?? 0);
        if (!$csId) { echo json_encode(['ok' => false, 'msg' => 'Invalid']); exit(); }
        try {
            $pdo->prepare("UPDATE class_subjects SET teacher_id=NULL WHERE id=?")->execute([$csId]);
            echo json_encode(['ok' => true, 'msg' => 'বিষয় মুছে ফেলা হয়েছে']);
        } catch (Exception $e) {
            echo json_encode(['ok' => false, 'msg' => $e->getMessage()]);
        }
        exit();
    }

    if ($act === 'assign') {
        $classId = (int)($_POST['class_id'] ?? 0);
        $teacherId = (int)($_POST['teacher_id'] ?? 0);
        $subjectIds = array_filter(array_map('intval', $_POST['subject_ids'] ?? []), fn($v) => $v > 0);
        $groupName = trim($_POST['group_name'] ?? '');

        if (!$classId || !$teacherId) { echo json_encode(['ok' => false, 'msg' => 'ক্লাস ও শিক্ষক নির্বাচন করুন']); exit(); }
        if (empty($subjectIds)) { echo json_encode(['ok' => false, 'msg' => 'অন্তত একটি বিষয় নির্বাচন করুন']); exit(); }

        try {
            $pdo->beginTransaction();

            // First: clear teacher_id for ALL subjects of this teacher in this class+group
            if ($hasGroupCol && $groupName !== '') {
                $pdo->prepare("UPDATE class_subjects SET teacher_id=NULL WHERE class_id=? AND teacher_id=? AND group_name=?")->execute([$classId, $teacherId, $groupName]);
            } else {
                $pdo->prepare("UPDATE class_subjects SET teacher_id=NULL WHERE class_id=? AND teacher_id=? AND (group_name IS NULL OR group_name='')")->execute([$classId, $teacherId]);
            }

            // Then: set teacher_id for selected subjects
            $count = 0;
            foreach ($subjectIds as $sid) {
                $chk = $pdo->prepare("SELECT id FROM class_subjects WHERE class_id=? AND subject_id=?");
                $chk->execute([$classId, $sid]);
                $row = $chk->fetch();

                if ($row) {
                    if ($hasGroupCol && $groupName !== '') {
                        $pdo->prepare("UPDATE class_subjects SET teacher_id=?, group_name=? WHERE id=?")->execute([$teacherId, $groupName, $row['id']]);
                    } else {
                        $pdo->prepare("UPDATE class_subjects SET teacher_id=? WHERE id=?")->execute([$teacherId, $row['id']]);
                    }
                } else {
                    if ($hasGroupCol && $groupName !== '') {
                        $pdo->prepare("INSERT INTO class_subjects(class_id,subject_id,teacher_id,group_name,created_at) VALUES(?,?,?,?,?)")->execute([$classId, $sid, $teacherId, $groupName, date('Y-m-d H:i:s')]);
                    } else {
                        $pdo->prepare("INSERT INTO class_subjects(class_id,subject_id,teacher_id,created_at) VALUES(?,?,?,?)")->execute([$classId, $sid, $teacherId, date('Y-m-d H:i:s')]);
                    }
                }
                $count++;
            }
            $pdo->commit();
            echo json_encode(['ok' => true, 'msg' => $count . 'টি বিষয় নির্ধারণ করা হয়েছে']);
        } catch (Exception $e) {
            $pdo->rollBack();
            echo json_encode(['ok' => false, 'msg' => 'সমস্যা: ' . $e->getMessage()]);
        }
        exit();
    }
}

// === Page Data ===
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status='active' ORDER BY name, section")->fetchAll();
$teachers = $pdo->query("SELECT t.id, t.employee_id, t.first_name, t.last_name FROM teachers t JOIN users u ON t.user_id=u.id WHERE t.status='active' ORDER BY t.first_name, t.last_name")->fetchAll();
$branches = $pdo->query("SELECT id, branch_name FROM school_branches WHERE status='active' ORDER BY branch_name")->fetchAll();

$assignments = $pdo->query("
    SELECT cs.id AS csid, cs.class_id, cs.subject_id, cs.teacher_id, COALESCE(cs.group_name,'') AS grp,
           s.name AS sname, s.code AS scode, t.first_name AS tfn, t.last_name AS tln,
           cl.name AS cname, cl.section AS csection
    FROM class_subjects cs
    JOIN subjects s ON cs.subject_id=s.id
    JOIN classes cl ON cs.class_id=cl.id
    LEFT JOIN teachers t ON cs.teacher_id=t.id
    WHERE s.status='active'
    ORDER BY cl.name, cl.section, cs.group_name, s.name
")->fetchAll();

$grouped = [];
foreach ($assignments as $a) {
    $key = $a['class_id'] . '|' . $a['grp'];
    $grouped[$key][] = $a;
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>শিক্ষক বিষয় নির্ধারণ</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<style>
:root{--p:#4361ee;--s:#7209b7}
body{background:#f0f4ff;font-size:.85rem}
.topbar{background:linear-gradient(135deg,var(--p),var(--s));padding:8px 20px;display:flex;align-items:center;justify-content:space-between}
.topbar a{color:#fff;text-decoration:none;font-size:.82rem}
.pg{padding:10px 0 6px}
.pg h4{margin:0;font-size:1.05rem;font-weight:800;color:var(--p)}
.pg p{margin:2px 0 0;font-size:.72rem;color:#888}
.card-m{background:#fff;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,.05);border:none;overflow:hidden}
.card-m .hd{background:linear-gradient(135deg,var(--p),var(--s));color:#fff;padding:8px 14px;font-weight:700;font-size:.85rem;display:flex;align-items:center;justify-content:space-between}
.card-m .bd{padding:12px 14px}
.fl{font-weight:600;color:#495057;font-size:.76rem;margin-bottom:2px}
.fc{border-radius:6px;border:1.5px solid #e0e0e0;padding:4px 8px;font-size:.8rem}
.fc:focus{border-color:var(--p);box-shadow:0 0 0 2px rgba(67,97,238,.1)}
.btn-p{background:linear-gradient(135deg,var(--p),var(--s));color:#fff;border:none;border-radius:6px;padding:5px 14px;font-weight:700;font-size:.8rem}
.btn-p:hover{opacity:.9;color:#fff}
.s-chip{display:inline-flex;align-items:center;gap:5px;padding:4px 10px;border-radius:6px;border:1.5px solid #e0e0e0;background:#f8f9fa;margin:2px;font-size:.78rem;cursor:pointer;transition:.15s;user-select:none}
.s-chip:hover{border-color:var(--p);background:#eef2ff}
.s-chip.on{border-color:var(--p);background:linear-gradient(135deg,#eef2ff,#e8edff);font-weight:700}
.s-chip input{display:none}
.b-t{background:#006747;color:#fff;padding:1px 7px;border-radius:8px;font-size:.7rem}
.b-u{background:#ffc107;color:#333;padding:1px 7px;border-radius:8px;font-size:.7rem}
.ar{padding:6px 0;border-bottom:1px solid #f0f0f0;display:flex;justify-content:space-between;align-items:center;font-size:.8rem;flex-wrap:wrap;gap:4px}
.btn-remove{border:none;background:#fee2e2;color:#dc2626;border-radius:50%;width:20px;height:20px;display:inline-flex;align-items:center;justify-content:center;font-size:.6rem;cursor:pointer;transition:.15s;flex-shrink:0}
.btn-remove:hover{background:#dc2626;color:#fff}
.ar:last-child{border-bottom:none}
.ebox{text-align:center;padding:24px;color:#aaa;font-size:.8rem}
.ebox i{font-size:2rem;margin-bottom:6px;display:block}
.toast-a{position:fixed;top:16px;right:16px;z-index:9999;min-width:280px}
</style>
</head>
<body>
<div class="topbar">
    <a href="index.php"><i class="fas fa-graduation-cap me-1"></i> অ্যাডমিন প্যানেল</a>
    <div class="d-flex gap-3">
        <a href="index.php"><i class="fas fa-home me-1"></i>হোম</a>
        <a href="../logout.php"><i class="fas fa-sign-out-alt me-1"></i>লগআউট</a>
    </div>
</div>

<div class="container-fluid px-3 px-md-4 pb-3">
    <div class="pg">
        <h4><i class="fas fa-chalkboard-teacher me-1"></i> শিক্ষক বিষয় নির্ধারণ</h4>
        <p>ক্লাস, গ্রুপ ও শাখা অনুযায়ী শিক্ষককে বিষয় নির্ধারণ করুন</p>
    </div>
    <div id="globalMsg"></div>
    <div class="row g-3">
        <div class="col-lg-5">
            <div class="card-m">
                <div class="hd"><span><i class="fas fa-plus-circle me-1"></i> বিষয় নির্ধারণ</span></div>
                <div class="bd">
                    <form id="mainForm" onsubmit="return doAssign(event)">
                        <div class="mb-2">
                            <label class="fl">ক্লাস <span class="text-danger">*</span></label>
                            <select class="form-select fc" id="classId" required onchange="loadSubjects()">
                                <option value="">নির্বাচন করুন</option>
                                <?php foreach ($classes as $c): ?>
                                <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name'].' - '.$c['section']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="row g-2 mb-2">
                            <div class="col-6">
                                <label class="fl">গ্রুপ</label>
                                <select class="form-select fc" id="groupName" onchange="loadSubjects()">
                                    <option value="">সব গ্রুপ</option>
                                </select>
                            </div>
                            <div class="col-6">
                                <label class="fl">শাখা</label>
                                <select class="form-select fc" id="branchId">
                                    <option value="0">সব শাখা</option>
                                    <?php foreach ($branches as $b): ?>
                                    <option value="<?= $b['id'] ?>"><?= htmlspecialchars($b['branch_name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="mb-2">
                            <label class="fl">শিক্ষক <span class="text-danger">*</span></label>
                            <select class="form-select fc" id="teacherId" required onchange="autoSelectByTeacher()">
                                <option value="">নির্বাচন করুন</option>
                                <?php foreach ($teachers as $t): ?>
                                <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['first_name'].' '.$t['last_name'].' ('.$t['employee_id'].')') ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-2">
                            <label class="fl">বিষয় নির্বাচন <span class="text-danger">*</span> <small class="text-muted">(একাধিক সিলেক্ট করুন)</small></label>
                            <div id="subjectsBox" class="border rounded p-2" style="min-height:50px;max-height:280px;overflow-y:auto;background:#fafbfc">
                                <div class="ebox"><i class="fas fa-mouse-pointer"></i>ক্লাস সিলেক্ট করুন</div>
                            </div>
                            <div id="selectedCount" class="mt-1" style="font-size:.72rem;color:#888"></div>
                        </div>
                        <div class="d-flex gap-2 mt-2">
                            <button type="submit" class="btn btn-p flex-fill" id="submitBtn"><i class="fas fa-save me-1"></i>সেভ করুন</button>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="resetAll()"><i class="fas fa-redo"></i></button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-lg-7">
            <div class="card-m">
                <div class="hd">
                    <span><i class="fas fa-list-alt me-1"></i> বর্তমান নির্ধারণ</span>
                    <button class="btn btn-sm btn-outline-light" onclick="if(confirm('সকল নির্ধারণ মুছে ফেলতে চান?'))location.href='./reset_teacher_data.php?reset_action=reset_all_subjects&redirect_back=teacher_subject_assignment'"><i class="fas fa-trash me-1"></i>রিসেট</button>
                </div>
                <div class="bd" style="max-height:580px;overflow-y:auto">
                    <?php if (empty($grouped)): ?>
                    <div class="ebox"><i class="fas fa-inbox"></i>কোনো নির্ধারণ নেই</div>
                    <?php else: ?>
                    <?php foreach ($grouped as $key => $items): ?>
                    <?php $first = $items[0]; ?>
                    <div class="mb-2">
                        <div class="fw-bold text-primary" style="font-size:.8rem">
                            <i class="fas fa-layer-group me-1"></i><?= htmlspecialchars($first['cname'].' - '.$first['csection']) ?>
                            <?php if ($first['grp']): ?> <span class="badge bg-info text-dark" style="font-size:.68rem"><?= htmlspecialchars($first['grp']) ?></span><?php endif; ?>
                        </div>
                        <?php foreach ($items as $a): ?>
                        <div class="ar">
                            <span class="fw-semibold"><?= htmlspecialchars($a['sname']) ?> <span class="text-muted">(<?= htmlspecialchars($a['scode']) ?>)</span></span>
                            <?php if ($a['teacher_id']): ?>
                                <span class="b-t"><i class="fas fa-user-tie me-1"></i><?= htmlspecialchars($a['tfn'].' '.$a['tln']) ?></span>
                                <button class="btn-remove" onclick="removeSubject(<?= (int)$a['csid'] ?>, this)" title="বিষয় মুছুন"><i class="fas fa-times"></i></button>
                            <?php else: ?>
                                <span class="b-u">অনির্ধারিত</span>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="toast-a" id="toastArea"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const $=id=>document.getElementById(id);

function toast(m,t='success'){
    const d=document.createElement('div');
    d.className='alert alert-'+t+' alert-dismissible fade show py-2';
    d.style.cssText='font-size:.8rem;margin-bottom:4px';
    d.innerHTML='<i class="fas fa-'+(t==='success'?'check-circle':'exclamation-triangle')+' me-1"></i>'+m+'<button type="button" class="btn-close btn-close-sm" data-bs-dismiss="alert"></button>';
    $('toastArea').appendChild(d);setTimeout(()=>d.remove(),5000);
}

function showMsg(m,t){
    $('globalMsg').innerHTML='<div class="alert alert-'+t+' alert-dismissible fade show py-2" style="font-size:.8rem"><i class="fas fa-'+(t==='success'?'check-circle':'exclamation-triangle')+' me-1"></i>'+m+'<button type="button" class="btn-close btn-close-sm" data-bs-dismiss="alert"></button></div>';
}

function api(fd){return fetch('teacher_subject_assignment.php',{method:'POST',body:fd}).then(r=>r.json())}

// Load groups
function loadGroups(){
    var fd=new FormData();fd.append('ajax','1');fd.append('action','get_groups');
    api(fd).then(function(d){
        if(d.ok&&d.groups&&d.groups.length){
            var h='<option value="">সব গ্রুপ</option>';
            d.groups.forEach(function(g){h+='<option value="'+g+'">'+g+'</option>';});
            $('groupName').innerHTML=h;
        }
    });
}

var subjectsData=[];

function loadSubjects(){
    var cid=$('classId').value,gn=$('groupName').value;
    if(!cid){$('subjectsBox').innerHTML='<div class="ebox"><i class="fas fa-mouse-pointer"></i>ক্লাস সিলেক্ট করুন</div>';$('selectedCount').innerHTML='';subjectsData=[];return;}
    $('subjectsBox').innerHTML='<div class="text-center py-2 text-muted" style="font-size:.78rem"><i class="fas fa-spinner fa-spin me-1"></i>লোড হচ্ছে...</div>';
    subjectsData=[];

    var fd=new FormData();
    fd.append('ajax','1');
    fd.append('action','get_subjects');
    fd.append('class_id',cid);
    fd.append('group_name',gn);

    api(fd).then(function(d){
        if(!d.ok){$('subjectsBox').innerHTML='<div class="alert alert-danger py-1" style="font-size:.78rem">'+d.msg+'</div>';return;}
        if(!d.subjects||!d.subjects.length){
            $('subjectsBox').innerHTML='<div class="ebox"><i class="fas fa-info-circle"></i>এই ক্লাসে কোনো বিষয় নেই।<br><a href="subjects/assign_by_class.php" class="text-primary" style="font-size:.78rem">প্রথমে ক্লাসে বিষয় যোগ করুন</a></div>';
            $('selectedCount').innerHTML='';return;
        }

        subjectsData=d.subjects;
        renderSubjects();
        autoSelectByTeacher();
    }).catch(function(e){
        $('subjectsBox').innerHTML='<div class="alert alert-danger py-1" style="font-size:.78rem">নেটওয়ার্ক ত্রুটি: '+e.message+'</div>';
    });
}

function renderSubjects(){
    var h='<div class="d-flex flex-wrap">';
    subjectsData.forEach(function(s){
        var tb=s.teacher?'<span class="b-t ms-1" title="'+s.teacher+'">'+s.teacher.split(' ')[0]+'</span>':'';
        h+='<div class="s-chip" data-id="'+s.id+'" data-teacher-id="'+s.teacher_id+'"><input type="checkbox" name="subject_ids[]" value="'+s.id+'"><span>'+s.name+'</span><span class="text-muted">('+s.code+')</span>'+tb+'</div>';
    });
    h+='</div>';
    $('subjectsBox').innerHTML=h;

    document.querySelectorAll('.s-chip').forEach(function(el){
        el.onclick=function(){
            var cb=this.querySelector('input');
            cb.checked=!cb.checked;
            this.classList.toggle('on',cb.checked);
            updCount();
        };
    });
    updCount();
}

function autoSelectByTeacher(){
    var tid=parseInt($('teacherId').value)||0;
    document.querySelectorAll('.s-chip').forEach(function(el){
        var match=tid&&parseInt(el.dataset.teacherId)===tid;
        var cb=el.querySelector('input');
        cb.checked=match;
        el.classList.toggle('on',match);
    });
    updCount();
}

function updCount(){
    var n=document.querySelectorAll('.s-chip.on').length;
    $('selectedCount').innerHTML=n?'<i class="fas fa-check-circle text-success"></i> '+n+'টি বিষয় নির্বাচিত':'';
}

function doAssign(e){
    e.preventDefault();
    var cid=$('classId').value,tid=$('teacherId').value,gn=$('groupName').value;
    var ch=document.querySelectorAll('.s-chip input:checked');
    var sids=[];ch.forEach(function(c){sids.push(c.value);});

    if(!cid){toast('ক্লাস নির্বাচন করুন','warning');return false;}
    if(!tid){toast('শিক্ষক নির্বাচন করুন','warning');return false;}
    if(!sids.length){toast('অন্তত একটি বিষয় নির্বাচন করুন','warning');return false;}

    $('submitBtn').disabled=true;
    $('submitBtn').innerHTML='<i class="fas fa-spinner fa-spin me-1"></i>সেভ...';

    var fd=new FormData();
    fd.append('ajax','1');fd.append('action','assign');
    fd.append('class_id',cid);fd.append('teacher_id',tid);fd.append('group_name',gn);
    sids.forEach(function(s){fd.append('subject_ids[]',s);});

    api(fd).then(function(d){
        $('submitBtn').disabled=false;$('submitBtn').innerHTML='<i class="fas fa-save me-1"></i>সেভ করুন';
        if(d.ok){showMsg(d.msg,'success');setTimeout(function(){location.reload();},1000);}
        else toast(d.msg,'danger');
    }).catch(function(e){
        $('submitBtn').disabled=false;$('submitBtn').innerHTML='<i class="fas fa-save me-1"></i>সেভ করুন';
        toast('নেটওয়ার্ক ত্রুটি','danger');
    });
    return false;
}

function resetAll(){$('mainForm').reset();$('subjectsBox').innerHTML='<div class="ebox"><i class="fas fa-mouse-pointer"></i>ক্লাস সিলেক্ট করুন</div>';$('selectedCount').innerHTML='';}

function removeSubject(csId, btn){
    if(!confirm('এই বিষয়ের শিক্ষক মুছে ফেলতে চান?'))return;
    btn.disabled=true;btn.innerHTML='<i class="fas fa-spinner fa-spin"></i>';
    var fd=new FormData();fd.append('ajax','1');fd.append('action','remove_subject');fd.append('cs_id',csId);
    api(fd).then(function(d){
        if(d.ok){toast(d.msg,'success');setTimeout(function(){location.reload();},800);}
        else{toast(d.msg,'danger');btn.disabled=false;btn.innerHTML='<i class="fas fa-times"></i>';}
    }).catch(function(){toast('নেটওয়ার্ক ত্রুটি','danger');btn.disabled=false;btn.innerHTML='<i class="fas fa-times"></i>';}
    );
}

loadGroups();
</script>
</body>
</html>
