<?php
session_start();require_once'../config/database.php';
if(!isset($_SESSION['user_id'])||$_SESSION['user_role']!='admin'){header('Location: ../login.php');exit;}
$s=$e='';
$eid=isset($_GET['class_id'])?(int)$_GET['class_id']:0;
$ce=null;$cet=[];
if($eid>0){$q=$pdo->prepare("SELECT*FROM classes WHERE id=?");$q->execute([$eid]);$ce=$q->fetch();
  if($ce){$q=$pdo->prepare("SELECT ct.teacher_id,t.first_name,t.last_name,ct.assignment_type FROM class_teachers ct JOIN teachers t ON ct.teacher_id=t.id WHERE ct.class_id=? AND ct.status='active' ORDER BY ct.assignment_type,t.first_name,t.last_name");$q->execute([$eid]);$cet=$q->fetchAll();}
}
if($_SERVER['REQUEST_METHOD']=='POST'&&isset($_POST['create_class'])){
  $n=trim($_POST['name']??'');$sc=trim($_POST['section']??'');$c=(int)($_POST['capacity']??40);$ctid=!empty($_POST['class_teacher_id'])?(int)$_POST['class_teacher_id']:null;$ats=isset($_POST['additional_teachers'])?array_map('intval',$_POST['additional_teachers']):[];
  if(!$n)$e='ক্লাসের নাম প্রয়োজন';
  else{try{$pdo->beginTransaction();$q=$pdo->prepare("SELECT COUNT(*)FROM classes WHERE name=? AND (section=? OR (section='' AND ?=''))");$q->execute([$n,$sc,$sc]);
    if($q->fetchColumn()>0)$e='এই নাম ও শাখার ক্লাস ইতিমধ্যে বিদ্যমান';
    else{$q=$pdo->prepare("INSERT INTO classes(name,section,class_teacher_id,capacity)VALUES(?,?,?,?)");$q->execute([$n,$sc,$ctid,$c]);$cid=$pdo->lastInsertId();
      if($ctid){$q=$pdo->prepare("INSERT INTO class_teachers(class_id,teacher_id,assignment_type,assigned_by,status)VALUES(?,?,'primary',?,'active')");$q->execute([$cid,$ctid,$_SESSION['user_id']??null]);}
      foreach($ats as$tid){if($tid!=$ctid){$q=$pdo->prepare("INSERT INTO class_teachers(class_id,teacher_id,assignment_type,assigned_by,status)VALUES(?,?,'assistant',?,'active')");$q->execute([$cid,$tid,$_SESSION['user_id']??null]);}}
      $pdo->commit();$s='ক্লাস সফলভাবে তৈরি হয়েছে';$_POST=[];}
  }catch(Exception$x){$pdo->rollBack();$e='ক্লাস তৈরিতে সমস্যা: '.$x->getMessage();}}
}
if(isset($_POST['direct_delete_class'])&&isset($_POST['class_id'])){
  $did=(int)$_POST['class_id'];
  if($did>0){try{$q=$pdo->prepare("SELECT COUNT(*)FROM students WHERE class_id=? AND status='active'");$q->execute([$did]);
    if($q->fetchColumn()>0)$e='এই ক্লাসে ছাত্র আছে, মুছে ফেলা যাবে না';
    else{$pdo->beginTransaction();$pdo->prepare("DELETE FROM class_teachers WHERE class_id=?")->execute([$did]);$pdo->prepare("DELETE FROM class_subjects WHERE class_id=?")->execute([$did]);$pdo->prepare("DELETE FROM classes WHERE id=?")->execute([$did]);$pdo->commit();$s='ক্লাস মুছে ফেলা হয়েছে';header('Location: manage.php?d=1&m='.urlencode($s));exit();}
  }catch(Exception$x){if($pdo->inTransaction())$pdo->rollBack();$e='মুছতে সমস্যা: '.$x->getMessage();}}else $e='অবৈধ আইডি';
}
if(isset($_GET['d'])&&isset($_GET['m']))$s=urldecode($_GET['m']);
if(isset($_POST['reset_assistant_teachers'])){
  $rid=(int)$_POST['class_id'];
  if($rid>0){try{$pdo->prepare("DELETE FROM class_teachers WHERE class_id=? AND assignment_type='assistant'")->execute([$rid]);$s='সহায়ক শিক্ষক রিসেট হয়েছে';}catch(Exception$x){$e='রিসেটে সমস্যা: '.$x->getMessage();}}else $e='অবৈধ আইডি';
}
if(isset($_POST['assign_subjects'])){
  $cid=(int)$_POST['class_id'];$subs=isset($_POST['subjects'])?array_map('intval',$_POST['subjects']):[];
  if($cid>0){try{$pdo->beginTransaction();$q=$pdo->prepare("SELECT subject_id FROM class_subjects WHERE class_id=?");$q->execute([$cid]);$es=$q->fetchAll(PDO::FETCH_COLUMN);
    $add=array_diff($subs,$es);$rem=array_diff($es,$subs);
    if($add){$q=$pdo->prepare("INSERT INTO class_subjects(class_id,subject_id)VALUES(?,?)");foreach($add as$sid)$q->execute([$cid,$sid]);}
    if($rem){$in=implode(',',array_fill(0,count($rem),'?'));$pdo->prepare("DELETE FROM class_subjects WHERE class_id=? AND subject_id IN($in)")->execute(array_merge([$cid],$rem));}
    $pdo->commit();$s='বিষয় নির্ধারণ সফল';}catch(Exception$x){$pdo->rollBack();$e='বিষয় নির্ধারণে সমস্যা: '.$x->getMessage();}}else $e='ক্লাস নির্বাচন করুন';
}
if(isset($_POST['update_class'])){
  $uid=(int)($_POST['id']??0);$n=trim($_POST['name']??'');$sc=trim($_POST['section']??'');$c=(int)($_POST['capacity']??0);$ctid=!empty($_POST['class_teacher_id'])?(int)$_POST['class_teacher_id']:null;$ats=isset($_POST['additional_teachers'])?array_map('intval',$_POST['additional_teachers']):[];$st=$_POST['status']??'active';$d=trim($_POST['description']??'');
  if($uid<=0||!$n)$e='প্রয়োজনীয় তথ্য দিন';
  else{try{$pdo->beginTransaction();$q=$pdo->prepare("SELECT COUNT(*)FROM classes WHERE name=? AND (section=? OR (section='' AND ?='')) AND id<>?");$q->execute([$n,$sc,$sc,$uid]);
    if($q->fetchColumn()>0)$e='এই নাম ও শাখার ক্লাস বিদ্যমান';
    else{$pdo->prepare("UPDATE classes SET name=?,section=?,class_teacher_id=?,capacity=?,status=?,description=? WHERE id=?")->execute([$n,$sc,$ctid,$c,$st,$d,$uid]);
      $pdo->prepare("DELETE FROM class_teachers WHERE class_id=?")->execute([$uid]);
      if($ctid){$q=$pdo->prepare("INSERT INTO class_teachers(class_id,teacher_id,assignment_type,assigned_by,status)VALUES(?,?,'primary',?,'active')");$q->execute([$uid,$ctid,$_SESSION['user_id']??null]);}
      foreach($ats as$tid){if($tid!=$ctid){$q=$pdo->prepare("INSERT INTO class_teachers(class_id,teacher_id,assignment_type,assigned_by,status)VALUES(?,?,'assistant',?,'active')");$q->execute([$uid,$tid,$_SESSION['user_id']??null]);}}
      $pdo->commit();header('Location: manage.php?class_id='.$uid);exit();}
  }catch(Exception$x){$pdo->rollBack();$e='আপডেটে সমস্যা: '.$x->getMessage();}}
}
$ts=$pdo->query("SELECT t.id,t.first_name,t.last_name FROM teachers t WHERE t.status='active' ORDER BY t.first_name,t.last_name")->fetchAll();
$subs=$pdo->query("SELECT id,name,code FROM subjects WHERE status='active' ORDER BY name")->fetchAll();
$cls=$pdo->prepare("SELECT c.*,COUNT(DISTINCT s.id)sc,COUNT(DISTINCT cs.subject_id)scnt FROM classes c LEFT JOIN students s ON c.id=s.class_id AND s.status='active' LEFT JOIN class_subjects cs ON c.id=cs.class_id WHERE c.status='active' GROUP BY c.id ORDER BY c.name,c.section");$cls->execute();$cls=$cls->fetchAll();
foreach($cls as&$x){$q=$pdo->prepare("SELECT ct.assignment_type,CONCAT(t.first_name,' ',t.last_name)tn FROM class_teachers ct JOIN teachers t ON ct.teacher_id=t.id WHERE ct.class_id=? AND ct.status='active' ORDER BY ct.assignment_type");$q->execute([$x['id']]);$x['teachers']=$q->fetchAll();$p=array_filter($x['teachers'],fn($t)=>$t['assignment_type']=='primary');$x['teacher_name']=!empty($p)?reset($p)['tn']:'';}
unset($x);
$stt=$pdo->query("SELECT COUNT(*)tc,SUM(capacity)tp,(SELECT COUNT(*)FROM students WHERE status='active')ts FROM classes c WHERE c.status='active'")->fetch();
function h($s){return htmlspecialchars($s,ENT_QUOTES,'UTF-8');}
?><!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>ক্লাস ব্যবস্থাপনা</title>
<style>
*,body{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Hind Siliguri',Arial,'Siyam Rupali','Noto Sans Bengali',sans-serif;background:#1a1818;height:100vh;overflow:hidden;color:#d4ccc4;display:flex;flex-direction:column}
.h{background:#2a2725;color:#d4ccc4;padding:7px 14px;display:flex;align-items:center;justify-content:space-between;font-size:.8rem;flex-shrink:0;border-bottom:1px solid #3a3735}
.h a{color:#a09888;text-decoration:none;font-size:.74rem;padding:3px 8px;border-radius:5px;transition:all .2s}
.h a:hover{background:rgba(255,255,255,.06);color:#d4ccc4}
.w{flex:1;overflow:hidden;max-width:100%;margin:0 auto;display:flex;flex-direction:column}
.sr{display:flex;gap:8px;margin-bottom:6px;flex-shrink:0}
.sr>div{flex:1;background:#1e1c1b;border:1px solid #3a3735;border-radius:8px;display:flex;align-items:center;gap:8px;padding:8px 12px}
.sr i{width:30px;height:30px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:.85rem;flex-shrink:0}
.sr b{font-size:1.1rem;font-weight:700;display:block;line-height:1.2}.sr small{font-size:.65rem;color:#706860}
.mn{flex:1;overflow:hidden;display:grid;grid-template-columns:1fr 1.8fr;gap:10px}@media(max-width:900px){.mn{grid-template-columns:1fr}}
.c{background:#252220;border-radius:10px;border:1px solid #3a3735;display:flex;flex-direction:column;overflow:hidden}
.ct{background:#2f2c2a;padding:6px 10px;font-size:.75rem;font-weight:600;display:flex;align-items:center;gap:4px;border-bottom:1px solid #3a3735;flex-shrink:0}
.cb{padding:5px 8px;flex:1;overflow-y:auto}
.cb::-webkit-scrollbar{width:3px}.cb::-webkit-scrollbar-thumb{background:#3a3735;border-radius:3px}
label{font-size:.65rem;font-weight:600;color:#a09888;display:block;margin-bottom:1px}
input,select,textarea{width:100%;padding:3px 6px;border:1px solid #3a3735;border-radius:4px;font-size:.7rem;outline:none;font-family:inherit;background:#1e1c1b;transition:all .2s;color:#d4ccc4}
input:focus,select:focus,textarea:focus{border-color:#6a6058;background:#22201f}
textarea{resize:none;min-height:24px;height:24px}
.btn{display:inline-flex;align-items:center;gap:2px;padding:3px 8px;border:none;border-radius:4px;font-size:.7rem;font-weight:600;cursor:pointer;text-decoration:none;font-family:inherit;transition:all .2s;white-space:nowrap}
.btn-g{background:linear-gradient(135deg,#6a7a60,#5a6a50);color:#e8e4dc}.btn-g:hover{box-shadow:0 2px 6px rgba(74,90,60,.3)}
.btn-o{background:linear-gradient(135deg,#8a7a5a,#7a6a4a);color:#e8e4dc}.btn-o:hover{box-shadow:0 2px 6px rgba(90,70,40,.3)}
.btn-r{background:linear-gradient(135deg,#8a5a4a,#7a4a3a);color:#e8e4dc}.btn-r:hover{box-shadow:0 2px 6px rgba(122,74,58,.3)}
.btn-b{background:linear-gradient(135deg,#6a7a8a,#5a6a7a);color:#e8e4dc}.btn-b:hover{box-shadow:0 2px 6px rgba(90,106,122,.3)}
.btn-p{background:linear-gradient(135deg,#7a5a7a,#6a4a6a);color:#e8e4dc}.btn-p:hover{box-shadow:0 2px 6px rgba(106,74,106,.3)}
.btn-s{background:#3a3735;color:#a09888}.btn-s:hover{background:#4a4745}.btn-sm{padding:2px 6px;font-size:.65rem}
.a{padding:4px 8px;border-radius:4px;font-size:.68rem;margin-bottom:4px;display:flex;align-items:center;gap:3px}
.a-s{background:#1a2a18;color:#7aaa6a;border:1px solid #2a3a28}.a-d{background:#2a1818;color:#ca7a6a;border:1px solid #3a2828}
.t{width:100%;border-collapse:collapse;font-size:.68rem}
.t th{text-align:left;padding:3px 5px;background:#2a2725;border-bottom:1px solid #3a3735;font-weight:600;color:#a09888;white-space:nowrap;font-size:.65rem}
.t td{padding:3px 5px;border-bottom:1px solid #2a2725;vertical-align:middle}.t tr:hover td{background:#2a2725}
.bdg{display:inline-block;padding:1px 6px;border-radius:8px;font-size:.63rem;font-weight:600}
.bdg-g{background:#1a2a18;color:#7aaa6a}.bdg-b{background:#1a2228;color:#6a8a9a}.bdg-o{background:#2a2218;color:#9a8a6a}.bdg-s{background:#2a2725;color:#706860}.bdg-p{background:#221a22;color:#8a6a8a}
.mt{margin-top:3px}.mb{margin-bottom:2px}.gap{display:flex;gap:4px;flex-wrap:wrap}
.chk{display:flex;align-items:center;gap:3px;font-size:.68rem;padding:1px 0}
.chk input{width:auto}
.mt{margin-top:3px}
</style></head><body>
<nav class=h><div>🎓 স্কুল ম্যানেজমেন্ট</div><div><a href=../index.php>🏠 হোম</a><a href=add.php>✨ নতুন ক্লাস</a><a href=../logout.php>🚪 লগআউট</a></div></nav>
<div class=w>
<div class=sr>
<div><i style=background:#3a3735;color:#8a9aaa>🏫</i><div><b style=color:#8a9aaa><?=$stt['tc']?:0?></b><small>মোট ক্লাস</small></div></div>
<div><i style=background:#3a3735;color:#7aaa6a>👥</i><div><b style=color:#7aaa6a><?=$stt['ts']?:0?></b><small>শিক্ষার্থী</small></div></div>
<div><i style=background:#3a3735;color:#caaa6a>📋</i><div><b style=color:#caaa6a><?=$stt['tp']?:0?></b><small>ধারণক্ষমতা</small></div></div>
</div>
<?php if($s):?><div class="a a-s">✓ <?=h($s)?></div><?php endif;if($e):?><div class="a a-d">⚠ <?=h($e)?></div><?php endif;?>
<div class=mn>
<div>
<?php if($ce):?>
<div class=c style=margin-bottom:6px>
<div class=ct style=background:#2a2725>✏️ সম্পাদনা #<?=$ce['id']?></div>
<div class=cb>
<form method=post action=""><input type=hidden name=id value=<?=$ce['id']?>>
<div style=display:grid;grid-template-columns:1fr 1fr;gap:3px>
<div><label>নাম *</label><input type=text name=name value="<?=h($ce['name'])?>" required></div>
<div><label>শাখা</label><input type=text name=section value="<?=h($ce['section'])?>"></div>
<div><label>প্রধান শিক্ষক</label><select name=class_teacher_id><option value="">নির্বাচন</option><?php foreach($ts as$t):?><option value=<?=$t['id']?> <?=$ce['class_teacher_id']==$t['id']?'selected':''?>><?=h($t['first_name'].' '.$t['last_name'])?></option><?php endforeach;?></select></div>
<div><label>ধারণক্ষমতা</label><input type=number name=capacity value=<?=(int)$ce['capacity']?> min=1 max=1000></div>
<div><label>স্ট্যাটাস</label><select name=status><option value=active <?=$ce['status']=='active'?'selected':''?>>✅ সক্রিয়</option><option value=inactive <?=$ce['status']=='inactive'?'selected':''?>>⛔ নিষ্ক্রিয়</option></select></div>
</div>
<div class=mt><label>অতিরিক্ত শিক্ষক</label><select name=additional_teachers[] multiple size=2 style=min-height:36px><?php foreach($ts as$t):$sel='';foreach($cet as$ctt){if($ctt['teacher_id']==$t['id']&&$ctt['assignment_type']=='assistant'){$sel='selected';break;}}?><option value=<?=$t['id']?> <?=$sel?>><?=h($t['first_name'].' '.$t['last_name'])?></option><?php endforeach;?></select></div>
<div class=mt><label>বিবরণ</label><textarea name=description><?=h($ce['description']??'')?></textarea></div>
<div class="gap mt"><button class="btn btn-o" name=update_class>💾 আপডেট</button><?php if(!empty($cet)):?><button class="btn btn-s btn-sm" onclick="r(<?=$ce['id']?>)">🔄 রিসেট</button><?php endif;?><a href=manage.php class="btn btn-s">✖ বাতিল</a></div>
</form>
</div></div>
<?php endif;?>
<div class=c style=margin-bottom:6px>
<div class=ct>✨ নতুন ক্লাস</div>
<div class=cb>
<form method=post action="">
<div style=display:grid;grid-template-columns:1fr 1fr;gap:3px>
<div><label>নাম *</label><input type=text name=name value="<?=h($_POST['name']??'')?>" placeholder='প্রথম শ্রেণী' required></div>
<div><label>শাখা</label><input type=text name=section value="<?=h($_POST['section']??'')?>" placeholder='ক, খ'></div>
<div><label>প্রধান শিক্ষক</label><select name=class_teacher_id><option value="">নির্বাচন</option><?php foreach($ts as$t):?><option value=<?=$t['id']?> <?=(($_POST['class_teacher_id']??'')==$t['id'])?'selected':''?>><?=h($t['first_name'].' '.$t['last_name'])?></option><?php endforeach;?></select></div>
<div><label>ধারণক্ষমতা</label><input type=number name=capacity value="<?=h($_POST['capacity']??'40')?>" min=1 max=1000></div>
</div>
<div class=mt><label>অতিরিক্ত শিক্ষক</label><select name=additional_teachers[] multiple size=2 style=min-height:36px><?php foreach($ts as$t):?><option value=<?=$t['id']?> <?=(isset($_POST['additional_teachers'])&&is_array($_POST['additional_teachers'])&&in_array($t['id'],$_POST['additional_teachers']))?'selected':''?>><?=h($t['first_name'].' '.$t['last_name'])?></option><?php endforeach;?></select></div>
<div class=mt><button class="btn btn-g" name=create_class>💾 তৈরি</button></div>
</form>
</div></div>
<div class=c>
<div class=ct>📚 বিষয়</div>
<div class=cb>
<form method=post action="">
<div class=mb><label>ক্লাস</label><select name=class_id required style=font-size:.68rem><option value="">নির্বাচন</option><?php foreach($cls as$x):?><option value=<?=$x['id']?>><?=h($x['name'].' - '.$x['section'])?></option><?php endforeach;?></select></div>
<div style=display:grid;grid-template-columns:repeat(3,1fr);gap:1px><?php foreach($subs as$sb):?><label class=chk><input type=checkbox name=subjects[] value=<?=$sb['id']?>><span><?=h($sb['name'])?></span></label><?php endforeach;?></div>
<div class=mt><button class="btn btn-p" name=assign_subjects>✅ নির্ধারণ</button></div>
</form>
</div></div>
</div>
<div>
<div class=c>
<div class=ct>📋 ক্লাস তালিকা</div>
<div class=cb>
<?php if(empty($cls)):?><div style=text-align:center;padding:12px;color:#706860;font-size:.72rem>কোন ক্লাস নেই</div>
<?php else:?>
<table class=t><thead><tr><th>ক্লাস</th><th>শিক্ষক</th><th>ছাত্র</th><th>বিষয়</th><th>কার্যক্রম</th></tr></thead>
<tbody><?php foreach($cls as$x):?><tr>
<td><strong style=color:#8a9aaa><?=h($x['name'])?></strong><div style=font-size:.63rem;color:#706860>শাখা: <?=h($x['section']?:'—')?> | ধারণ: <?=$x['capacity']?></div></td>
<td><?php if(!empty($x['teachers'])):?><?php foreach($x['teachers'] as$t):?><div style=font-size:.65rem;margin-bottom:1px><?=h($t['tn'])?> <span class="bdg <?=$t['assignment_type']=='primary'?'bdg-b':'bdg-s'?>" style=font-size:.6rem><?=$t['assignment_type']=='primary'?'প্রধান':'সহায়ক'?></span></div><?php endforeach;?><?php else:?><span style=color:#706860;font-size:.65rem>—</span><?php endif;?></td>
<td><span class="bdg bdg-g"><?=$x['sc']?></span></td>
<td><span class="bdg bdg-p"><?=$x['scnt']?></span></td>
<td><div class=gap><a href=../students/list.php?class_id=<?=$x['id']?> class="btn btn-b btn-sm">👥</a><a href=?class_id=<?=$x['id']?> class="btn btn-o btn-sm">✏️</a><button class="btn btn-r btn-sm" onclick="dc(<?=$x['id']?>,'<?=h($x['name'].(!empty($x['section'])?' - '.$x['section']:''))?>')">🗑️</button></div></td>
</tr><?php endforeach;?></tbody></table>
<?php endif;?>
</div></div>
<div style=display:flex;gap:4px;margin-top:4px;flex-wrap:wrap><a href=../students/add.php class="btn btn-g btn-sm">👤 ছাত্র</a><a href=../teachers/add.php class="btn btn-b btn-sm">👨‍🏫 শিক্ষক</a><a href=../attendance/mark.php class="btn btn-o btn-sm">📅 উপস্থিতি</a><a href=../exams/manage.php class="btn btn-p btn-sm">📝 পরীক্ষা</a></div>
</div></div></div>
<script>
function dc(i,n){if(confirm('"'+n+'" মুছে ফেলবেন?')){var f=document.createElement('form');f.method='POST';f.action='';var a=document.createElement('input');a.type='hidden';a.name='class_id';a.value=i;var b=document.createElement('input');b.type='hidden';b.name='direct_delete_class';b.value='1';f.appendChild(a);f.appendChild(b);document.body.appendChild(f);f.submit()}}
function r(i){if(confirm('সহায়ক শিক্ষক রিসেট করবেন?')){var f=document.createElement('form');f.method='POST';f.action='';var a=document.createElement('input');a.type='hidden';a.name='class_id';a.value=i;var b=document.createElement('input');b.type='hidden';b.name='reset_assistant_teachers';b.value='1';f.appendChild(a);f.appendChild(b);document.body.appendChild(f);f.submit()}}
setTimeout(function(){document.querySelectorAll('.a').forEach(function(e){e.remove()})},5000);
</script></body></html>
