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

if(isset($_POST['action'])&&$_POST['action']==='delete_student_subject'){
header('Content-Type: application/json');
try{$sid=$_POST['student_id']??0;$sub=$_POST['subject_id']??0;if(!$sid||!$sub){echo json_encode(['success'=>false,'message'=>'Invalid ID']);exit;}
$s=$pdo->prepare("DELETE FROM student_subjects WHERE student_id=? AND subject_id=?");$r=$s->execute([$sid,$sub]);echo json_encode(['success'=>!!$r,'message'=>$r?'Deleted':'Failed']);}catch(Exception$e){echo json_encode(['success'=>false,'message'=>$e->getMessage()]);}
exit;}

if($_SERVER['REQUEST_METHOD']==='POST'&&isset($_POST['action'])&&$_POST['action']==='assign_subjects'){
$cid=$_POST['class_id']??0;$gn=$_POST['group_name']??'';$ss=$_POST['session']??'';$sids=$_POST['student_ids']??[];
$gsub=$_POST['subject_ids']??[];$sj=json_decode($_POST['student_subjects']??'{}',true)??[];
$has=!empty($gsub);if(!$has){foreach($sj as$ssub){if(!empty($ssub)){$has=true;break;}}}
if(empty($sids))$err='ছাত্র নির্বাচন করুন!';
elseif(!$has)$err='বিষয় নির্বাচন করুন!';
else{try{$pdo->beginTransaction();$cnt=0;
foreach($sids as$sid){$as=array_unique(array_merge($gsub,$sj[$sid]??[]));
if(!empty($as)){$ph=str_repeat('?,',count($as)-1).'?';$s=$pdo->prepare("SELECT subject_id FROM student_subjects WHERE student_id=? AND subject_id IN ($ph)");$s->execute(array_merge([$sid],$as));$ex=$s->fetchAll(PDO::FETCH_COLUMN);$new=array_diff($as,$ex);
if(!empty($new)){$v=[];$par=[];foreach($new as$subj){$v[]='(?,?,?)';$par[]=$sid;$par[]=$subj;$par[]=0;}
$s=$pdo->prepare("INSERT INTO student_subjects(student_id,subject_id,is_fourth_subject)VALUES ".implode(',',$v));$s->execute($par);$cnt+=count($new);}}
$pdo->commit();$msg="$cnt টি বিষয় নির্ধারণ করা হয়েছে!";}}catch(Exception$e){$pdo->rollBack();$err=$e->getMessage();}}}

$cf=$_GET['class_id']??'';$gf=$_GET['group_name']??'';$sf=$_GET['session']??'';
$classes=$pdo->query("SELECT*FROM classes WHERE status='active' ORDER BY name")->fetchAll();
$groups=[];if($cf){$s=$pdo->prepare("SELECT DISTINCT group_name FROM students WHERE class_id=? AND group_name IS NOT NULL AND group_name!='' ORDER BY group_name");$s->execute([$cf]);$groups=$s->fetchAll();}
$sessions=[];try{$s=$pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL AND session!='' ORDER BY session DESC");$sessions=$s->fetchAll(PDO::FETCH_COLUMN);}catch(Exception$e){}

$subjects=[];if($cf){$hasGC=false;try{$ch=$pdo->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='class_subjects' AND COLUMN_NAME='group_name'");$ch->execute();$hasGC=$ch->fetchColumn()>0;}catch(Exception$e){}
$sql="SELECT DISTINCT s.* FROM subjects s JOIN class_subjects cs ON s.id=cs.subject_id WHERE s.status='active' AND cs.class_id=?";$par=[$cf];
if($hasGC&&$gf){$sql.=" AND (cs.group_name=? OR cs.group_name IS NULL)";$par[]=$gf;}
$sql.=" ORDER BY s.code";$s=$pdo->prepare($sql);$s->execute($par);$subjects=$s->fetchAll();}else{$subjects=$pdo->query("SELECT*FROM subjects WHERE status='active' ORDER BY code")->fetchAll();}

$students=[];if($cf){$sql="SELECT s.id,s.student_id,s.first_name,s.last_name,s.roll_number,s.group_name,s.session,c.name class_name FROM students s JOIN classes c ON s.class_id=c.id WHERE s.class_id=? AND s.status='active'";$par=[$cf];
if($gf){$sql.=" AND s.group_name=?";$par[]=$gf;}if($sf){$sql.=" AND s.session=?";$par[]=$sf;}$sql.=" ORDER BY s.roll_number,s.first_name";
$s=$pdo->prepare($sql);$s->execute($par);$students=$s->fetchAll();
foreach($students as&$st){$s=$pdo->prepare("SELECT s.id,s.name,s.code FROM student_subjects ss JOIN subjects s ON ss.subject_id=s.id WHERE ss.student_id=? ORDER BY s.code");$s->execute([$st['id']]);$st['current_subjects']=$s->fetchAll();}unset($st);}
?><!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="../assets/css/style.css" rel="stylesheet">
<style>
:root{--p:#667eea;--s:#764ba2}
body{background:linear-gradient(135deg,#f0f4ff 0%,#e8edf5 100%);min-height:100vh}
.fc{background:#fff;border-radius:10px;box-shadow:0 4px 18px rgba(0,0,0,.05);border:none;overflow:hidden}
.fc .ch{background:linear-gradient(135deg,var(--p),var(--s));color:#fff;border:none;padding:7px 12px;font-weight:700;font-size:.88rem}
.fc .cb{padding:10px 12px}
.fl{font-weight:600;color:#495057;margin-bottom:2px;font-size:.8rem}
.fc .fc-i,.fc .fs{border-radius:6px;border:2px solid #e9ecef;padding:5px 9px;transition:.2s;font-size:.82rem}
.fc .fc-i:focus,.fc .fs:focus{border-color:var(--p);box-shadow:0 0 0 3px rgba(102,126,234,.1)}
.btn-p{background:linear-gradient(135deg,var(--p),var(--s));border:none;border-radius:6px;padding:5px 16px;font-weight:700;font-size:.82rem;box-shadow:0 3px 10px rgba(102,126,234,.2)}
.btn-p:hover{box-shadow:0 5px 14px rgba(102,126,234,.3)}
nav.navbar{background:linear-gradient(135deg,var(--p),var(--s))!important;padding:5px 0!important}
.sg{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:4px;max-height:200px;overflow-y:auto;padding:6px;border:1px solid #dee2e6;border-radius:6px;background:#f8f9fa}
.si{padding:4px 6px;border:1px solid #e9ecef;border-radius:4px;background:#fff;font-size:.8rem;transition:.2s}
.si:hover{background:#eef2ff;border-color:var(--p)}
.st{display:inline-block;background:var(--p);color:#fff;padding:2px 8px;border-radius:10px;font-size:.72rem;margin:1px}
.st .b-close{font-size:.4rem;opacity:1;margin-left:3px;cursor:pointer;background:none;border:none;color:#fff;padding:0}
.table th{background:linear-gradient(135deg,var(--p),var(--s));color:#fff;font-weight:600;font-size:.75rem;padding:5px 8px!important;border:none}
.table td{padding:4px 6px!important;vertical-align:middle;font-size:.8rem}
.ab{position:sticky;bottom:0;background:#fff;padding:10px;box-shadow:0 -3px 12px rgba(0,0,0,.08);z-index:100;border-radius:8px}
@media(max-width:576px){.sg{grid-template-columns:repeat(3,1fr)}}
</style></head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark"><div class="container-fluid px-3"><a class="navbar-brand fw-bold" style="font-size:.95rem" href="../index.php"><i class="fas fa-graduation-cap me-1"></i>বাল্ক বিষয় নির্বাচন</a><div class="d-flex gap-2"><a class="nav-link text-white py-0" href="list.php"><i class="fas fa-list"></i></a></div></div></nav>
<div class="container py-2">
<?php if($msg):?><div class="alert alert-success py-1 small"><?=$msg?></div><?php endif;?>
<?php if($err):?><div class="alert alert-danger py-1 small"><?=$err?></div><?php endif;?>

<div class="fc mb-2"><div class="ch"><i class="fas fa-filter me-1"></i>ফিল্টার</div><div class="cb">
<form method="GET"><div class="row g-1">
<div class="col-md-3"><label class="fl">ক্লাস</label><select class="form-select fs" name="class_id" onchange="this.form.submit()"><option value="">-- ক্লাস --</option><?php foreach($classes as$c):?><option value="<?=$c['id']?>"<?=$cf==$c['id']?'selected':''?>><?=$c['name']?></option><?php endforeach;?></select></div>
<div class="col-md-3"><label class="fl">গ্রুপ</label><select class="form-select fs" name="group_name" onchange="this.form.submit()"<?=!$cf?' disabled':''?>><option value="">-- গ্রুপ --</option><?php foreach($groups as$g):?><option value="<?=htmlspecialchars($g['group_name'])?>"<?=$gf==$g['group_name']?'selected':''?>><?=htmlspecialchars($g['group_name'])?></option><?php endforeach;?></select></div>
<div class="col-md-3"><label class="fl">সেশন</label><select class="form-select fs" name="session" onchange="this.form.submit()"><option value="">-- সেশন --</option><?php foreach($sessions as$s):?><option value="<?=htmlspecialchars($s)?>"<?=$sf==$s?'selected':''?>><?=htmlspecialchars($s)?></option><?php endforeach;?></select></div>
<div class="col-md-3 d-flex align-items-end"><button type="submit" class="btn btn-p btn-sm flex-fill"><i class="fas fa-search"></i> খুঁজুন</button></div>
</div></form>
</div></div>

<?php if(!empty($students)):?>
<form method="POST" id="bf"><input type="hidden" name="action" value="assign_subjects"><input type="hidden" name="student_subjects" id="ssInput" value="{}">
<?php if($cf):?><input type="hidden" name="class_id" value="<?=$cf?>"><?php endif;?><?php if($gf):?><input type="hidden" name="group_name" value="<?=$gf?>"><?php endif;?><?php if($sf):?><input type="hidden" name="session" value="<?=$sf?>"><?php endif;?>

<div class="fc mb-2"><div class="ch"><i class="fas fa-book me-1"></i>সকলের জন্য বিষয় নির্বাচন</div><div class="cb">
<div class="sg"><?php foreach($subjects as$sub):?><div class="si"><div class="form-check mb-0"><input class="form-check-input sub-g" type="checkbox" name="subject_ids[]" value="<?=$sub['id']?>" id="sg_<?=$sub['id']?>"><label class="form-check-label small" for="sg_<?=$sub['id']?>"><?=htmlspecialchars($sub['code'])?>-<?=htmlspecialchars($sub['name'])?></label></div></div><?php endforeach;?></div>
</div></div>

<div class="d-flex justify-content-between align-items-center mb-1">
<small class="text-muted"><i class="fas fa-users me-1"></i><?=count($students)?> জন</small>
<div class="btn-group btn-group-sm"><button type="button" class="btn btn-outline-primary" onclick="document.querySelectorAll('.tb-cb').forEach(c=>c.checked=!c.checked)"><i class="fas fa-check-double"></i></button>
<button type="button" class="btn btn-outline-secondary" onclick="document.querySelectorAll('.tb-cb').forEach(c=>c.checked=false)"><i class="fas fa-times"></i></button></div>
</div>

<div class="table-responsive"><table class="table table-sm table-hover align-middle mb-0"><thead><tr><th style="width:30px;text-align:center"><i class="fas fa-check"></i></th><th>ছাত্র</th><th>আইডি</th><th>রোল</th><th>গ্রুপ</th><th style="min-width:150px">বর্তমান বিষয়</th></tr></thead>
<tbody><?php foreach($students as$st):?><tr><td style="text-align:center"><input class="form-check-input tb-cb" type="checkbox" name="student_ids[]" value="<?=$st['id']?>" id="st_<?=$st['id']?>"></td>
<td><label for="st_<?=$st['id']?>" class="fw-semibold small mb-0" style="cursor:pointer"><?=htmlspecialchars($st['first_name'].' '.$st['last_name'])?></label></td>
<td class="small text-muted"><?=$st['student_id']?></td><td class="small"><?=$st['roll_number']?></td><td class="small"><?=$st['group_name']?htmlspecialchars($st['group_name']):'-'?></td>
<td><span id="cs_<?=$st['id']?>"><?php if(!empty($st['current_subjects'])):?><?php foreach($st['current_subjects'] as$subj):?><span class="st" id="stg_<?=$st['id']?>_<?=$subj['id']?>"><?=htmlspecialchars($subj['code'])?><button type="button" class="b-close" onclick="rmSub(<?=$st['id']?>,<?=$subj['id']?>,'<?=addslashes($subj['code'])?>')">&times;</button></span><?php endforeach;?><?php else:?><span class="text-muted small">-</span><?php endif;?></span></td></tr>
<?php endforeach;?></tbody></table></div>

<div class="ab"><div class="d-flex justify-content-between"><div><button type="button" class="btn btn-outline-primary btn-sm" onclick="document.querySelectorAll('.tb-cb').forEach(c=>c.checked=true)"><i class="fas fa-users"></i> সব নির্বাচন</button></div>
<div><button type="submit" class="btn btn-p btn-sm" onclick="return confirm('নিশ্চিত?')"><i class="fas fa-save me-1"></i>বিষয় নির্ধারণ</button></div></div></div>
</form>
<?php elseif($cf):?><div class="alert alert-info py-1 small">কোন ছাত্র পাওয়া যায়নি</div><?php endif;?>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
let ss={};const si=document.getElementById('ssInput');
function up(st){const c=document.querySelectorAll(`input[type="checkbox"][data-st="${st}"]:checked`);ss[st]=Array.from(c).map(x=>x.value);si.value=JSON.stringify(ss);}
function rmSub(sid,subid,code){if(!confirm(`"${code}" মুছবেন?`))return;
const x=new XMLHttpRequest();x.open('POST','',true);x.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
x.onreadystatechange=function(){if(x.readyState===4&&x.status===200){try{const r=JSON.parse(x.responseText);if(r.success){const e=document.getElementById('stg_'+sid+'_'+subid);if(e)e.remove();if(ss[sid]){ss[sid]=ss[sid].filter(id=>id!=subid);si.value=JSON.stringify(ss);}}else alert(r.message);}catch(e){} }};
x.send('action=delete_student_subject&student_id='+encodeURIComponent(sid)+'&subject_id='+encodeURIComponent(subid));}
</script>
</body></html>