<?php
session_start();require_once'../config/database.php';
if(!isset($_SESSION['user_id'])){header('Location: ../login.php');exit();}
$sm='';$em='';
if($_SERVER['REQUEST_METHOD']==='POST'&&isset($_POST['action'])){
$a=$_POST['action'];$id=isset($_POST['id'])?(int)$_POST['id']:0;
if(!isset($_SESSION['user_role'])||!in_array($_SESSION['user_role'],['admin','teacher']))$em='আপনার অনুমতি নেই';
elseif($id<=0)$em='বিষয় সনাক্ত করা যায়নি';
else{try{
if($a==='deactivate'){$s=$pdo->prepare("UPDATE subjects SET status='inactive' WHERE id=?");$s->execute([$id]);$sm='বিষয় নিষ্ক্রিয় করা হয়েছে';}
elseif($a==='activate'){$s=$pdo->prepare("UPDATE subjects SET status='active' WHERE id=?");$s->execute([$id]);$sm='বিষয় সক্রিয় করা হয়েছে';}
elseif($a==='delete'){$r1=$pdo->prepare("SELECT COUNT(*)FROM class_subjects WHERE subject_id=?");$r1->execute([$id]);$cc=$r1->fetchColumn();
$r2=$pdo->prepare("SELECT COUNT(*)FROM student_subjects WHERE subject_id=?");$r2->execute([$id]);$sc=$r2->fetchColumn();
if($cc>0||$sc>0){if($cc>0&&$sc>0)$em="এই বিষয়টি $cc টি ক্লাস এবং $sc জন শিক্ষার্থী ব্যবহার করছে";elseif($cc>0)$em="এই বিষয়টি $cc টি ক্লাস ব্যবহার করছে";else $em="এই বিষয়টি $sc জন শিক্ষার্থী ব্যবহার করছে";}
else{$d=$pdo->prepare("DELETE FROM subjects WHERE id=?");$d->execute([$id]);$sm='বিষয় মুছে ফেলা হয়েছে';}}
}catch(Exception$e){$em='অপারেশন ব্যর্থ হয়েছে';}}}
$p=isset($_GET['page'])?max(1,(int)$_GET['page']):1;$l=isset($_GET['limit'])?max(1,(int)$_GET['limit']):10;$o=($p-1)*$l;
$sq=isset($_GET['search'])?trim($_GET['search']):'';$sf=isset($_GET['status'])?$_GET['status']:'active';
$sb=isset($_GET['sort_by'])?$_GET['sort_by']:'name';$so=isset($_GET['sort_order'])?$_GET['sort_order']:'ASC';
$fs=['name','code','created_at'];if(!in_array($sb,$fs))$sb='name';if(!in_array($so,['ASC','DESC']))$so='ASC';
$wc=[];
if($sq){$wc[]="(s.name LIKE:s OR s.code LIKE:s2 OR s.description LIKE:s3)";$par['s']="%$sq%";$par['s2']="%$sq%";$par['s3']="%$sq%";}
if($sf){$wc[]='s.status=:st';$par['st']=$sf;}
$w=empty($wc)?'1=1':implode(' AND ',$wc);
$cs=$pdo->prepare("SELECT COUNT(*)FROM subjects s WHERE $w");$cs->execute($par??[]);$tr=(int)$cs->fetchColumn();$tp=ceil($tr/$l);
$oc="s.name $so";if($sb==='code')$oc="s.code $so, s.name ASC";elseif($sb==='created_at')$oc="s.created_at $so";
$qpar=$par??[];$qpar['l']=$l;$qpar['of']=$o;
$s=$pdo->prepare("SELECT s.id,s.name,s.code,s.description,s.status,s.created_at,(SELECT COUNT(DISTINCT cs.class_id)FROM class_subjects cs WHERE cs.subject_id=s.id)used_classes_count FROM subjects s WHERE $w ORDER BY $oc LIMIT :l OFFSET :of");$s->execute($qpar);$subjects=$s->fetchAll();
$is_admin=isset($_SESSION['user_role'])&&in_array($_SESSION['user_role'],['admin','teacher']);
?><!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">
<style>
:root{--p:#667eea;--s:#764ba2}body{background:linear-gradient(135deg,#f0f4ff,#e8edf5);min-height:100vh;font-size:.85rem}
.navbar{background:linear-gradient(135deg,var(--p),var(--s))!important;padding:5px 0!important}
.fc{background:#fff;border-radius:10px;box-shadow:0 4px 18px rgba(0,0,0,.05);border:none;overflow:hidden;margin-bottom:14px}
.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:.78rem}
.fc-i,.fs{border-radius:6px;border:2px solid #e9ecef;padding:5px 9px;font-size:.82rem;transition:.2s}
.fc-i:focus,.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)}
.table th{background:linear-gradient(135deg,var(--p),var(--s));color:#fff;font-weight:600;font-size:.75rem;padding:6px 8px!important;border:none}
.table td{padding:5px 8px!important;vertical-align:middle;font-size:.8rem}
.pagination .page-link{border:none;font-size:.8rem;padding:4px 10px;margin:0 2px;border-radius:6px!important;color:var(--p);font-weight:600}
.pagination .active .page-link{background:linear-gradient(135deg,var(--p),var(--s));color:#fff;box-shadow:0 3px 8px rgba(102,126,234,.3)}
.a-b{position:sticky;bottom:0;background:#fff;padding:8px 12px;box-shadow:0 -3px 12px rgba(0,0,0,.06);z-index:100;border-radius:8px;display:flex;justify-content:space-between;align-items:center}
.empty{text-align:center;padding:30px 0;color:#999}
.empty i{font-size:2.5rem;margin-bottom:8px;display:block}
@media(max-width:576px){.fc table{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-book 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">
<?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-filter me-1"></i>ফিল্টার ও অনুসন্ধান</div><div class="cb">
<form method="GET"><div class="row g-1">
<div class="col-md-4"><label class="fl">খুঁজুন</label><div class="input-group input-group-sm"><span class="input-group-text bg-white border-2 border-end-0" style="border:2px solid #e9ecef;border-right:none;border-radius:6px 0 0 6px"><i class="fas fa-search text-muted"></i></span><input class="form-control fc-i" name="search" placeholder="নাম, কোড, বিবরণ" value="<?=htmlspecialchars($sq)?>" style="border-left:none;border-radius:0 6px 6px 0"></div></div>
<div class="col-md-2"><label class="fl">অবস্থা</label><select class="form-select fs" name="status"><option value="">সব</option><option value="active"<?=$sf==='active'?' selected':''?>>সক্রিয়</option><option value="inactive"<?=$sf==='inactive'?' selected':''?>>নিষ্ক্রিয়</option></select></div>
<div class="col-md-2"><label class="fl">সাজান</label><select class="form-select fs" name="sort_by"><option value="name"<?=$sb==='name'?' selected':''?>>নাম</option><option value="code"<?=$sb==='code'?' selected':''?>>কোড</option><option value="created_at"<?=$sb==='created_at'?' selected':''?>>তারিখ</option></select></div>
<div class="col-md-1"><label class="fl">অর্ডার</label><select class="form-select fs" name="sort_order"><option value="ASC"<?=$so==='ASC'?' selected':''?>>↑</option><option value="DESC"<?=$so==='DESC'?' selected':''?>>↓</option></select></div>
<div class="col-md-1"><label class="fl">প্রতি</label><select class="form-select fs" name="limit"><?php foreach([10,20,50,100] as$opt):?><option value="<?=$opt?>"<?=$l==$opt?' selected':''?>><?=$opt?></option><?php endforeach;?></select></div>
<div class="col-md-2 d-flex align-items-end"><button type="submit" class="btn btn-p btn-sm w-100"><i class="fas fa-search"></i> খুঁজুন</button></div></div></form></div></div>

<div class="fc"><div class="ch"><i class="fas fa-list me-1"></i>বিষয় তালিকা <span class="badge bg-light text-dark ms-1"><?=$tr?> টি</span></div><div class="cb p-0">
<div class="table-responsive"><table class="table table-hover mb-0"><thead><tr><th>নাম <?=sort_link('name','বিষয়ের নাম')?></th><th>কোড <?=sort_link('code','কোড')?></th><th>বিবরণ</th><th>ব্যবহৃত ক্লাস</th><th>অবস্থা</th><th class="text-end no-print">কার্যক্রম</th></tr></thead>
<tbody><?php if(empty($subjects)):?><tr><td colspan="6"><div class="empty"><i class="fas fa-book-open text-muted"></i>কোন বিষয় পাওয়া যায়নি</div></td></tr><?php else:?><?php foreach($subjects as$sub):?><tr>
<td><strong><?=htmlspecialchars($sub['name'])?></strong></td>
<td><span class="badge" style="background:var(--p)"><?=htmlspecialchars($sub['code'])?></span></td>
<td><?=$sub['description']?htmlspecialchars($sub['description']):'<span class="text-muted small">-</span>'?></td>
<td><?php if((int)$sub['used_classes_count']>0):?><span class="badge bg-info"><i class="fas fa-school"></i> <?=(int)$sub['used_classes_count']?>টি</span><?php else:?><span class="text-muted small">-</span><?php endif;?></td>
<td><?php if($sub['status']==='active'):?><span class="badge bg-success">সক্রিয়</span><?php else:?><span class="badge bg-secondary">নিষ্ক্রিয়</span><?php endif;?></td>
<td class="text-end no-print"><div class="btn-group btn-group-sm">
<a href="edit.php?id=<?=(int)$sub['id']?>" class="btn btn-outline-warning"><i class="fas fa-edit"></i></a>
<?php if($is_admin):?><?php if($sub['status']==='active'):?>
<form method="POST" onsubmit="return confirm('মুছবেন?')" class="d-inline"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?=(int)$sub['id']?>"><button type="submit" class="btn btn-outline-danger"><i class="fas fa-trash"></i></button></form>
<form method="POST" onsubmit="return confirm('নিষ্ক্রিয় করবেন?')" class="d-inline"><input type="hidden" name="action" value="deactivate"><input type="hidden" name="id" value="<?=(int)$sub['id']?>"><button type="submit" class="btn btn-outline-danger"><i class="fas fa-ban"></i></button></form>
<?php else:?>
<form method="POST" onsubmit="return confirm('সক্রিয় করবেন?')" class="d-inline"><input type="hidden" name="action" value="activate"><input type="hidden" name="id" value="<?=(int)$sub['id']?>"><button type="submit" class="btn btn-outline-success"><i class="fas fa-check"></i></button></form>
<?php endif;?><?php endif;?></div></td></tr><?php endforeach;?><?php endif;?></tbody></table></div>
</div></div>

<?php if($tp>1):?><div class="a-b"><small class="text-muted"><?=$tr?> টির মধ্যে <?=(($p-1)*$l+1)?>-<?=min($p*$l,$tr)?></small>
<nav><ul class="pagination pagination-sm mb-0"><?php if($p>1):?><li class="page-item"><a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$p-1]))?>"><i class="fas fa-chevron-left"></i></a></li><?php endif;
$sp=max(1,$p-2);$ep=min($tp,$p+2);if($sp>1){?><li class="page-item"><a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>1]))?>">১</a></li><?php if($sp>2) echo '<li class="page-item disabled"><span class="page-link">...</span></li>';}
for($i=$sp;$i<=$ep;$i++):?><li class="page-item <?=$i==$p?'active':''?>"><a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$i]))?>"><?=$i?></a></li><?php endfor;
if($ep<$tp){if($ep<$tp-1) echo '<li class="page-item disabled"><span class="page-link">...</span></li>';?><li class="page-item"><a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$tp]))?>"><?=$tp?></a></li><?php }
if($p<$tp):?><li class="page-item"><a class="page-link" href="?<?=http_build_query(array_merge($_GET,['page'=>$p+1]))?>"><i class="fas fa-chevron-right"></i></a></li><?php endif;?></ul></nav></div><?php endif;?>
</div>
<?php function sort_link($f,$t){global$sb,$so,$_GET;$ng=array_merge($_GET,['sort_by'=>$f,'sort_order'=>(($sb==$f&&$so=='ASC')?'DESC':'ASC')]);$ng['page']=max(1,$_GET['page']??1);$q=http_build_query($ng);$a=$sb==$f?"fa-sort-".($so=='ASC'?'up':'down'):'fa-sort text-muted';return"<a class=\"text-white ms-1\" href=\"?$q\" style=\"font-size:.65rem;opacity:.8\"><i class=\"fas $a\"></i></a>";}
?><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script></body></html>