<?php
session_start();require_once'../config/database.php';
if(!isset($_SESSION['user_id'])||($_SESSION['user_role']!='admin'&&$_SESSION['user_role']!='teacher')){header('Location: ../login.php');exit();}
$sm='';$em='';
if($_SERVER['REQUEST_METHOD']=='POST'&&isset($_POST['action'])){
switch($_POST['action']){
case'add_subject':$n=trim($_POST['name']);$c=trim($_POST['code']);$d=trim($_POST['description']);
if(empty($n)||empty($c))$em='নাম এবং কোড প্রয়োজন';else{try{$pdo->prepare("INSERT INTO subjects(name,code,description)VALUES(?,?,?)")->execute([$n,$c,$d]);$sm='বিষয় যোগ করা হয়েছে';}catch(Exception$e){$em=strpos($e->getMessage(),'Duplicate')!==false?'এই কোড ইতিমধ্যে আছে':'বিষয় যোগ করতে সমস্যা';}}
break;
case'assign_to_class':$cid=$_POST['class_id'];$sids=$_POST['subject_ids']??[];
if(empty($cid)||empty($sids))$em='ক্লাস এবং বিষয় নির্বাচন করুন';else{try{$pdo->beginTransaction();$pdo->prepare("DELETE FROM class_subjects WHERE class_id=?")->execute([$cid]);$s=$pdo->prepare("INSERT INTO class_subjects(class_id,subject_id)VALUES(?,?)");foreach($sids as$sid)$s->execute([$cid,$sid]);$pdo->commit();$sm='ক্লাসে বিষয় নির্ধারণ করা হয়েছে';}catch(Exception$e){$pdo->rollBack();$em='বিষয় নির্ধারণে সমস্যা';}}
break;
case'add_group':$gn=trim($_POST['group_name']);$gc=strtoupper(trim($_POST['group_code']));$gd=trim($_POST['group_description']);$gs=$_POST['group_status']??'active';
if($gn===''||$gc==='')$em='গ্রুপ নাম এবং কোড প্রয়োজন';else{try{$c=$pdo->prepare("SELECT COUNT(*)FROM student_groups WHERE group_code=?");$c->execute([$gc]);if($c->fetchColumn()>0)throw new Exception('এই কোড ইতিমধ্যে আছে');
$pdo->prepare("INSERT INTO student_groups(group_name,group_code,description,status)VALUES(?,?,?,?)")->execute([$gn,$gc,$gd,$gs]);$sm='গ্রুপ যোগ করা হয়েছে';}catch(Exception$e){$em=$e->getMessage()?:'গ্রুপ যোগ করতে সমস্যা';}}
break;
case'update_group':$id=(int)($_POST['id']??0);$gn=trim($_POST['group_name']);$gc=strtoupper(trim($_POST['group_code']));$gd=trim($_POST['group_description']);$gs=$_POST['group_status']??'active';
if($id<=0||$gn===''||$gc==='')$em='অবৈধ ইনপুট';else{try{$c=$pdo->prepare("SELECT COUNT(*)FROM student_groups WHERE group_code=? AND id!=?");$c->execute([$gc,$id]);if($c->fetchColumn()>0)throw new Exception('এই কোড ইতিমধ্যে আছে');
$pdo->prepare("UPDATE student_groups SET group_name=?,group_code=?,description=?,status=? WHERE id=?")->execute([$gn,$gc,$gd,$gs,$id]);$sm='গ্রুপ আপডেট হয়েছে';}catch(Exception$e){$em=$e->getMessage()?:'গ্রুপ আপডেটে সমস্যা';}}
break;
case'delete_group':$id=(int)($_POST['id']??0);try{$r=$pdo->prepare("SELECT COUNT(*)FROM students WHERE group_name=(SELECT group_name FROM student_groups WHERE id=? LIMIT 1)");$r->execute([$id]);if($r->fetchColumn()>0)throw new Exception('গ্রুপটি শিক্ষার্থীদের সাথে যুক্ত');
$pdo->prepare("DELETE FROM student_groups WHERE id=?")->execute([$id]);$sm='গ্রুপ মুছে ফেলা হয়েছে';}catch(Exception$e){$em=$e->getMessage()?:'গ্রুপ ডিলিট করতে সমস্যা';}
break;}}
$subjects=$pdo->query("SELECT*FROM subjects WHERE status='active' ORDER BY name")->fetchAll();
$classes=$pdo->query("SELECT id,name,section FROM classes WHERE status='active' ORDER BY name,section")->fetchAll();
$class_subjects=[];if(!empty($classes)){$a=$pdo->query("SELECT cs.class_id,cs.subject_id,s.name subject_name,s.code subject_code FROM class_subjects cs JOIN subjects s ON cs.subject_id=s.id WHERE s.status='active' ORDER BY s.name")->fetchAll();foreach($a as$v)$class_subjects[$v['class_id']][]=$v;}
$groups=$pdo->query("SELECT*FROM student_groups ORDER BY group_name")->fetchAll();
function h($s){return htmlspecialchars($s);}
?><!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"><link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
<style>
:root{--p:#6C63FF;--s:#A855F7;--g:#34D399;--o:#FB923C;--bg1:#0F0C29;--bg2:#302B63;--bg3:#24243E}
body{font-family:'Hind Siliguri',sans-serif;background:linear-gradient(135deg,#0F0C29,#302B63,#24243E);min-height:100vh;font-size:.85rem;color:#fff}
.navbar{background:linear-gradient(135deg,#1a1a3e,#2d1b69)!important;padding:5px 0!important;border-bottom:1px solid rgba(168,85,247,.2)}
.fc{background:rgba(255,255,255,.06);backdrop-filter:blur(16px);border-radius:14px;box-shadow:0 8px 32px rgba(0,0,0,.25);border:1px solid rgba(255,255,255,.08);overflow:hidden;margin-bottom:14px}
.fc .ch{background:linear-gradient(135deg,rgba(108,99,255,.35),rgba(168,85,247,.25));color:#fff;border:none;padding:7px 12px;font-weight:700;font-size:.88rem;backdrop-filter:blur(4px)}
.fc .cb{padding:10px 12px}.fl{font-weight:600;color:#fff;margin-bottom:2px;font-size:.78rem}
.fc-i,.fs{background:#1e1b4b;border:1px solid rgba(255,255,255,.12);border-radius:8px;padding:5px 9px;font-size:.82rem;transition:.3s;width:100%;color:#fff}
.fc-i:focus,.fs:focus{border-color:var(--p);box-shadow:0 0 0 3px rgba(108,99,255,.2);outline:none}
.fc-i option,.fs option{background:#1e1b4b;color:#fff}
.fc-i::placeholder,.fs::placeholder{color:rgba(255,255,255,.3)}
.btn-p{background:linear-gradient(135deg,var(--p),var(--s));border:none;border-radius:8px;padding:5px 16px;font-weight:700;font-size:.82rem;box-shadow:0 4px 14px rgba(108,99,255,.3)}.btn-p:hover{transform:translateY(-1px);box-shadow:0 6px 20px rgba(108,99,255,.4)}
.nav-tabs{border-bottom:1px solid rgba(255,255,255,.08)}.nav-tabs .nav-link{color:rgba(255,255,255,.6);font-weight:600;font-size:.82rem;border:none;padding:7px 14px;border-radius:0;margin-right:2px;transition:.3s}
.nav-tabs .nav-link:hover{color:#fff;background:rgba(255,255,255,.04)}
.nav-tabs .nav-link.active{background:linear-gradient(135deg,var(--p),var(--s));color:#fff;border-radius:8px 8px 0 0;box-shadow:0 -2px 12px rgba(108,99,255,.25);border:none}
.table{color:#fff!important;margin-bottom:0}.table th{background:linear-gradient(135deg,rgba(108,99,255,.4),rgba(168,85,247,.3));color:#fff!important;font-weight:600;font-size:.75rem;padding:6px 8px!important;border:none}
.table td{padding:5px 8px!important;vertical-align:middle;font-size:.8rem;border-color:rgba(255,255,255,.06);color:#fff!important}.table-hover tbody tr:hover{background:rgba(255,255,255,.04)}
.cc{background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06);border-radius:10px;overflow:hidden;margin-bottom:10px}
.cc .cch{background:rgba(255,255,255,.06);padding:6px 10px;font-weight:600;font-size:.82rem;border-bottom:1px solid rgba(255,255,255,.06);color:#fff}
.empty{text-align:center;padding:20px;color:rgba(255,255,255,.45);font-size:.82rem}
.alert{backdrop-filter:blur(8px);border:none;border-radius:8px}.alert-success{background:rgba(52,211,153,.15);color:#fff}.alert-danger{background:rgba(239,68,68,.15);color:#fff}
.form-text{color:rgba(255,255,255,.55)!important}
.modal-content{background:linear-gradient(135deg,#1e1b4b,#0f0c29);border:1px solid rgba(255,255,255,.1);color:#fff}.modal-header{border-bottom:1px solid rgba(255,255,255,.08)}.modal-footer{border-top:1px solid rgba(255,255,255,.08)}
.btn-close{filter:invert(1) brightness(200%)}
.text-muted{color:rgba(255,255,255,.55)!important}
.form-check-input{background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.2)}.form-check-input:checked{background:var(--p);border-color:var(--p)}
.form-check-label{color:#fff}
.badge{font-weight:500}.bg-success{background:rgba(52,211,153,.2)!important;color:#fff!important}.bg-secondary{background:rgba(255,255,255,.1)!important;color:rgba(255,255,255,.55)!important}
.btn-light{background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.15);color:#fff}.btn-light:hover{background:rgba(255,255,255,.2);color:#fff}
.btn-outline-primary{color:#818cf8;border-color:#818cf8}.btn-outline-primary:hover{background:#818cf8;border-color:#818cf8;color:#fff}
.btn-outline-info{color:#22d3ee;border-color:#22d3ee}.btn-outline-info:hover{background:#22d3ee;border-color:#22d3ee;color:#fff}
.btn-outline-warning{color:#fbbf24;border-color:#fbbf24}.btn-outline-warning:hover{background:#fbbf24;border-color:#fbbf24;color:#000}
.btn-outline-danger{color:#f87171;border-color:#f87171}.btn-outline-danger:hover{background:#f87171;border-color:#f87171;color:#fff}
body,.card,.card-body,.card-header,.btn,.form-label,.form-select,.form-control,.form-check,.nav-link,.list-group-item,.table,.table td,.table th,.table tr,td,th,tr,.btn i,a,a:hover,i,span,small,p,h1,h2,h3,h4,h5,h6,div,label,select,option,input,textarea,strong,b,em{color:#fff!important}
@media(max-width:576px){.nav-tabs .nav-link{font-size:.75rem;padding:5px 8px}}
</style></head>
<body>
<nav class="navbar navbar-expand navbar-dark"><div class="container-fluid px-3"><a class="navbar-brand fw-bold" style="font-size:.9rem" href="../index.php"><i class="fas fa-cog me-1"></i>বিষয় ব্যবস্থাপনা</a>
<div class="navbar-nav ms-auto flex-row gap-1"><a class="nav-link text-white py-0 px-2" href="list.php"><i class="fas fa-list"></i></a><a class="nav-link text-white py-0 px-2" href="../logout.php"><i class="fas fa-sign-out-alt"></i></a></div></div></nav>
<div class="container py-2">
<?php if($sm):?><div class="alert alert-success py-1 small alert-dismissible fade show"><?=$sm?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif;?>
<?php if($em):?><div class="alert alert-danger py-1 small alert-dismissible fade show"><?=$em?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif;?>

<div class="fc"><div class="ch"><i class="fas fa-book me-1"></i>বিষয় ব্যবস্থাপনা</div><div class="cb">
<div class="d-flex gap-2 mb-2 flex-wrap">
<a href="subject_selection.php" class="btn btn-sm btn-outline-primary"><i class="fas fa-tasks"></i> বিষয় নির্বাচন</a>
<a href="subject_report.php" class="btn btn-sm btn-outline-info"><i class="fas fa-chart-bar"></i> রিপোর্ট</a>
<small class="text-muted align-self-center">সেশন, ক্লাস, গ্রুপ ও শিক্ষার্থী ভিত্তিক নির্বাচন</small></div>

<ul class="nav nav-tabs" id="tabs"><li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#t1"><i class="fas fa-plus"></i> নতুন বিষয়</button></li>
<li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#t2"><i class="fas fa-link"></i> ক্লাসে নির্ধারণ</button></li>
<li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#t3"><i class="fas fa-list"></i> বিষয় তালিকা</button></li>
<li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#t4"><i class="fas fa-layer-group"></i> গ্রুপ</button></li></ul>

<div class="tab-content mt-2">

<div class="tab-pane fade show active" id="t1"><div class="row"><div class="col-md-6">
<form method="POST"><input type="hidden" name="action" value="add_subject">
<div class="mb-2"><label class="fl">বিষয়ের নাম *</label><input class="form-control fc-i" name="name" required></div>
<div class="mb-2"><label class="fl">বিষয়ের কোড *</label><input class="form-control fc-i" name="code" required placeholder="যেমন: BAN101"></div>
<div class="mb-2"><label class="fl">বিবরণ</label><textarea class="form-control fc-i" name="description" rows="3"></textarea></div>
<button type="submit" class="btn btn-p btn-sm"><i class="fas fa-save"></i> বিষয় যোগ করুন</button></form></div></div></div>

<div class="tab-pane fade" id="t2"><form method="POST"><input type="hidden" name="action" value="assign_to_class">
<div class="row"><div class="col-md-8">
<div class="mb-2"><label class="fl">ক্লাস *</label><select class="form-select fs" name="class_id" required onchange="loadClassSubjects(this.value)"><option value="">ক্লাস নির্বাচন</option><?php foreach($classes as$cl):?><option value="<?=$cl['id']?>"><?=h($cl['name'].' - '.$cl['section'])?></option><?php endforeach;?></select></div>
<div class="mb-2"><label class="fl">বিষয় নির্বাচন *</label><div class="row"><?php foreach($subjects as$sub):?><div class="col-md-4 mb-1"><div class="form-check"><input class="form-check-input" type="checkbox" name="subject_ids[]" value="<?=$sub['id']?>" id="s_<?=$sub['id']?>"><label class="form-check-label small" for="s_<?=$sub['id']?>"><?=h($sub['name'])?> (<?=h($sub['code'])?>)</label></div></div><?php endforeach;?></div></div>
<button type="submit" class="btn btn-p btn-sm"><i class="fas fa-link"></i> বিষয় নির্ধারণ করুন</button></div></div></form></div>

<div class="tab-pane fade" id="t3">
<h6 class="fw-bold mt-2">সকল বিষয়</h6>
<div class="table-responsive"><table class="table table-hover"><thead><tr><th>নাম</th><th>কোড</th><th>বিবরণ</th><th>ব্যবহৃত ক্লাস</th></tr></thead>
<tbody><?php foreach($subjects as$sub):?><tr><td><?=h($sub['name'])?></td><td><span class="badge" style="background:var(--p)"><?=h($sub['code'])?></span></td><td><?=$sub['description']?h($sub['description']):'<span class="text-muted small">-</span>'?></td>
<td><?php $uc=[];foreach($class_subjects as$ci=>$sl){foreach($sl as$as){if($as['subject_id']==$sub['id']){foreach($classes as$cl){if($cl['id']==$ci){$uc[]=$cl['name'].'-'.$cl['section'];break;}}break;}}}echo$uc?implode(', ',$uc):'<span class="text-muted small">-</span>';?></td></tr><?php endforeach;?></tbody></table></div>

<h6 class="fw-bold mt-3">ক্লাস অনুযায়ী বিষয়</h6>
<?php foreach($classes as$cl):?><div class="cc"><div class="cch"><?=h($cl['name'].' - '.$cl['section'])?></div><div class="cb"><?php if(isset($class_subjects[$cl['id']])):?><div class="d-flex flex-wrap gap-1"><?php foreach($class_subjects[$cl['id']] as$sub):?><span class="badge" style="background:var(--p);font-size:.78rem"><?=h($sub['subject_name'])?> (<?=h($sub['subject_code'])?>)</span><?php endforeach;?></div><?php else:?><p class="text-muted small mb-0">কোন বিষয় নেই</p><?php endif;?></div></div><?php endforeach;?></div>

<div class="tab-pane fade" id="t4"><div class="row"><div class="col-md-5">
<div class="fc mb-2"><div class="ch"><i class="fas fa-plus"></i> নতুন গ্রুপ</div><div class="cb">
<form method="POST"><input type="hidden" name="action" value="add_group">
<div class="mb-2"><label class="fl">গ্রুপ নাম *</label><input class="form-control fc-i" name="group_name" required></div>
<div class="mb-2"><label class="fl">গ্রুপ কোড *</label><input class="form-control fc-i" name="group_code" required placeholder="যেমন: SCI"><div class="form-text small">উদাহরণ: SCI, COM, ARTS</div></div>
<div class="mb-2"><label class="fl">বিবরণ</label><textarea class="form-control fc-i" rows="2" name="group_description"></textarea></div>
<div class="mb-2"><label class="fl">অবস্থা</label><select class="form-select fs" name="group_status"><option value="active">সক্রিয়</option><option value="inactive">নিষ্ক্রিয়</option></select></div>
<button type="submit" class="btn btn-p btn-sm"><i class="fas fa-save"></i> সংরক্ষণ</button></form></div></div></div>
<div class="col-md-7"><div class="fc mb-2"><div class="ch"><i class="fas fa-layer-group"></i> গ্রুপ তালিকা <a href="../groups/list.php" target="_blank" class="btn btn-sm btn-light ms-1 py-0 px-2"><i class="fas fa-external-link-alt"></i></a></div>
<div class="cb p-0"><?php if(empty($groups)):?><div class="empty">কোন গ্রুপ নেই</div><?php else:?><div class="table-responsive"><table class="table table-hover mb-0"><thead><tr><th>নাম</th><th>কোড</th><th>অবস্থা</th><th class="text-end no-print">অ্যাকশন</th></tr></thead>
<tbody><?php foreach($groups as$g):?><tr><td><?=h($g['group_name'])?></td><td><span class="badge" style="background:var(--p)"><?=h($g['group_code'])?></span></td><td><span class="badge <?=$g['status']==='active'?'bg-success':'bg-secondary'?>"><?=$g['status']==='active'?'সক্রিয়':'নিষ্ক্রিয়'?></span></td>
<td class="text-end no-print"><div class="btn-group btn-group-sm">
<button type="button" class="btn btn-outline-warning" data-bs-toggle="modal" data-bs-target="#egm" data-id="<?=(int)$g['id']?>" data-name="<?=h($g['group_name'])?>" data-code="<?=h($g['group_code'])?>" data-desc="<?=h($g['description'])?>" data-status="<?=h($g['status'])?>"><i class="fas fa-edit"></i></button>
<form method="POST" class="d-inline" onsubmit="return confirm('মুছবেন?')"><input type="hidden" name="action" value="delete_group"><input type="hidden" name="id" value="<?=(int)$g['id']?>"><button type="submit" class="btn btn-outline-danger"><i class="fas fa-trash"></i></button></form></div></td></tr><?php endforeach;?></tbody></table></div><?php endif;?></div></div></div></div></div>

</div></div></div></div>

<div class="modal fade" id="egm" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
<form method="POST"><input type="hidden" name="action" value="update_group"><input type="hidden" name="id" id="eg_id">
<div class="modal-header"><h5 class="modal-title"><i class="fas fa-edit"></i> গ্রুপ এডিট</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<div class="modal-body">
<div class="mb-2"><label class="fl">গ্রুপ নাম *</label><input class="form-control fc-i" name="group_name" id="eg_name" required></div>
<div class="mb-2"><label class="fl">গ্রুপ কোড *</label><input class="form-control fc-i" name="group_code" id="eg_code" required></div>
<div class="mb-2"><label class="fl">বিবরণ</label><textarea class="form-control fc-i" rows="3" name="group_description" id="eg_desc"></textarea></div>
<div class="mb-2"><label class="fl">অবস্থা</label><select class="form-select fs" name="group_status" id="eg_status"><option value="active">সক্রিয়</option><option value="inactive">নিষ্ক্রিয়</option></select></div></div>
<div class="modal-footer"><button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">বন্ধ</button><button type="submit" class="btn btn-p btn-sm">সংরক্ষণ</button></div></form></div></div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
let cs=<?=json_encode($class_subjects)?>;
function loadClassSubjects(cid){document.querySelectorAll('input[name="subject_ids[]"]').forEach(c=>c.checked=false);if(cs[cid])cs[cid].forEach(s=>{const cb=document.getElementById('s_'+s.subject_id);if(cb)cb.checked=true})}
document.getElementById('egm')?.addEventListener('show.bs.modal',function(e){const b=e.relatedTarget;document.getElementById('eg_id').value=b.getAttribute('data-id');document.getElementById('eg_name').value=b.getAttribute('data-name');document.getElementById('eg_code').value=b.getAttribute('data-code');document.getElementById('eg_desc').value=b.getAttribute('data-desc')||'';document.getElementById('eg_status').value=b.getAttribute('data-status')||'active'});
</script></body></html>