<?php session_start();require_once'../config/database.php';
function h($s){return htmlspecialchars((string)$s,ENT_QUOTES,'UTF-8');}
if(!isset($_SESSION['user_id'])||($_SESSION['user_role']!='admin'&&$_SESSION['user_role']!='teacher')){header('Location: ../login.php');exit();}
$sn=$_GET['session']??'';$ci=$_GET['class_id']??'';$gn=$_GET['group_name']??'';$sm='';$em='';
try{$ses=$pdo->query("SELECT session_name FROM academic_sessions WHERE status='active' ORDER BY session_name DESC")->fetchAll();$cls=$pdo->query("SELECT id,name,section FROM classes WHERE status='active' ORDER BY name,section")->fetchAll();$grps=$pdo->query("SELECT group_name,group_code FROM student_groups WHERE status='active' ORDER BY group_name")->fetchAll();}catch(Exception$e){$em=$e->getMessage();}
$csb=[];$st=[];$ss=[];
if(!empty($ci)){$s=$pdo->prepare("SELECT s.id,s.name,s.code FROM class_subjects cs JOIN subjects s ON cs.subject_id=s.id WHERE cs.class_id=? AND s.status='active' ORDER BY s.name");$s->execute([$ci]);$csb=$s->fetchAll();}
if($sn&&$ci){$ws=["s.status='active'","s.session=?","s.class_id=?"];$ps=[$sn,$ci];
if($gn!==''){if(in_array($gn,['General','সাধারণ'],true)){$ws[]="COALESCE(s.group_name,'')IN(?,?,?)";$ps[]='General';$ps[]='সাধারণ';$ps[]='';}else{$ws[]="COALESCE(s.group_name,'')=?";$ps[]=$gn;}}
$wsi=implode(' AND ',$ws);$s=$pdo->prepare("SELECT s.id,s.student_id,s.first_name,s.last_name,s.roll_number,COALESCE(s.group_name,'')AS group_name FROM students s WHERE $wsi ORDER BY s.roll_number");$s->execute($ps);$st=$s->fetchAll();
$s=$pdo->prepare("SELECT student_id,subject_id FROM student_subjects WHERE student_id IN(SELECT id FROM students s WHERE $wsi)");$s->execute($ps);foreach($s->fetchAll()as$r)$ss[$r['student_id']][]=$r['subject_id'];}
if($_SERVER['REQUEST_METHOD']=='POST'&&isset($_POST['save_all'])){$sn=$_POST['session']??'';$ci=$_POST['class_id']??'';$gn=$_POST['group_name']??'';
try{$pdo->beginTransaction();$del=$pdo->prepare("DELETE FROM student_subjects WHERE student_id=?");$in=$pdo->prepare("INSERT INTO student_subjects(student_id,subject_id)VALUES(?,?)");foreach(($_POST['subjects']??[])as$sid=>$subs){$del->execute([(int)$sid]);foreach($subs as$sb)$in->execute([(int)$sid,(int)$sb]);}$pdo->commit();header("Location: subject_selection.php?session=".urlencode($sn)."&class_id=".urlencode($ci)."&group_name=".urlencode($gn));exit();}catch(Exception$e){$pdo->rollBack();$em='ত্রুটি: '.$e->getMessage();}}
?><!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}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-s{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-s:focus{border-color:var(--p);box-shadow:0 0 0 3px rgba(108,99,255,.2);outline:none}.fc-s option{background:#1e1b4b;color:#fff}
.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);color:#fff}.btn-p:hover{transform:translateY(-1px);box-shadow:0 6px 20px rgba(108,99,255,.4);color:#fff}
.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;font-size:.72rem}
.stbl{border-collapse:collapse;width:100%}.stbl td,.stbl th{padding:3px 6px;vertical-align:middle;border-bottom:1px solid rgba(255,255,255,.06)}.stbl th{background:rgba(108,99,255,.15);font-weight:600;font-size:.75rem;color:#fff!important;text-align:center}.stbl td:first-child{width:160px;font-size:.78rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#fff!important}.stbl td:first-child span{opacity:.6;font-size:.7rem}.stbl .form-check{display:inline-block;margin:0}
.text-muted{color:rgba(255,255,255,.55)!important}.alert{backdrop-filter:blur(8px);border:none;border-radius:8px;color:#fff}.alert-success{background:rgba(52,211,153,.12)}.alert-danger{background:rgba(239,68,68,.12)}.alert-info{background:rgba(96,165,250,.12)}
body,.card,.card-body,.card-header,.btn,.form-label,.form-select,.form-control,.form-check,.nav-link,.table,.table td,.table th,.table tr,td,th,tr,.btn i,a,i,span,small,p,h1,h2,h3,h4,h5,h6,div,label,select,option,input,textarea,strong,b,em{color:#fff!important}
</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-tasks 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="manage.php"><i class="fas fa-cog"></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-fluid py-2">
<?php if($sm):?><div class="alert alert-success py-1 small"><?=$sm?></div><?php endif;?><?php if($em):?><div class="alert alert-danger py-1 small"><?=$em?></div><?php endif;?>
<div class="fc"><div class="ch"><i class="fas fa-filter me-1"></i>সেশন, ক্লাস, গ্রুপ ও শিক্ষার্থী ভিত্তিক নির্বাচন</div><div class="cb">
<form method="GET" class="row g-2 align-items-end">
<div class="col-md-3"><label class="fl">সেশন *</label><select class="form-select fc-s" name="session" required><option value="">নির্বাচন</option><?php foreach($ses as$s):?><option value="<?=h($s['session_name'])?>" <?=$sn===$s['session_name']?'selected':''?>><?=h($s['session_name'])?></option><?php endforeach;?></select></div>
<div class="col-md-3"><label class="fl">ক্লাস *</label><select class="form-select fc-s" name="class_id" required><option value="">নির্বাচন</option><?php foreach($cls as$c):?><option value="<?=$c['id']?>" <?=$ci==$c['id']?'selected':''?>><?=h($c['name'].' - '.$c['section'])?></option><?php endforeach;?></select></div>
<div class="col-md-3"><label class="fl">গ্রুপ</label><select class="form-select fc-s" name="group_name"><option value="">সব</option><?php foreach($grps as$g):?><option value="<?=h($g['group_name'])?>" <?=$gn===$g['group_name']?'selected':''?>><?=h($g['group_name'].' ('.$g['group_code'].')')?></option><?php endforeach;?></select></div>
<div class="col-md-3 d-flex align-items-end"><button type="submit" class="btn btn-p"><i class="fas fa-search"></i> লোড</button></div></form></div></div>

<?php if(!empty($st)&&!empty($csb)):?><div class="fc mt-2"><div class="ch"><i class="fas fa-users me-1"></i>শিক্ষার্থী তালিকা (<?=count($st)?> জন)</div><div class="cb p-0" style="overflow-x:auto">
<form method="POST"><input type="hidden" name="session" value="<?=h($sn)?>"><input type="hidden" name="class_id" value="<?=h($ci)?>"><input type="hidden" name="group_name" value="<?=h($gn)?>">
<table class="stbl"><thead><tr><th style="text-align:left">নাম</th><?php foreach($csb as$sb):?><th style="font-size:.72rem"><?=h($sb['name'])?></th><?php endforeach;?></tr></thead><tbody>
<?php foreach($st as$s):$oid=$s['id'];$sel=$ss[$oid]??[];?>
<tr><td><span style="opacity:.6"><?=h($s['roll_number'])?></span> <?=h(trim($s['first_name'].' '.$s['last_name']))?></td>
<?php foreach($csb as$sb):$chk=in_array($sb['id'],$sel)?'checked':'';?><td style="text-align:center"><div class="form-check" style="display:inline-block;margin:0"><input class="form-check-input" type="checkbox" name="subjects[<?=$oid?>][]" value="<?=$sb['id']?>" id="s<?=$oid?>_<?=$sb['id']?>" <?=$chk?>><label class="form-check-label" for="s<?=$oid?>_<?=$sb['id']?>"></label></div></td><?php endforeach;?>
</tr><?php endforeach;?></tbody></table>
<div class="p-2 text-end"><button type="submit" name="save_all" class="btn btn-p"><i class="fas fa-save me-1"></i>সব সংরক্ষণ করুন</button></div></form></div></div><?php elseif($sn&&$ci):?><div class="alert alert-info py-1 small mt-2">কোনো শিক্ষার্থী বা বিষয় পাওয়া যায়নি। ক্লাসে বিষয় নির্ধারণ করুন।</div><?php endif;?>
</div>
<script>document.querySelector('select[name="class_id"]')?.addEventListener('change',function(){this.closest('form')?.submit()});
document.querySelector('select[name="session"]')?.addEventListener('change',function(){this.closest('form')?.submit()});
document.querySelector('select[name="group_name"]')?.addEventListener('change',function(){this.closest('form')?.submit()});</script>
</body></html>
