<?php
session_start();
require_once '../includes/access_control.php';
require_once '../config/database.php';
require_any_role(['admin','teacher']);
$ur=$_SESSION['user_role'];$uid=$_SESSION['user_id'];
$un=$_SESSION['user_name']??$_SESSION['username']??'ব্যবহারকারী';
$ok='';$err='';

$bday=[];
if(!empty($_POST['date_of_birth'])){$d=DateTime::createFromFormat('Y-m-d',$_POST['date_of_birth']);if($d)$bday=['day'=>$d->format('d'),'month'=>$d->format('m'),'year'=>$d->format('Y')];}

$tid=null;
if($ur==='teacher'){$s=$pdo->prepare("SELECT id FROM teachers WHERE user_id=?");$s->execute([$uid]);$t=$s->fetch();if($t)$tid=$t['id'];else{header('Location: ../index.php');exit();}}

$cls=[];
if($ur==='admin'){$cls=$pdo->query("SELECT id,name,section FROM classes WHERE status='active' ORDER BY name,section")->fetchAll();}
elseif($ur==='teacher'&&$tid){$a=get_teacher_assigned_classes($tid);if(!empty($a)){$p=str_repeat('?,',count($a)-1).'?';$s=$pdo->prepare("SELECT DISTINCT c.id,c.name,c.section FROM classes c WHERE c.id IN ($p) AND c.status='active' ORDER BY c.name,c.section");$s->execute($a);$cls=$s->fetchAll();}}

$ses=$pdo->query("SELECT session_name FROM academic_sessions WHERE status='active' ORDER BY session_name DESC")->fetchAll();
$grp=$pdo->query("SELECT group_name,group_code,description FROM student_groups WHERE status='active' ORDER BY group_name")->fetchAll();

$csm=[];
if(!empty($cls)){$ids=array_column($cls,'id');$p=str_repeat('?,',count($ids)-1).'?';$s=$pdo->prepare("SELECT cs.class_id,cs.subject_id,s.name,s.code FROM class_subjects cs JOIN subjects s ON cs.subject_id=s.id WHERE cs.class_id IN ($p) AND s.status='active' ORDER BY s.name");$s->execute($ids);foreach($s->fetchAll() as$cs)$csm[$cs['class_id']][]=$cs;}

if($_SERVER['REQUEST_METHOD']=='POST'){
$fn=trim($_POST['first_name']);$ln=trim($_POST['last_name']??'');
$fan=trim($_POST['father_name']??'');$mon=trim($_POST['mother_name']??'');
$em=trim($_POST['email']);$ph=trim($_POST['phone']);$ad=trim($_POST['address']);
$dob=$_POST['date_of_birth'];$gen=$_POST['gender'];$bg=$_POST['blood_group']??null;
$cid=$_POST['class_id'];$ss=$_POST['session'];$gn=$_POST['group_name'];
$rn=$_POST['roll_number'];$adm=$_POST['admission_date'];
$gun=trim($_POST['guardian_name']);$gup=trim($_POST['guardian_phone']);
$gue=trim($_POST['guardian_email']);$gua=trim($_POST['guardian_address']);
$st=$_POST['status'];$sch=$_POST['scholarship']??'no';$subs=$_POST['subjects']??[];

if(empty($fn)||empty($cid)||empty($ss)||empty($rn)){$err='প্রয়োজনীয় ক্ষেত্রগুলো পূরণ করুন';}
else{
if($ur==='teacher'&&$tid){$a=get_teacher_assigned_classes($tid);if(!in_array($cid,$a))$err='আপনি এই ক্লাসে ছাত্র নিয়োগ করতে পারেন না';}
if(empty($err)){try{
$pdo->beginTransaction();
$s=$pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id=? AND session=? AND COALESCE(group_name,'')=? AND roll_number=? AND status='active'");
$s->execute([$cid,$ss,$gn?:'',$rn]);if($s->fetchColumn()>0)throw new Exception("রোল নম্বর ইতিমধ্যে ব্যবহৃত".($gn?" ($gn গ্রুপে)":""));
$s=$pdo->query("SELECT MAX(CAST(SUBSTRING(student_id,3) AS UNSIGNED)) as mx FROM students WHERE student_id LIKE 'ST%'");$r=$s->fetch();$ni=($r['mx']??0)+1;$sid='ST'.str_pad($ni,4,'0',STR_PAD_LEFT);
$pp=null;
if(isset($_FILES['photo'])&&$_FILES['photo']['error']==0){$ud='../uploads/students/';if(!is_dir($ud))mkdir($ud,0755,true);$ex=strtolower(pathinfo($_FILES['photo']['name'],PATHINFO_EXTENSION));if(in_array($ex,['jpg','jpeg','png','gif'])){$nf='student_'.$ni.'_'.time().'.'.$ex;if(move_uploaded_file($_FILES['photo']['tmp_name'],$ud.$nf))$pp='uploads/students/'.$nf;}}
$s=$pdo->prepare("INSERT INTO students(student_id,first_name,last_name,father_name,mother_name,email,phone,address,date_of_birth,gender,blood_group,class_id,session,group_name,roll_number,admission_date,guardian_name,guardian_phone,guardian_email,guardian_address,status,scholarship,photo,created_at,updated_at)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())");
$s->execute([$sid,$fn,$ln,$fan,$mon,$em,$ph,$ad,$dob?:null,$gen,$bg,$cid,$ss,$gn?:null,$rn,$adm?:null,$gun,$gup,$gue,$gua,$st,$sch,$pp]);
$nid=$pdo->lastInsertId();
if(!empty($subs)){$s=$pdo->prepare("INSERT INTO student_subjects(student_id,subject_id,is_fourth_subject)VALUES(?,?,?)");$c=count($subs);$noFourthCls=[6,7,8];$isFourthAllowed=!in_array((int)$cid,$noFourthCls);foreach($subs as$i=>$sb)$s->execute([$nid,$sb,$isFourthAllowed&&$i==$c-1?1:0]);}
$uname='student_'.$ni;$pw=substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'),0,8);$hpw=password_hash($pw,PASSWORD_DEFAULT);
$s=$pdo->prepare("INSERT INTO users(username,password,email,role,created_at)VALUES(?,?,?,'student',NOW())");$s->execute([$uname,$hpw,$em?:null]);$uid2=$pdo->lastInsertId();
$s=$pdo->prepare("UPDATE students SET user_id=? WHERE id=?");$s->execute([$uid2,$nid]);
$pdo->commit();
$ok="ছাত্র সফলভাবে যোগ হয়েছে। লগইন: ইউজারনেম: $uname, পাসওয়ার্ড: $pw";
$_POST=[];
}catch(Exception$e){$pdo->rollBack();$err=$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="../assets/css/style.css" rel="stylesheet">
<style>
:root{--p:#667eea;--s:#764ba2}
body{background:linear-gradient(135deg,#f0f4ff 0%,#e8edf5 100%);min-height:100vh}
.steps{display:flex;background:#fff;border-radius:10px;padding:6px;margin-bottom:10px;box-shadow:0 3px 12px rgba(102,126,234,.12);overflow-x:auto}
.st{display:flex;align-items:center;gap:4px;padding:5px 10px;cursor:pointer;border-radius:6px;font-weight:600;font-size:.78rem;color:#adb5bd;transition:.2s;white-space:nowrap}
.st.act{background:linear-gradient(135deg,var(--p),var(--s));color:#fff;box-shadow:0 3px 8px rgba(102,126,234,.25)}
.st .n{width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.65rem;font-weight:700;background:#e9ecef;color:#6c757d;flex-shrink:0}
.st.act .n{background:rgba(255,255,255,.25);color:#fff}
.sec{display:none}.sec.act{display:block;animation:fade .25s ease}
@keyframes fade{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}
.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)}
.sc{background:#f8f9fa;border:2px solid #e9ecef;border-radius:8px;padding:5px 8px;transition:.2s;cursor:pointer;font-size:.82rem}
.sc.sel{border-color:var(--p);background:linear-gradient(135deg,#eef2ff,#e8edff);box-shadow:0 2px 8px rgba(102,126,234,.12)}
.sc .form-check-input:checked{background-color:var(--p);border-color:var(--p)}
.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)}
.pu{border:2px dashed #d0d5e0;border-radius:8px;padding:8px;text-align:center;transition:.3s;background:#fafbff;cursor:pointer}
.pu:hover{border-color:var(--p);background:#f0f3ff}
.pu img{max-width:80px;max-height:80px;border-radius:6px;object-fit:cover;margin-top:3px}
nav.navbar{background:linear-gradient(135deg,var(--p),var(--s))!important;padding:5px 0!important}
.sb{background:linear-gradient(135deg,#e8f5e9,#c8e6c9);border-radius:12px;padding:1rem;text-align:center;font-size:.85rem}
.Tbtn,.AIbtn,.Vbtn{display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:4px;border:1px solid #ced4da;background:#fff;cursor:pointer;font-size:.7rem;padding:0;transition:.2s;margin-left:2px}
.Tbtn:hover{background:#e8f4fd;border-color:#0dcaf0}.AIbtn:hover{background:#f0f0ff;border-color:#667eea}.Vbtn:hover{background:#fff0f0;border-color:#dc3545}
.iwb{display:flex;align-items:center;gap:2px}.iwb .fc-i,.iwb .fs{flex:1}
@media(max-width:576px){.st span{display:none}.st{padding:4px 6px}}
</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="<?=($ur=='teacher')?'../teachers/dashboard.php':'../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="index.php"><i class="fas fa-list"></i></a><a class="nav-link text-white py-0" href="../logout.php"><i class="fas fa-sign-out-alt"></i></a></div></div></nav>
<div class="container py-2" style="max-width:900px">
<?php if($ok): ?><div class="sb"><div style="font-size:2.5rem;color:#2ecc71"><i class="fas fa-check-circle"></i></div><?=$ok?><div class="mt-2"><a href="add_with_fourth_subject.php" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> আরেকজন যোগ</a></div></div>
<?php else: ?>
<?php if($err):?><div class="alert alert-danger py-1 mb-2 small"><?=$err?></div><?php endif;?>

<div class="steps" id="steps">
<div class="st act" data-s="1"><div class="n">1</div><span>মৌলিক</span></div>
<div class="st" data-s="2"><div class="n">2</div><span>একাডেমিক</span></div>
<div class="st" data-s="3"><div class="n">3</div><span>অভিভাবক</span></div>
</div>

<form method="POST" action="" enctype="multipart/form-data">
<div class="sec act" data-sec="1"><div class="fc"><div class="ch"><i class="fas fa-user me-1"></i>মৌলিক তথ্য</div><div class="cb"><div class="row g-2">
<div class="col-md-6"><label class="fl">প্রথম নাম (ইংরেজিতে) <span class="text-danger">*</span></label><div class="iwb"><input type="text" class="form-control fc-i" name="first_name" value="<?=htmlspecialchars($_POST['first_name']??'')?>" required><button type="button" class="Tbtn" onclick="tf('first_name')" title="অনুবাদ">T</button><button type="button" class="AIbtn" onclick="ai('first_name')" title="AI সাজেশন">AI</button><button type="button" class="Vbtn" onclick="vi('first_name')" title="ভয়েস">🎤</button></div></div>
<div class="col-md-6"><label class="fl">শেষ নাম (বাংলায়)</label><div class="iwb"><input type="text" class="form-control fc-i" name="last_name" value="<?=htmlspecialchars($_POST['last_name']??'')?>"><button type="button" class="Tbtn" onclick="tf('last_name')">T</button><button type="button" class="AIbtn" onclick="ai('last_name')">AI</button><button type="button" class="Vbtn" onclick="vi('last_name')">🎤</button></div></div>
<div class="col-md-6"><label class="fl">পিতার নাম</label><div class="iwb"><input type="text" class="form-control fc-i" name="father_name" value="<?=htmlspecialchars($_POST['father_name']??'')?>"><button type="button" class="Tbtn" onclick="tf('father_name')">T</button><button type="button" class="AIbtn" onclick="ai('father_name')">AI</button><button type="button" class="Vbtn" onclick="vi('father_name')">🎤</button></div></div>
<div class="col-md-6"><label class="fl">মাতার নাম</label><div class="iwb"><input type="text" class="form-control fc-i" name="mother_name" value="<?=htmlspecialchars($_POST['mother_name']??'')?>"><button type="button" class="Tbtn" onclick="tf('mother_name')">T</button><button type="button" class="AIbtn" onclick="ai('mother_name')">AI</button><button type="button" class="Vbtn" onclick="vi('mother_name')">🎤</button></div></div>
<div class="col-md-4"><label class="fl">জন্ম তারিখ</label><input type="date" class="form-control fc-i" name="date_of_birth" value="<?=$_POST['date_of_birth']??''?>"></div>
<div class="col-md-4"><label class="fl">লিঙ্গ</label><select class="form-select fs" name="gender"><option value="">নির্বাচন</option><option value="male"<?=(($_POST['gender']??'')=='male')?'selected':''?>>পুরুষ</option><option value="female"<?=(($_POST['gender']??'')=='female')?'selected':''?>>মহিলা</option><option value="other"<?=(($_POST['gender']??'')=='other')?'selected':''?>>অন্যান্য</option></select></div>
<div class="col-md-4"><label class="fl">রক্তের গ্রুপ</label><select class="form-select fs" name="blood_group"><option value="">নির্বাচন</option><?php foreach(['A+','A-','B+','B-','O+','O-','AB+','AB-']as$b):?><option value="<?=$b?>"<?=(($_POST['blood_group']??'')==$b)?'selected':''?>><?=$b?></option><?php endforeach;?></select></div>
<div class="col-md-6"><label class="fl">ইমেইল</label><div class="iwb"><input type="email" class="form-control fc-i" name="email" value="<?=htmlspecialchars($_POST['email']??'')?>"><button type="button" class="Tbtn" onclick="tf('email')">T</button><button type="button" class="AIbtn" onclick="ai('email')">AI</button><button type="button" class="Vbtn" onclick="vi('email')">🎤</button></div></div>
<div class="col-md-6"><label class="fl">ফোন</label><div class="iwb"><input type="text" class="form-control fc-i" name="phone" value="<?=htmlspecialchars($_POST['phone']??'')?>"><button type="button" class="Tbtn" onclick="tf('phone')">T</button><button type="button" class="AIbtn" onclick="ai('phone')">AI</button><button type="button" class="Vbtn" onclick="vi('phone')">🎤</button></div></div>
<div class="col-md-6"><label class="fl">ছবি</label><input type="file" class="form-control fc-i" name="photo" accept="image/*" onchange="pv(event)"></div>
<div class="col-12"><label class="fl">ঠিকানা</label><div class="iwb"><textarea class="form-control fc-i" name="address" rows="1"><?=htmlspecialchars($_POST['address']??'')?></textarea><button type="button" class="Tbtn" onclick="tf('address')" style="align-self:stretch">T</button><button type="button" class="AIbtn" onclick="ai('address')" style="align-self:stretch">AI</button><button type="button" class="Vbtn" onclick="vi('address')" style="align-self:stretch">🎤</button></div></div>
</div><div id="pvbox" class="mt-1" style="display:none"><img id="pvi" style="max-width:120px;max-height:120px;border-radius:6px;border:2px solid #ddd"></div>
<div class="d-flex justify-content-end mt-2"><button type="button" class="btn btn-p btn-sm" onclick="gs(2)">পরবর্তী <i class="fas fa-arrow-right ms-1"></i></button></div></div></div></div>

<div class="sec" data-sec="2"><div class="fc"><div class="ch"><i class="fas fa-graduation-cap me-1"></i>একাডেমিক তথ্য</div><div class="cb"><div class="row g-2">
<div class="col-md-4"><label class="fl">ক্লাস <span class="text-danger">*</span></label><select class="form-select fs" id="cid" name="class_id" required><option value="">নির্বাচন</option><?php foreach($cls as$c):?><option value="<?=$c['id']?>"<?=(($_POST['class_id']??'')==$c['id'])?'selected':''?>><?=$c['name'].' - '.$c['section']?></option><?php endforeach;?></select></div>
<div class="col-md-4"><label class="fl">সেশন <span class="text-danger">*</span></label><select class="form-select fs" name="session" required><option value="">নির্বাচন</option><?php foreach($ses as$s):?><option value="<?=$s['session_name']?>"<?=(($_POST['session']??'')==$s['session_name'])?'selected':''?>><?=$s['session_name']?></option><?php endforeach;?></select></div>
<div class="col-md-4"><label class="fl">গ্রুপ</label><select class="form-select fs" name="group_name"><option value="">কোন গ্রুপ নেই</option><?php foreach($grp as$g):?><option value="<?=$g['group_name']?>"<?=(($_POST['group_name']??'')==$g['group_name'])?'selected':''?>><?=$g['group_name']?></option><?php endforeach;?></select></div>
<div class="col-md-3"><label class="fl">রোল <span class="text-danger">*</span></label><input type="text" class="form-control fc-i" name="roll_number" value="<?=htmlspecialchars($_POST['roll_number']??'')?>" required></div>
<div class="col-md-3"><label class="fl">ভর্তি তারিখ</label><input type="date" class="form-control fc-i" name="admission_date" value="<?=$_POST['admission_date']??date('Y-m-d')?>"></div>
<div class="col-md-3"><label class="fl">অবস্থা</label><select class="form-select fs" name="status"><option value="active"<?=(($_POST['status']??'active')=='active')?'selected':''?>>সক্রিয়</option><option value="inactive"<?=(($_POST['status']??'')=='inactive')?'selected':''?>>নিষ্ক্রিয়</option><option value="graduated"<?=(($_POST['status']??'')=='graduated')?'selected':''?>>স্নাতক</option><option value="transferred"<?=(($_POST['status']??'')=='transferred')?'selected':''?>>স্থানান্তরিত</option></select></div>
<div class="col-md-3"><label class="fl">উপবৃত্তি</label><select class="form-select fs" name="scholarship"><option value="no"<?=(($_POST['scholarship']??'no')=='no')?'selected':''?>>না</option><option value="yes"<?=(($_POST['scholarship']??'')=='yes')?'selected':''?>>হ্যাঁ</option><option value="partial"<?=(($_POST['scholarship']??'')=='partial')?'selected':''?>>আংশিক</option><option value="full"<?=(($_POST['scholarship']??'')=='full')?'selected':''?>>পূর্ণ</option><option value="merit"<?=(($_POST['scholarship']??'')=='merit')?'selected':''?>>যোগ্যতাভিত্তিক</option><option value="need-based"<?=(($_POST['scholarship']??'')=='need-based')?'selected':''?>>প্রয়োজনীয়তাভিত্তিক</option><option value="sports"<?=(($_POST['scholarship']??'')=='sports')?'selected':''?>>খেলাধুলাভিত্তিক</option><option value="arts"<?=(($_POST['scholarship']??'')=='arts')?'selected':''?>>শিল্পভিত্তিক</option></select></div>
</div>
<div class="mt-2"><label class="fl">বিষয় <span class="text-info small">(শেষটি চতুর্থ বিষয়)</span></label><div id="sc"><div class="alert alert-info py-1 small">ক্লাস নির্বাচন করুন</div></div></div>
<div class="d-flex justify-content-between mt-2"><button type="button" class="btn btn-outline-secondary btn-sm" onclick="gs(1)"><i class="fas fa-arrow-left"></i> পূর্ব</button><button type="button" class="btn btn-p btn-sm" onclick="gs(3)">পরবর্তী <i class="fas fa-arrow-right ms-1"></i></button></div></div></div></div>

<div class="sec" data-sec="3"><div class="fc"><div class="ch"><i class="fas fa-user-shield me-1"></i>অভিভাবকের তথ্য</div><div class="cb"><div class="row g-2">
<div class="col-md-6"><label class="fl">নাম</label><div class="iwb"><input type="text" class="form-control fc-i" name="guardian_name" value="<?=htmlspecialchars($_POST['guardian_name']??'')?>"><button type="button" class="Tbtn" onclick="tf('guardian_name')">T</button><button type="button" class="AIbtn" onclick="ai('guardian_name')">AI</button><button type="button" class="Vbtn" onclick="vi('guardian_name')">🎤</button></div></div>
<div class="col-md-6"><label class="fl">ফোন</label><div class="iwb"><input type="text" class="form-control fc-i" name="guardian_phone" value="<?=htmlspecialchars($_POST['guardian_phone']??'')?>"><button type="button" class="Tbtn" onclick="tf('guardian_phone')">T</button><button type="button" class="AIbtn" onclick="ai('guardian_phone')">AI</button><button type="button" class="Vbtn" onclick="vi('guardian_phone')">🎤</button></div></div>
<div class="col-md-6"><label class="fl">ইমেইল</label><div class="iwb"><input type="email" class="form-control fc-i" name="guardian_email" value="<?=htmlspecialchars($_POST['guardian_email']??'')?>"><button type="button" class="Tbtn" onclick="tf('guardian_email')">T</button><button type="button" class="AIbtn" onclick="ai('guardian_email')">AI</button><button type="button" class="Vbtn" onclick="vi('guardian_email')">🎤</button></div></div>
<div class="col-12"><label class="fl">ঠিকানা</label><div class="iwb"><textarea class="form-control fc-i" name="guardian_address" rows="1"><?=htmlspecialchars($_POST['guardian_address']??'')?></textarea><button type="button" class="Tbtn" onclick="tf('guardian_address')" style="align-self:stretch">T</button><button type="button" class="AIbtn" onclick="ai('guardian_address')" style="align-self:stretch">AI</button><button type="button" class="Vbtn" onclick="vi('guardian_address')" style="align-self:stretch">🎤</button></div></div>
</div><div class="d-flex justify-content-between mt-2"><button type="button" class="btn btn-outline-secondary btn-sm" onclick="gs(2)"><i class="fas fa-arrow-left"></i> পূর্ব</button><button type="submit" class="btn btn-p btn-sm"><i class="fas fa-plus me-1"></i>ছাত্র যোগ করুন</button></div></div></div></div>
</form>
<?php endif;?></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
let cs=1,d,vl='bn-BD';const T=document.getElementById('steps');
if(T)T.querySelectorAll('.st').forEach(el=>el.addEventListener('click',()=>gs(parseInt(el.dataset.s))));
function gs(n){document.querySelectorAll('.sec').forEach(el=>el.classList.remove('act'));document.querySelector(`[data-sec="${n}"]`).classList.add('act');if(T)T.querySelectorAll('.st').forEach(el=>el.classList.toggle('act',parseInt(el.dataset.s)===n));cs=n;window.scrollTo({top:0,behavior:'smooth'});if(n===2){const id=document.getElementById('cid').value;if(id)loadSub(id);}}

document.getElementById('cid').addEventListener('change',function(){loadSub(this.value)});
function loadSub(id){const c=document.getElementById('sc');if(!id){c.innerHTML='<div class="alert alert-info py-1 small">ক্লাস নির্বাচন করুন</div>';return;}
c.innerHTML='<div class="py-2 text-center"><div class="spinner-border spinner-border-sm text-primary"></div></div>';
const subs=<?=json_encode($csm)?>;if(subs[id]&&subs[id].length>0){let h='<div class="row g-1">';
subs[id].forEach(s=>{const sel=<?=json_encode($_POST['subjects']??[])?>;const ch=Array.isArray(sel)&&sel.includes(String(s.subject_id));h+=`<div class="col-md-3 col-sm-4 col-6"><div class="sc${ch?' sel':''}"><div class="form-check"><input class="form-check-input" type="checkbox" name="subjects[]" value="${s.subject_id}" id="sb_${s.subject_id}"${ch?' checked':''}><label class="form-check-label fw-bold small" for="sb_${s.subject_id}">${s.name} (${s.code})</label></div></div></div>`;
});h+='</div>';c.innerHTML=h;
document.querySelectorAll('.sc').forEach(cd=>{cd.addEventListener('click',function(e){if(e.target.tagName!=='INPUT'){const cb=this.querySelector('input');cb.checked=!cb.checked;this.classList.toggle('sel',cb.checked);}});const cb=cd.querySelector('input');if(!cb._listener){cb.addEventListener('change',function(){this.closest('.sc').classList.toggle('sel',this.checked);});cb._listener=true;}});
}else{c.innerHTML='<div class="alert alert-warning py-1 small">কোন বিষয় পাওয়া যায়নি</div>';}}

(function(){var f=document.querySelectorAll('.needs-validation');Array.prototype.slice.call(f).forEach(function(fm){fm.addEventListener('submit',function(e){if(!fm.checkValidity()){e.preventDefault();e.stopPropagation();}fm.classList.add('was-validated');},false);})})();

function pv(e){const f=e.target.files[0];if(f){const r=new FileReader();r.onload=function(ev){const box=document.getElementById('pvbox');box.style.display='block';document.getElementById('pvi').src=ev.target.result;};r.readAsDataURL(f);}}

const tm={'রহমান':'Rahman','হাসান':'Hasan','আলী':'Ali','করিম':'Karim','রহিম':'Rahim','খান':'Khan','শেখ':'Sheikh','মিয়া':'Mia','ভূঁইয়া':'Bhuinya','শিকদার':'Shikdar','মুহাম্মদ':'Mohammad','আব্দুল':'Abdul','হামিদ':'Hamid','মরিয়ম':'Morium','বেগম':'Begum','নাজমা':'Nazma','সুলতানা':'Sultana','রহিমা':'Rehima','মোনিরা':'Monira','জাহানারা':'Jahanara','ঢাকা':'Dhaka','চট্টগ্রাম':'Chittagong','খুলনা':'Khulna','রাজশাহী':'Rajshahi','সিলেট':'Sylhet','বরিশাল':'Barisal','ময়মনসিংহ':'Mymensingh','rahman':'রহমান','hasan':'হাসান','ali':'আলী','karim':'করিম','rahim':'রহিম','khan':'খান','sheikh':'শেখ','mia':'মিয়া','bhuinya':'ভূঁইয়া','shikdar':'শিকদার','mohammad':'মুহাম্মদ','abdul':'আব্দুল','hamid':'হামিদ','morium':'মরিয়ম','begum':'বেগম','nazma':'নাজমা','sultana':'সুলতানা','rehima':'রহিমা','monira':'মোনিরা','jahanara':'জাহানারা','dhaka':'ঢাকা','chittagong':'চট্টগ্রাম','khulna':'খুলনা','rajshahi':'রাজশাহী','sylhet':'সিলেট','barisal':'বরিশাল','mymensingh':'ময়মনসিংহ','ahmed':'আহমেদ','john':'জন','jane':'জেন','mike':'মাইক','sarah':'সারা','david':'ডেভিড','robert':'রবার্ট','emma':'এম্মা','william':'উইলিয়াম'};

function tf(id){const f=document.getElementById(id);if(!f||!f.value.trim()){alert('টেক্সট লিখুন');return;}let bc=0,ec=0;for(let c of f.value){if(/[\u0980-\u09FF]/.test(c))bc++;else if(/[a-zA-Z]/.test(c))ec++;}
const isBn=bc>ec||(ec===0&&/[\u0980-\u09FF]/.test(f.value));const w=f.value.split(/\s+/);const r=w.map(wd=>{const cw=wd.replace(/[\p{P}\p{S}]/gu,'').trim().toLowerCase();return tm[cw]||wd;}).join(' ');f.value=r;alert(isBn?'বাংলা→ইংরেজি':'ইংরেজি→বাংলা');}

const aiData={first_name:['জন','আহমেদ','মুহাম্মদ','রহমান','করিম','রহিম','সালমান','রাহুল','তারেক','সাইফ'],last_name:['খান','শেখ','হাসান','আলী','রহমান','করিম','রহিম','মিয়া','ভূঁইয়া','শিকদার'],father_name:['মুহাম্মদ আলী','আব্দুল খালেক','আব্দুল হামিদ','মোহাম্মদ হাসান','আব্দুর রহমান','মোঃ করিম'],mother_name:['মরিয়ম বেগম','নাজমা বেগম','সুলতানা বেগম','রহিমা বেগম','মোনিরা বেগম','জাহানারা বেগম'],email:['user@gmail.com','user@yahoo.com'],phone:['01XXXXXXXXX'],address:['ঢাকা','চট্টগ্রাম','খুলনা','রাজশাহী','সিলেট'],guardian_name:['মুহাম্মদ আলী','আব্দুল খালেক','আব্দুল হামিদ'],guardian_email:['guardian@gmail.com'],guardian_phone:['01XXXXXXXXX'],guardian_address:['ঢাকা','চট্টগ্রাম','খুলনা']};

function ai(id){const f=document.getElementById(id);if(!f)return;if(id==='date_of_birth'){const y=Math.floor(Math.random()*(new Date().getFullYear()-10-1950+1))+1950;const m=Math.floor(Math.random()*12)+1;const d=Math.floor(Math.random()*new Date(y,m,0).getDate())+1;f.value=`${y}-${String(m).padStart(2,'0')}-${String(d).padStart(2,'0')}`;alert('তারিখ পূরণ করা হয়েছে');}else if(aiData[id]){const s=aiData[id];f.value=s[Math.floor(Math.random()*s.length)];}}

function vi(id){const f=document.getElementById(id);if(!f)return;if(!('webkitSpeechRecognition' in window)&&!('SpeechRecognition' in window)){alert('Chrome ব্যবহার করুন');return;}
const SR=window.SpeechRecognition||window.webkitSpeechRecognition;const r=new SR();r.lang=vl;r.continuous=false;r.interimResults=false;
r.onresult=function(e){const t=e.results[0][0].transcript.trim();f.value=t;};r.onerror=function(e){if(e.error!=='no-speech'&&e.error!=='audio-capture'&&e.error!=='not-allowed')alert('Error: '+e.error);};r.start();}

document.addEventListener('DOMContentLoaded',()=>{const id=document.getElementById('cid').value;if(id)loadSub(id);});
</script>
</body></html>