<?php
session_start();
require_once '../config/database.php';
if (!isset($_SESSION['user_id'])) { header('Location: ../login.php'); exit(); }

$msg = $err = '';
// Class 6, 7, 8 — no fourth subject allowed
define('NO_FOURTH_CLASSES', [6, 7, 8]);

if ($_SERVER['REQUEST_METHOD']==='POST'&&isset($_POST['action'])) {

  // ── Bulk remove fourth subject by class/session/group ──────────────────────
  if ($_POST['action'] === 'bulk_remove_fourth') {
    $bulk_class   = (int)($_POST['bulk_class_id'] ?? 0);
    $bulk_session = trim($_POST['bulk_session'] ?? '');
    $bulk_group   = trim($_POST['bulk_group'] ?? '');
    if (!$bulk_class) {
      $err = 'ক্লাস নির্বাচন করুন।';
    } else {
      try {
        $sql = "UPDATE student_subjects ss
                INNER JOIN students s ON s.id = ss.student_id
                SET ss.is_fourth_subject = 0
                WHERE s.class_id = ?
                  AND ss.is_fourth_subject = 1";
        $bp = [$bulk_class];
        if ($bulk_session !== '') { $sql .= " AND s.session = ?"; $bp[] = $bulk_session; }
        if ($bulk_group   !== '') { $sql .= " AND COALESCE(s.group_name,'') = ?"; $bp[] = $bulk_group; }
        $st = $pdo->prepare($sql);
        $st->execute($bp);
        $n = $st->rowCount();
        $msg = "✓ $n জন ছাত্র-ছাত্রীর চতুর্থ বিষয় সরানো হয়েছে।";
      } catch(Exception $e){ $err='ত্রুটি: '.$e->getMessage(); }
    }
  }

  // ── Bulk SET fourth subject by class/session/group ──────────────────────────
  elseif ($_POST['action'] === 'bulk_set_fourth') {
    $bulk_class     = (int)($_POST['bulk_set_class_id'] ?? 0);
    $bulk_session   = trim($_POST['bulk_set_session'] ?? '');
    $bulk_group     = trim($_POST['bulk_set_group'] ?? '');
    $bulk_subject   = (int)($_POST['bulk_set_subject_id'] ?? 0);
    if (!$bulk_class || !$bulk_subject) {
      $err = 'ক্লাস ও বিষয় উভয়ই নির্বাচন করুন।';
    } elseif (in_array($bulk_class, NO_FOURTH_CLASSES)) {
      $err = 'ষষ্ঠ, সপ্তম ও অষ্টম শ্রেণীতে চতুর্থ বিষয় প্রযোজ্য নয়।';
    } else {
      try {
        $pdo->beginTransaction();
        // Step 1: clear existing fourth subject for matching students
        $sql1 = "UPDATE student_subjects ss
                 INNER JOIN students s ON s.id = ss.student_id
                 SET ss.is_fourth_subject = 0
                 WHERE s.class_id = ?";
        $bp1 = [$bulk_class];
        if ($bulk_session !== '') { $sql1 .= " AND s.session = ?"; $bp1[] = $bulk_session; }
        if ($bulk_group   !== '') { $sql1 .= " AND COALESCE(s.group_name,'') = ?"; $bp1[] = $bulk_group; }
        $pdo->prepare($sql1)->execute($bp1);

        // Step 2: set the chosen subject as fourth for students who have it
        $sql2 = "UPDATE student_subjects ss
                 INNER JOIN students s ON s.id = ss.student_id
                 SET ss.is_fourth_subject = 1
                 WHERE s.class_id = ?
                   AND ss.subject_id = ?";
        $bp2 = [$bulk_class, $bulk_subject];
        if ($bulk_session !== '') { $sql2 .= " AND s.session = ?"; $bp2[] = $bulk_session; }
        if ($bulk_group   !== '') { $sql2 .= " AND COALESCE(s.group_name,'') = ?"; $bp2[] = $bulk_group; }
        $st2 = $pdo->prepare($sql2);
        $st2->execute($bp2);
        $n = $st2->rowCount();
        $pdo->commit();
        $msg = "✓ $n জন ছাত্র-ছাত্রীর চতুর্থ বিষয় সেট করা হয়েছে।";
      } catch(Exception $e){ $pdo->rollBack(); $err='ত্রুটি: '.$e->getMessage(); }
    }
  }

  // ── Single student fourth subject set/remove ───────────────────────────────
  else {
  try {
    $pdo->beginTransaction();
    $sid=(int)$_POST['student_id'];$sub=(int)$_POST['subject_id'];
    // Check if student belongs to a class that has no fourth subject
    $cls=$pdo->prepare("SELECT c.id FROM students s JOIN classes c ON s.class_id=c.id WHERE s.id=?");
    $cls->execute([$sid]);$clsRow=$cls->fetch();
    if ($clsRow && in_array((int)$clsRow['id'], NO_FOURTH_CLASSES)) {
      $err='ষষ্ঠ, সপ্তম ও অষ্টম শ্রেণীতে চতুর্থ বিষয় প্রযোজ্য নয়। সব বিষয় বাধ্যতামূলক।';
    } else {
    $pdo->prepare("UPDATE student_subjects SET is_fourth_subject=0 WHERE student_id=?")->execute([$sid]);
    if ($sub>0) {
      $c=$pdo->prepare("SELECT COUNT(*) FROM student_subjects WHERE student_id=? AND subject_id=?");
      $c->execute([$sid,$sub]);
      if ($c->fetchColumn()>0){$pdo->prepare("UPDATE student_subjects SET is_fourth_subject=1 WHERE student_id=? AND subject_id=?")->execute([$sid,$sub]);$msg='চতুর্থ বিষয় নির্ধারণ করা হয়েছে!';}
      else $err='ছাত্র-ছাত্রী এই বিষয়ে ভর্তি নয়!';
    } else $msg='চতুর্থ বিষয় সরানো হয়েছে!';
    }
    $pdo->commit();
  } catch(Exception $e){$pdo->rollBack();$err='ত্রুটি: '.$e->getMessage();}
  }
}
$sf=(int)($_GET['session_id']??0);$cf=(int)($_GET['class_id']??0);$gf=$_GET['group_name']??'';$sq=trim($_GET['search']??'');
$ff=$_GET['fourth_subject']??'';$stf=$_GET['status']??'active';$scf=$_GET['section']??'';$pp=min((int)($_GET['per_page']??20),100);$pg=max(1,(int)($_GET['page']??1));

$S=$pdo->query("SELECT id,session_name FROM academic_sessions ORDER BY start_date DESC")->fetchAll();
$C=$pdo->query("SELECT id,name,section FROM classes WHERE status='active' ORDER BY name")->fetchAll();
$secs=$pdo->query("SELECT DISTINCT section FROM classes WHERE status='active' ORDER BY section")->fetchAll(PDO::FETCH_COLUMN);
$ALL_GROUPS=$pdo->query("SELECT DISTINCT group_name FROM students WHERE group_name IS NOT NULL AND group_name!='' ORDER BY group_name")->fetchAll(PDO::FETCH_COLUMN);
$GR=[];if($cf){$g=$pdo->prepare("SELECT DISTINCT group_name FROM students WHERE class_id=? AND group_name!='' ORDER BY group_name");$g->execute([$cf]);$GR=$g->fetchAll();}
try{$hs=$pdo->query("SHOW COLUMNS FROM students LIKE 'session_id'")->rowCount()>0;}catch(Exception $e){$hs=false;}
$sl="s.id,s.student_id,s.first_name,s.last_name,s.roll_number,s.group_name,s.status,s.class_id,c.name cl,c.section sc,(SELECT subject_id FROM student_subjects WHERE student_id=s.id AND is_fourth_subject=1 LIMIT 1) fid";
if($hs)$sl.=",ses.session_name";
$fm="FROM students s LEFT JOIN classes c ON s.class_id=c.id".($hs?" LEFT JOIN academic_sessions ses ON s.session_id=ses.id":"");
$w="WHERE 1=1";$p=[];
if($sf&&$hs){$w.=" AND s.session_id=?";$p[]=$sf;}
if($cf){$w.=" AND s.class_id=?";$p[]=$cf;}
if($gf){$w.=" AND s.group_name=?";$p[]=$gf;}
if($scf){$w.=" AND c.section=?";$p[]=$scf;}
if($stf){$w.=" AND s.status=?";$p[]=$stf;}
if($sq){$q="%$sq%";$w.=" AND (s.student_id LIKE ? OR CONCAT(s.first_name,' ',s.last_name) LIKE ? OR s.roll_number LIKE ?)";$p=array_merge($p,[$q,$q,$q]);}
$cs=$pdo->prepare("SELECT COUNT(*) $fm $w");$cs->execute($p);$total=$cs->fetchColumn();
$pages=ceil($total/$pp);$offset=($pg-1)*$pp;
$q=$pdo->prepare("SELECT $sl $fm $w ORDER BY c.name,s.group_name,s.roll_number LIMIT ? OFFSET ?");$q->execute(array_merge($p,[$pp,$offset]));$students=$q->fetchAll();
foreach($students as &$s){$ss=$pdo->prepare("SELECT sub.id,sub.name,sub.code,ss.is_fourth_subject FROM student_subjects ss JOIN subjects sub ON ss.subject_id=sub.id WHERE ss.student_id=? ORDER BY ss.is_fourth_subject DESC");$ss->execute([$s['id']]);$s['subjects']=$ss->fetchAll();}
if($ff==='with')$students=array_filter($students,fn($s)=>$s['fid']!==null);elseif($ff==='without')$students=array_filter($students,fn($s)=>$s['fid']===null);
$fc=count(array_filter($students,fn($s)=>$s['fid']!==null));$nc=count($students)-$fc;
?>
<!DOCTYPE html>
<html lang="bn"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>ছাত্র-ছাত্রী (বিষয়সহ) - স্কুল</title>
<link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<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>
*{box-sizing:border-box}
body{background:#eef1f5;font-family:'Hind Siliguri',sans-serif;color:#333}
.navbar{box-shadow:0 2px 8px rgba(0,0,0,.12)}
/* header */
.hd{background:linear-gradient(135deg,#1a3a5c,#0d2137);color:#fff;border-radius:14px;padding:20px 24px;margin-bottom:20px;box-shadow:0 6px 18px rgba(13,33,55,.25)}
.hd h3{font-weight:700;margin:0}.hd p{margin:4px 0 0;opacity:.85;font-size:.9rem}
/* stats */
.sc{background:#fff;border-radius:10px;padding:10px 14px;display:flex;align-items:center;gap:12px;box-shadow:0 1px 4px rgba(0,0,0,.07);transition:.2s;cursor:default}
.sc:hover{box-shadow:0 4px 12px rgba(0,0,0,.1)}
.sc .i{width:36px;height:36px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:1rem;flex-shrink:0}
.sc .v{font-size:1.3rem;font-weight:800;line-height:1;margin-bottom:2px}
.sc .l{font-size:.72rem;color:#888}
.sc.s1 .i{background:#eef0ff;color:#4361ee}.sc.s2 .i{background:#e6faf5;color:#06d6a0}.sc.s3 .i{background:#fff3e6;color:#fb8500}
/* filter card */
.fc{background:#fff;border-radius:12px;padding:18px 20px;margin-bottom:18px;box-shadow:0 2px 10px rgba(0,0,0,.06)}
.fl{font-size:.8rem;font-weight:600;color:#555;margin-bottom:3px}
.fg{margin-bottom:0}
.fg select,.fg input{border-radius:7px;border:1px solid #ddd;font-size:.85rem;padding:6px 10px}
/* filter pills */
.pp{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:14px}
.pp button{padding:5px 14px;border-radius:20px;border:2px solid #4361ee;background:#fff;color:#4361ee;font-size:.82rem;font-weight:600;transition:.2s;cursor:pointer}
.pp button:hover,.pp button.a{background:#4361ee;color:#fff}
.pp button.r{background:#fff;border-color:#ddd;color:#888}.pp button.r:hover{background:#eee;color:#555}
/* table */
.tw{background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 2px 10px rgba(0,0,0,.06)}
.tw table{width:100%;border-collapse:collapse}
.tw thead{background:linear-gradient(135deg,#1a3a5c,#0d2137);color:#fff}
.tw th{padding:11px 12px;font-size:.82rem;font-weight:600;white-space:nowrap;border:none;text-transform:uppercase;letter-spacing:.4px}
.tw td{padding:10px 12px;font-size:.85rem;border-bottom:1px solid #f0f0f0;vertical-align:middle}
.tw tbody tr:hover{background:#f0f7ff}
/* subject badges */
.sb{display:inline-block;padding:2px 8px;font-size:.72rem;border-radius:10px;margin:1px;font-weight:500}
.sb.r{background:#e9ecef;color:#495057}
.sb.f{background:linear-gradient(135deg,#4361ee,#764ba2);color:#fff;animation:pl 2s ease-in-out infinite}
@keyframes pl{0%,100%{transform:scale(1)}50%{transform:scale(1.06)}}
/* pagination */
.pg{margin-top:16px}
.col-hidden{display:none!important}
#ctm .dropdown-item input{vertical-align:middle}
.emp{text-align:center;padding:50px;color:#999}.emp i{font-size:3.5rem;opacity:.25;margin-bottom:12px}
@media print{.navbar,.fc,.pp,.pg,.dropdown,.btn{display:none!important}.sc{page-break-inside:avoid;border:1px solid #ddd}}
</style>
</head><body>
<nav class="navbar navbar-expand-lg navbar-dark" style="background:linear-gradient(135deg,#1a3a5c,#0d2137)">
  <div class="container-fluid">
    <a class="navbar-brand fw-bold" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#n"><span class="navbar-toggler-icon"></span></button>
    <div class="collapse navbar-collapse" id="n">
      <ul class="navbar-nav ms-auto">
        <li class="nav-item"><a class="nav-link" href="list.php"><i class="fas fa-list"></i> তালিকা</a></li>
        <li class="nav-item"><a class="nav-link active" href="#"><i class="fas fa-book"></i> বিষয়</a></li>
        <li class="nav-item"><a class="nav-link" href="../index.php"><i class="fas fa-home"></i> হোম</a></li>
      </ul>
    </div>
  </div>
</nav>

<div class="container-fluid p-3">
<?php if($msg):?><div class="alert alert-success alert-dismissible fade show py-2"><i class="fas fa-check"></i> <?=$msg?><button type="button" class="btn-close py-2" data-bs-dismiss="alert"></button></div><?php endif;?>
<?php if($err):?><div class="alert alert-danger alert-dismissible fade show py-2"><i class="fas fa-exclamation"></i> <?=$err?><button type="button" class="btn-close py-2" data-bs-dismiss="alert"></button></div><?php endif;?>

<div class="hd d-flex justify-content-between align-items-center flex-wrap gap-2">
  <div><h3><i class="fas fa-book-reader"></i> ছাত্র-ছাত্রী (বিষয়সহ)</h3><p>প্রতিটি ছাত্র-ছাত্রীর বিষয় ও চতুর্থ বিষয় তালিকা</p></div>
  <div class="d-flex gap-1">
    <button class="btn btn-sm btn-light fw-bold" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট</button>
    <button class="btn btn-sm btn-light fw-bold" onclick="exp()"><i class="fas fa-download"></i> এক্সেল</button>
    <div class="dropdown d-inline-block">
      <button class="btn btn-sm btn-light fw-bold" data-bs-toggle="dropdown"><i class="fas fa-columns"></i> কলাম</button>
      <div class="dropdown-menu dropdown-menu-end p-2" id="ctm" style="min-width:155px;font-size:.85rem">
        <?php foreach([['1','আইডি'],['2','নাম'],['3','ক্লাস'],['4','শাখা'],['5','গ্রুপ'],['6','বিষয়সমূহ'],['7','চতুর্থ বিষয়'],['8','স্ট্যাটাস']] as $c):?>
        <label class="dropdown-item px-2 py-1" style="cursor:pointer"><input type="checkbox" class="ct me-2" data-col="<?=$c[0]?>" checked><?=$c[1]?></label>
        <?php endforeach;?>
        <hr class="my-1"><button class="btn btn-sm btn-link text-decoration-none px-2 py-0" onclick="rc()" style="font-size:.8rem">রিসেট</button>
      </div>
    </div>
  </div>
</div>

<div class="row g-2 mb-3">
  <div class="col-4"><div class="sc s1"><div class="i"><i class="fas fa-users"></i></div><div><div class="v"><?=$total?></div><div class="l">মোট ছাত্র</div></div></div></div>
  <div class="col-4"><div class="sc s2"><div class="i"><i class="fas fa-star"></i></div><div><div class="v"><?=$fc?></div><div class="l">চতুর্থ সহ</div></div></div></div>
  <div class="col-4"><div class="sc s3"><div class="i"><i class="fas fa-exclamation"></i></div><div><div class="v"><?=$nc?></div><div class="l">চতুর্থ বিহীন</div></div></div></div>
</div>

<!-- ── Bulk Remove Fourth Subject Panel ─────────────────────────────────── -->
<div style="background:rgba(255,100,100,.08);border:1px solid rgba(255,100,100,.25);border-radius:10px;padding:14px 16px;margin-bottom:14px">
  <div class="d-flex align-items-center gap-2 mb-2">
    <i class="fas fa-layer-group" style="color:#f87171"></i>
    <strong style="font-size:.88rem">ক্লাসভিত্তিক চতুর্থ বিষয় বাল্ক রিমুভ</strong>
  </div>
  <form method="POST" onsubmit="return confirm('নির্বাচিত ক্লাসের সকল ছাত্র-ছাত্রীর চতুর্থ বিষয় সরিয়ে দেবেন?')">
    <input type="hidden" name="action" value="bulk_remove_fourth">
    <div class="row g-2 align-items-end">
      <div class="col-6 col-md-3">
        <label style="font-size:.75rem;font-weight:600;color:#555;display:block;margin-bottom:2px">ক্লাস <span class="text-danger">*</span></label>
        <select name="bulk_class_id" class="form-select form-select-sm" required onchange="loadGroups(this.value,'bulk_remove_group_sel')">
          <option value="">-- ক্লাস নির্বাচন --</option>
          <?php foreach($C as $c): ?>
            <option value="<?=$c['id']?>"><?=$c['name']?>-<?=$c['section']?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-3">
        <label style="font-size:.75rem;font-weight:600;color:#555;display:block;margin-bottom:2px">সেশন (ঐচ্ছিক)</label>
        <select name="bulk_session" class="form-select form-select-sm">
          <option value="">সব সেশন</option>
          <?php foreach($S as $s): ?>
            <option value="<?=$s['session_name']?>"><?=$s['session_name']?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-2">
        <label style="font-size:.75rem;font-weight:600;color:#555;display:block;margin-bottom:2px">গ্রুপ (ঐচ্ছিক)</label>
        <select name="bulk_group" id="bulk_remove_group_sel" class="form-select form-select-sm">
          <option value="">সব গ্রুপ</option>
          <?php foreach($ALL_GROUPS as $g): ?>
            <option value="<?=htmlspecialchars($g)?>"><?=htmlspecialchars($g)?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-2">
        <button type="submit" class="btn btn-sm w-100 fw-bold" style="background:linear-gradient(135deg,#f87171,#ef4444);color:#fff;border:none">
          <i class="fas fa-trash-alt me-1"></i> চতুর্থ বিষয় রিমুভ করুন
        </button>
      </div>
    </div>
  </form>
</div>

<!-- ── Bulk SET Fourth Subject Panel ────────────────────────────────────── -->
<div style="background:rgba(79,195,247,.08);border:1px solid rgba(79,195,247,.25);border-radius:10px;padding:14px 16px;margin-bottom:14px">
  <div class="d-flex align-items-center gap-2 mb-2">
    <i class="fas fa-star" style="color:#4fc3f7"></i>
    <strong style="font-size:.88rem">ক্লাস ও গ্রুপভিত্তিক চতুর্থ বিষয় বাল্ক সেট</strong>
    <span style="font-size:.72rem;color:#888">(বিদ্যমান চতুর্থ বিষয় প্রথমে clear হবে, তারপর নতুনটি সেট হবে)</span>
  </div>
  <form method="POST" onsubmit="return confirm('নির্বাচিত ক্লাসের সকল ছাত্র-ছাত্রীর চতুর্থ বিষয় পরিবর্তন করবেন?')">
    <input type="hidden" name="action" value="bulk_set_fourth">
    <div class="row g-2 align-items-end">
      <div class="col-6 col-md-3">
        <label style="font-size:.75rem;font-weight:600;color:#555;display:block;margin-bottom:2px">ক্লাস <span class="text-danger">*</span></label>
        <select name="bulk_set_class_id" id="bulk_set_class_id" class="form-select form-select-sm" required onchange="loadSubjects(this.value);loadGroups(this.value,'bulk_set_group_sel')">
          <option value="">-- ক্লাস নির্বাচন --</option>
          <?php foreach($C as $c): ?>
            <option value="<?=$c['id']?>"><?=$c['name']?>-<?=$c['section']?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-2">
        <label style="font-size:.75rem;font-weight:600;color:#555;display:block;margin-bottom:2px">সেশন (ঐচ্ছিক)</label>
        <select name="bulk_set_session" class="form-select form-select-sm">
          <option value="">সব সেশন</option>
          <?php foreach($S as $s): ?>
            <option value="<?=$s['session_name']?>"><?=$s['session_name']?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-2">
        <label style="font-size:.75rem;font-weight:600;color:#555;display:block;margin-bottom:2px">গ্রুপ (ঐচ্ছিক)</label>
        <select name="bulk_set_group" id="bulk_set_group_sel" class="form-select form-select-sm">
          <option value="">সব গ্রুপ</option>
          <?php foreach($ALL_GROUPS as $g): ?>
            <option value="<?=htmlspecialchars($g)?>"><?=htmlspecialchars($g)?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-3">
        <label style="font-size:.75rem;font-weight:600;color:#555;display:block;margin-bottom:2px">চতুর্থ বিষয় <span class="text-danger">*</span></label>
        <select name="bulk_set_subject_id" id="bulk_set_subject_id" class="form-select form-select-sm" required>
          <option value="">-- আগে ক্লাস নির্বাচন করুন --</option>
        </select>
      </div>
      <div class="col-12 col-md-2">
        <button type="submit" class="btn btn-sm w-100 fw-bold" style="background:linear-gradient(135deg,#1565c0,#1e88e5);color:#fff;border:none">
          <i class="fas fa-star me-1"></i> চতুর্থ বিষয় সেট করুন
        </button>
      </div>
    </div>
  </form>
</div>

<div class="fc">
  <div class="pp">
    <button class="<?=$ff===''?'a':''?>" onclick="qf('all')"><i class="fas fa-list"></i> সব</button>
    <button class="<?=$ff==='with'?'a':''?>" onclick="qf('with')"><i class="fas fa-star"></i> চতুর্থ বিষয় সহ</button>
    <button class="<?=$ff==='without'?'a':''?>" onclick="qf('without')"><i class="fas fa-times"></i> ছাড়া</button>
    <button class="r" onclick="window.location='?'"><i class="fas fa-redo"></i> রিসেট</button>
  </div>
  <form method="GET" id="fm" class="row g-2">
    <?php if($hs):?>
    <div class="col-6 col-md"><div class="fg"><label class="fl">সেশন</label><select name="session_id" class="form-select form-select-sm" onchange="this.form.submit()"><option value="">সব</option><?php foreach($S as $s):?><option value="<?=$s['id']?>" <?=$s['id']==$sf?'selected':''?>><?=$s['session_name']?></option><?php endforeach;?></select></div></div>
    <?php endif;?>
    <div class="col-6 col-md"><div class="fg"><label class="fl">ক্লাস</label><select name="class_id" class="form-select form-select-sm" onchange="this.form.submit()"><option value="">সব</option><?php foreach($C as $c):?><option value="<?=$c['id']?>" <?=$c['id']==$cf?'selected':''?>><?=$c['name']?>-<?=$c['section']?></option><?php endforeach;?></select></div></div>
    <div class="col-6 col-md"><div class="fg"><label class="fl">গ্রুপ</label><select name="group_name" class="form-select form-select-sm" onchange="this.form.submit()"><option value="">সব</option><?php
      // Show class-specific groups if class selected, else all groups
      $grpList = !empty($GR) ? array_column($GR,'group_name') : $ALL_GROUPS;
      foreach($grpList as $g):?><option value="<?=htmlspecialchars($g)?>" <?=$g==$gf?'selected':''?>><?=htmlspecialchars($g)?></option><?php endforeach;?></select></div></div>
    <div class="col-6 col-md"><div class="fg"><label class="fl">স্ট্যাটাস</label><select name="status" class="form-select form-select-sm" onchange="this.form.submit()"><option value="active" <?=$stf==='active'?'selected':''?>>সক্রিয়</option><option value="inactive" <?=$stf==='inactive'?'selected':''?>>নিষ্ক্রিয়</option><option value="">সব</option></select></div></div>
    <div class="col-6 col-md"><div class="fg"><label class="fl">শাখা</label><select name="section" class="form-select form-select-sm" onchange="this.form.submit()"><option value="">সব</option><?php foreach($secs as $x):?><option value="<?=$x?>" <?=$x==$scf?'selected':''?>><?=$x?></option><?php endforeach;?></select></div></div>
    <div class="col-6 col-md"><div class="fg"><label class="fl">পৃ.</label><select name="per_page" class="form-select form-select-sm" onchange="this.form.submit()"><option value="20" <?=$pp==20?'selected':''?>>20</option><option value="50" <?=$pp==50?'selected':''?>>50</option><option value="100" <?=$pp==100?'selected':''?>>100</option></select></div></div>
    <div class="col-6 col-md"><div class="fg"><label class="fl">খুঁজুন</label><input type="text" name="search" class="form-control form-control-sm" placeholder="নাম/আইডি..." value="<?=htmlspecialchars($sq)?>"></div></div>
    <div class="col-6 col-md d-flex align-items-end"><button type="submit" class="btn btn-primary btn-sm w-100 fw-bold"><i class="fas fa-search"></i> খুঁজুন</button></div>
    <input type="hidden" name="fourth_subject" value="<?=htmlspecialchars($ff)?>">
  </form>
</div>

<?php if(empty($students)):?>
<div class="emp"><i class="fas fa-search"></i><h5>কোন ছাত্র-ছাত্রী পাওয়া যায়নি</h5><a href="?" class="btn btn-primary btn-sm mt-2"><i class="fas fa-redo"></i> রিসেট</a></div>
<?php else:?>
<div class="tw table-responsive">
  <table id="tb">
    <thead><tr><th>#</th><th data-col="1">আইডি</th><th data-col="2">নাম</th><th data-col="3">ক্লাস</th><th data-col="4">শাখা</th><th data-col="5">গ্রুপ</th><th data-col="6">বিষয়সমূহ</th><th data-col="7">চতুর্থ বিষয়</th><th data-col="8">স্ট্যাটাস</th></tr></thead>
    <tbody><?php $sn=$offset+1;foreach($students as $s):?><tr>
      <td style="color:#aaa;font-size:.8rem"><?=$sn++?></td>
      <td data-col="1"><strong><?=$s['student_id']?></strong><?php if($s['roll_number']):?><br><small class="text-muted">রোল: <?=$s['roll_number']?></small><?php endif;?></td>
      <td data-col="2"><strong><?=$s['first_name']?> <?=$s['last_name']?></strong></td>
      <td data-col="3"><?=$s['cl']?></td>
      <td data-col="4"><?=$s['sc']?:'—'?></td>
      <td data-col="5"><?php if($s['group_name']):?><span class="badge bg-info"><?=$s['group_name']?></span><?php else:?><span class="text-muted">-</span><?php endif;?></td>
      <td data-col="6"><?php if(!empty($s['subjects'])):?><?php foreach($s['subjects'] as $sub):?><span class="sb <?=$sub['is_fourth_subject']?'f':'r'?>" title="<?=$sub['name']?>"><?php if($sub['is_fourth_subject']):?><i class="fas fa-star"></i> <?php endif;?><?=$sub['code']?:substr($sub['name'],0,8)?></span> <?php endforeach;?><div style="font-size:.72rem;color:#999;margin-top:3px">মোট: <?=count($s['subjects'])?></div><?php else:?><span class="text-danger" style="font-size:.82rem"><i class="fas fa-times"></i> নেই</span><?php endif;?></td>
      <td data-col="7"><?php
        $noFourth = in_array((int)$s['class_id'], NO_FOURTH_CLASSES);
        if ($noFourth):?>
          <span class="badge bg-secondary" style="font-size:.7rem" title="এই শ্রেণীতে সব বিষয় বাধ্যতামূলক"><i class="fas fa-lock"></i> সব বাধ্যতামূলক</span>
        <?php elseif(!empty($s['subjects'])):?><form method="POST" style="display:inline"><input type="hidden" name="action" value="set_fourth_subject"><input type="hidden" name="student_id" value="<?=$s['id']?>"><select name="subject_id" class="form-select form-select-sm" style="font-size:.78rem;margin-bottom:3px" onchange="this.form.submit()"><option value="">--</option><?php foreach($s['subjects'] as $sub):?><option value="<?=$sub['id']?>" <?=$sub['is_fourth_subject']?'selected':''?>><?=$sub['code']?:substr($sub['name'],0,8)?> <?php if($sub['is_fourth_subject']):?>⭐<?php endif;?></option><?php endforeach;?></select></form><?php if($s['fid']):?><button class="btn btn-outline-danger btn-sm" style="font-size:.68rem;padding:1px 5px;width:100%" onclick="rm(<?=$s['id']?>)"><i class="fas fa-times"></i> সরান</button><?php endif;
        ?><?php else:?><small class="text-muted">-</small><?php endif;?></td>
      <td data-col="8"><span class="badge <?=$s['status']==='active'?'bg-success':'bg-danger'?>"><?=$s['status']==='active'?'সক্রিয়':'নিষ্ক্রিয়'?></span></td>
    </tr><?php endforeach;?></tbody>
  </table>
</div>
<?php if($pages>1):?>
<nav class="pg"><ul class="pagination justify-content-center mb-0">
  <li class="page-item <?=$pg<=1?'disabled':''?>"><a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$pg-1]))?>"><i class="fas fa-chevron-left"></i></a></li>
  <?php $st=max(1,$pg-2);$ed=min($pages,$pg+2);if($st>1):?><li class="page-item"><a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>1]))?>">1</a></li><?php if($st>2):?><li class="page-item disabled"><span class="page-link">...</span></li><?php endif;endif;?>
  <?php for($i=$st;$i<=$ed;$i++):?><li class="page-item <?=$i==$pg?'active':''?>"><a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$i]))?>"><?=$i?></a></li><?php endfor;?>
  <?php if($ed<$pages):?><?php if($ed<$pages-1):?><li class="page-item disabled"><span class="page-link">...</span></li><?php endif;?><li class="page-item"><a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$pages]))?>"><?=$pages?></a></li><?php endif;?>
  <li class="page-item <?=$pg>=$pages?'disabled':''?>"><a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$pg+1]))?>"><i class="fas fa-chevron-right"></i></a></li>
</ul><div class="text-center text-muted mt-1" style="font-size:.82rem">পৃষ্ঠা <?=$pg?>/<?=$pages?> (<?=$total?> রেকর্ড)</div></nav>
<?php endif;endif;?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script>
function rm(i){if(confirm('চতুর্থ বিষয় সরাবেন?')){var f=document.createElement('form');f.method='POST';f.innerHTML='<input type="hidden" name="action" value="set_fourth_subject"><input type="hidden" name="student_id" value="'+i+'"><input type="hidden" name="subject_id" value="0">';document.body.appendChild(f);f.submit();}}
function qf(v){document.querySelector('[name="fourth_subject"]').value=v;document.getElementById('fm').submit();}
function exp(){var wb=XLSX.utils.table_to_book(document.getElementById('tb'),{sheet:'Students'});XLSX.writeFile(wb,'students_'+new Date().toISOString().split('T')[0]+'.xlsx');}

function loadSubjects(classId) {
    var sel = document.getElementById('bulk_set_subject_id');
    sel.innerHTML = '<option value="">লোড হচ্ছে...</option>';
    if (!classId) { sel.innerHTML = '<option value="">-- আগে ক্লাস নির্বাচন করুন --</option>'; return; }
    fetch('get_class_subjects.php?class_id=' + classId)
        .then(function(r){ return r.json(); })
        .then(function(data){
            sel.innerHTML = '<option value="">-- বিষয় নির্বাচন করুন --</option>';
            if (data.length === 0) { sel.innerHTML = '<option value="">এই ক্লাসে কোন বিষয় নেই</option>'; return; }
            data.forEach(function(s){
                sel.innerHTML += '<option value="'+s.id+'">'+s.name+(s.code?' ('+s.code+')':'')+' </option>';
            });
        })
        .catch(function(){ sel.innerHTML = '<option value="">লোড ব্যর্থ হয়েছে</option>'; });
}

function loadGroups(classId, selId) {
    var sel = document.getElementById(selId);
    if (!sel) return;
    if (!classId) {
        sel.innerHTML = '<option value="">সব গ্রুপ</option>';
        return;
    }
    sel.innerHTML = '<option value="">লোড হচ্ছে...</option>';
    fetch('get_class_subjects.php?groups=1&class_id=' + encodeURIComponent(classId))
        .then(function(r){ return r.json(); })
        .then(function(data){
            sel.innerHTML = '<option value="">সব গ্রুপ</option>';
            if (!Array.isArray(data) || data.length === 0) return;
            data.forEach(function(g){
                // data is plain string array now
                var name = (typeof g === 'string') ? g : String(g.group_name || g || '');
                name = name.trim();
                if (name) {
                    var opt = document.createElement('option');
                    opt.value = name;
                    opt.textContent = name;
                    sel.appendChild(opt);
                }
            });
        })
        .catch(function(){ sel.innerHTML = '<option value="">গ্রুপ লোড ব্যর্থ</option>'; });
}
setTimeout(function(){document.querySelectorAll('.alert-dismissible').forEach(function(a){new bootstrap.Alert(a).close()})},5000);
(function(){var k='sws_cols',tb=document.getElementById('tb');if(!tb)return;
function a(c,h){tb.querySelectorAll('[data-col="'+c+'"]').forEach(function(e){if(h)e.classList.add('col-hidden');else e.classList.remove('col-hidden')});var b=document.querySelector('.ct[data-col="'+c+'"]');if(b)b.checked=!h}
function s(){var o={};document.querySelectorAll('.ct').forEach(function(b){o[b.dataset.col]=!b.checked});localStorage.setItem(k,JSON.stringify(o))}
try{var v=JSON.parse(localStorage.getItem(k));if(v)Object.keys(v).forEach(function(c){a(c,v[c])})}catch(e){}
document.getElementById('ctm').addEventListener('change',function(e){var b=e.target.closest('.ct');if(!b)return;a(b.dataset.col,!b.checked);s()});
window.rc=function(){document.querySelectorAll('.ct').forEach(function(b){a(b.dataset.col,false)});localStorage.removeItem(k)}})();
</script>
</body></html>
