<?php session_start();require_once'../config/database.php';
if(!isset($_SESSION['user_id'])||!in_array($_SESSION['user_role']??'',['admin','teacher'])){header('Location: ../login.php');exit();}
$cmn=['Bangla','বাংলা','English','ইংরেজি','Information and Communication Technology','তথ্য ও যোগাযোগ প্রযুক্তি','ICT','Economics','অর্থনীতি','Statistics','পরিসংখ্যান'];
$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 FROM student_groups WHERE status='active' ORDER BY group_name")->fetchAll();
$subs=$pdo->query("SELECT id,name,code FROM subjects WHERE status='active' ORDER BY name")->fetchAll();
$hgc=false;try{$c=$pdo->prepare("SELECT COUNT(*)FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE()AND TABLE_NAME='class_subjects'AND COLUMN_NAME='group_name'");$c->execute();$hgc=$c->fetchColumn()>0;}catch(Exception$e){}
if($_SERVER['REQUEST_METHOD']=='POST'&&isset($_POST['ajax'])){header('Content-Type: application/json');
try{if($_POST['action']==='get_class_subjects'){$cid=$_POST['class_id']??'';$gn=$_POST['group_name']??'';if(!$cid){echo json_encode(['success'=>false,'message'=>'Class ID required']);exit();}
$a=$pdo->prepare('SELECT id,name FROM subjects WHERE status="active"');$a->execute();$as=$a->fetchAll(PDO::FETCH_ASSOC);$cids=[];foreach($as as$s){if(in_array($s['name'],$cmn))$cids[]=intval($s['id']);}
if($hgc&&$gn!==''){$s=$pdo->prepare('SELECT subject_id FROM class_subjects WHERE class_id=? AND group_name=?');$s->execute([$cid,$gn]);$r=$s->fetchAll(PDO::FETCH_COLUMN,0);
if(empty($r)){$s=$pdo->prepare("SELECT subject_id FROM class_subjects WHERE class_id=? AND (group_name IS NULL OR group_name='')");$s->execute([$cid]);$r=$s->fetchAll(PDO::FETCH_COLUMN,0);}}else{$s=$pdo->prepare($hgc?'SELECT DISTINCT subject_id FROM class_subjects WHERE class_id=?':'SELECT subject_id FROM class_subjects WHERE class_id=?');$s->execute([$cid]);$r=$s->fetchAll(PDO::FETCH_COLUMN,0);}
echo json_encode(['success'=>true,'assigned'=>array_map('intval',$r),'common_subjects'=>$cids,'group_supported'=>$hgc]);exit();}
if($_POST['action']==='save_class_subjects'){$cid=intval($_POST['class_id']??0);$sids=json_decode($_POST['subject_ids']??'[]',true);if(!is_array($sids))$sids=[];$gn=$_POST['group_name']??'';
if($cid<=0){echo json_encode(['success'=>false,'message'=>'Invalid class id']);exit();}
$a=$pdo->prepare('SELECT id,name FROM subjects WHERE status="active"');$a->execute();$mp=[];foreach($a->fetchAll(PDO::FETCH_ASSOC)as$s)$mp[intval($s['id'])]=$s['name'];
$cs=[];$gs=[];foreach($sids as$s){$s=intval($s);if(isset($mp[$s])&&in_array($mp[$s],$cmn))$cs[]=$s;else $gs[]=$s;}
try{$pdo->beginTransaction();$ag=[];if($hgc){$g=$pdo->query("SELECT group_name FROM student_groups WHERE status='active'");$ag=$g->fetchAll(PDO::FETCH_COLUMN,0);}
if($hgc){if($gn!==''){$d=$pdo->prepare('DELETE FROM class_subjects WHERE class_id=? AND group_name=?');$d->execute([$cid,$gn]);}else{$d=$pdo->prepare("DELETE FROM class_subjects WHERE class_id=? AND (group_name IS NULL OR group_name='')");$d->execute([$cid]);}}else{$d=$pdo->prepare('DELETE FROM class_subjects WHERE class_id=?');$d->execute([$cid]);}
if(!empty($sids)){if($hgc){$in=$pdo->prepare('INSERT IGNORE INTO class_subjects(class_id,subject_id,group_name)VALUES(?,?,?)');if(!empty($cs)&&!empty($ag))foreach($ag as$g)foreach($cs as$s)$in->execute([$cid,$s,$g]);if(!empty($gs)&&$gn!=='')foreach($gs as$s)$in->execute([$cid,$s,$gn]);}else{$in=$pdo->prepare('INSERT IGNORE INTO class_subjects(class_id,subject_id)VALUES(?,?)');foreach($sids as$s){$s=intval($s);if($s>0)$in->execute([$cid,$s]);}}}
$pdo->commit();echo json_encode(['success'=>true,'message'=>'Class subjects updated','group_supported'=>$hgc]);exit();}catch(Exception$e){$pdo->rollBack();echo json_encode(['success'=>false,'message'=>'Failed: '.$e->getMessage()]);exit();}}
}catch(Exception$e){echo json_encode(['success'=>false,'message'=>'Server error: '.$e->getMessage()]);exit();}}
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}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}
.btn-o{background:transparent;border:1px solid rgba(255,255,255,.15);border-radius:8px;padding:5px 16px;font-weight:600;font-size:.82rem;color:#fff;transition:.3s}.btn-o:hover{background:rgba(255,255,255,.08);color:#fff}
.btn-g{background:rgba(52,211,153,.15);border:1px solid rgba(52,211,153,.3);border-radius:8px;padding:5px 16px;font-weight:600;font-size:.82rem;color:#fff}.btn-g:hover{background:rgba(52,211,153,.25);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:.82rem}
.text-muted{color:rgba(255,255,255,.55)!important}
.alert{backdrop-filter:blur(8px);border:none;border-radius:8px;color:#fff}.alert-info{background:rgba(96,165,250,.12)}.alert-warning{background:rgba(251,191,36,.12)}
hr{border-color:rgba(255,255,255,.08);margin:.75rem 0}
.badge{font-weight:500;font-size:.7rem;padding:2px 8px;color:#fff}.badge-p{background:rgba(108,99,255,.3)}
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){.fc-s{font-size:.75rem}}
</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-graduation-cap 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 py-2">
<div class="fc"><div class="ch"><i class="fas fa-link me-1"></i>ক্লাস ও গ্রুপ অনুযায়ী বিষয় নির্ধারণ</div><div class="cb">
<div class="row g-2 mb-2">
<div class="col-md-3"><label class="fl">সেশন</label><select class="form-select fc-s" id="filter_session"><option value="">সব সেশন</option><?php foreach($ses as$s):?><option value="<?=h($s['session_name'])?>"><?=h($s['session_name'])?></option><?php endforeach;?></select></div>
<div class="col-md-3"><label class="fl">ক্লাস *</label><select class="form-select fc-s" id="filter_class"><option value="">ক্লাস নির্বাচন</option><?php foreach($cls as$c):?><option value="<?=$c['id']?>"><?=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" id="filter_group"><option value="">গ্রুপ নির্বাচন</option><?php foreach($grps as$g):?><option value="<?=h($g['group_name'])?>"><?=h($g['group_name'])?></option><?php endforeach;?></select></div>
<div class="col-md-3 d-flex align-items-end"><button class="btn btn-p" onclick="load()"><i class="fas fa-search"></i> লোড</button></div></div>
<div id="notice" class="mb-2"></div>
<div id="subs"><div class="text-muted" style="padding:20px 0;text-align:center">ক্লাস ও গ্রুপ নির্বাচন করে লোড করুন</div></div>
<hr><div class="d-flex gap-2 flex-wrap">
<button class="btn btn-o" onclick="sA()"><i class="fas fa-check-double"></i> সব নির্বাচন</button>
<button class="btn btn-o" onclick="dA()"><i class="fas fa-times"></i> সব বাতিল</button>
<button class="btn btn-g ms-auto" onclick="save()"><i class="fas fa-save"></i> সংরক্ষণ করুন</button></div>
</div></div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
let cur=[],cids=[],all=<?=json_encode($subs)?>;
function load(){let c=document.getElementById('filter_class').value,g=document.getElementById('filter_group').value;if(!c||!g){alert('ক্লাস ও গ্রুপ নির্বাচন করুন');return;}
document.getElementById('subs').innerHTML='<div style="text-align:center;padding:20px">লোড হচ্ছে...</div>';
fetch('assign_by_class.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:`ajax=1&action=get_class_subjects&class_id=${c}&group_name=${encodeURIComponent(g)}`})
.then(r=>r.json()).then(d=>{if(d.success){cur=d.assigned||[];cids=d.common_subjects||[];
document.getElementById('notice').innerHTML=d.group_supported?'<div class="alert alert-info py-1"><strong>সাধারণ বিষয়:</strong> বাংলা, ইংরেজি, ICT, অর্থনীতি, পরিসংখ্যান সকল গ্রুপে স্বয়ংক্রিয়ভাবে যুক্ত হবে</div>':'<div class="alert alert-warning py-1">গ্রুপ-ভিত্তিক সংরক্ষণের জন্য `class_subjects.group_name` কলাম প্রয়োজন</div>';
render();}else document.getElementById('subs').innerHTML='<div class="text-danger" style="padding:20px;text-align:center">লোডে সমস্যা</div>';})
.catch(()=>{document.getElementById('subs').innerHTML='<div class="text-danger" style="padding:20px;text-align:center">নেটওয়ার্ক ত্রুটি</div>'});}
function render(){if(!all||!all.length){document.getElementById('subs').innerHTML='<div class="text-muted" style="padding:20px">কোন বিষয় নেই</div>';return;}
let cm=all.filter(s=>cids.includes(s.id)),ot=all.filter(s=>!cids.includes(s.id)),h='<div class="row g-2">';
if(cm.length){h+='<div class="col-12"><h6 style="color:#a5b4fc;font-size:.85rem;font-weight:600;margin:6px 0 4px"><i class="fas fa-star me-1"></i>সাধারণ বিষয় (সকল গ্রুপে প্রযোজ্য)</h6></div>';
cm.forEach(s=>{let ch=cur.includes(s.id)?'checked':'';h+=`<div class="col-md-4"><div class="form-check"><input class="form-check-input" type="checkbox" id="s_${s.id}" value="${s.id}" ${ch}><label class="form-check-label" for="s_${s.id}">${s.name} <span style="color:rgba(255,255,255,.35)">(${s.code})</span> <span class="badge badge-p">সাধারণ</span></label></div></div>`;})}
if(ot.length){h+='<div class="col-12"><h6 style="color:#e2e8f0;font-size:.85rem;font-weight:600;margin:8px 0 4px"><i class="fas fa-layer-group me-1"></i>গ্রুপ-ভিত্তিক বিষয়</h6></div>';
ot.forEach(s=>{let ch=cur.includes(s.id)?'checked':'';h+=`<div class="col-md-4"><div class="form-check"><input class="form-check-input" type="checkbox" id="s_${s.id}" value="${s.id}" ${ch}><label class="form-check-label" for="s_${s.id}">${s.name} <span style="color:rgba(255,255,255,.35)">(${s.code})</span></label></div></div>`;})}
h+='</div>';document.getElementById('subs').innerHTML=h;}
function sA(){document.querySelectorAll('#subs input[type=checkbox]').forEach(c=>c.checked=true)}
function dA(){document.querySelectorAll('#subs input[type=checkbox]').forEach(c=>c.checked=false)}
function save(){let c=document.getElementById('filter_class').value,g=document.getElementById('filter_group').value;if(!c||!g){alert('ক্লাস ও গ্রুপ নির্বাচন করুন');return;}
let s=Array.from(document.querySelectorAll('#subs input[type=checkbox]:checked')).map(x=>x.value);
fetch('assign_by_class.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:`ajax=1&action=save_class_subjects&class_id=${c}&group_name=${encodeURIComponent(g)}&subject_ids=${encodeURIComponent(JSON.stringify(s))}`})
.then(r=>r.json()).then(d=>{if(d.success){alert('সংরক্ষণ হয়েছে! সাধারণ বিষয় সকল গ্রুপে যুক্ত হয়েছে.');load();}else alert('ত্রুটি: '+d.message);}).catch(()=>alert('নেটওয়ার্ক ত্রুটি'));}
</script></body></html>