<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';
require_once '../includes/image_utils.php';
require_once '../includes/branch_helper.php';
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) { header('Location: ../login.php'); exit(); }
$sn = get_system_name($pdo);
$ur = $_SESSION['user_role'];
$ok = ''; $err = '';

$cls = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section")->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 FROM student_groups WHERE status = 'active' ORDER BY group_name")->fetchAll();
$branches = get_active_school_branches($pdo);

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'];
    $branch_id = !empty($_POST['branch_id']) ? (int)$_POST['branch_id'] : null;
    $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']);
    $subs = $_POST['subjects']??[];

    if (empty($fn)||empty($cid)||empty($ss)||empty($rn)) { $err = 'প্রয়োজনীয় ক্ষেত্রগুলো পূরণ করুন (নাম ইংরেজিতে, ক্লাস, সেশন, রোল নম্বর)'; }
    elseif (!preg_match('/^[A-Za-z\s]+$/',$fn)||preg_match('/[\x{0980}-\x{09FF}]/u',$fn)) { $err = 'নাম (ইংরেজিতে) ক্ষেত্রে শুধুমাত্র ইংরেজি অক্ষর অনুমোদিত'; }
    else {
        try {
            $pdo->beginTransaction();
            $yr = date('Y');
            $n=1; do{$sid=$yr.str_pad($n,4,'0',STR_PAD_LEFT);$s=$pdo->prepare("SELECT COUNT(*) FROM students WHERE student_id=?");$s->execute([$sid]);$e=$s->fetchColumn()>0;$n++;if($n>9999)throw new Exception("ID fail");}while($e);
            $n=1; do{$ano='APP'.$yr.str_pad($n,4,'0',STR_PAD_LEFT);$s=$pdo->prepare("SELECT COUNT(*) FROM students WHERE application_no=?");$s->execute([$ano]);$e=$s->fetchColumn()>0;$n++;if($n>9999)throw new Exception("APP fail");}while($e);
            $n=1; do{$cno='CUST'.$yr.str_pad($n,4,'0',STR_PAD_LEFT);$s=$pdo->prepare("SELECT COUNT(*) FROM students WHERE customer_number=?");$s->execute([$cno]);$e=$s->fetchColumn()>0;$n++;if($n>9999)throw new Exception("CUST fail");}while($e);
            $pw='STU'.rand(1000,9999);

            $s=$pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id=? AND session=? AND COALESCE(group_name,'')=? AND roll_number=? AND status='active' AND COALESCE(branch_id,0)=COALESCE(?,0)");
            $s->execute([$cid,$ss,$gn?:'',$rn,$branch_id ?: null]);
            if($s->fetchColumn()>0)throw new Exception("এই ক্লাস ও সেশনে".($gn?" ($gn গ্রুপে)":"")." এই রোল নম্বর ইতিমধ্যে ব্যবহৃত হয়েছে");

            $uid=null;
            if(!empty($em)){
                if(!filter_var($em,FILTER_VALIDATE_EMAIL))throw new Exception("ইমেইল ঠিকানা সঠিক নয়");
                $s=$pdo->prepare("SELECT COUNT(*) FROM users WHERE email=? AND email IS NOT NULL AND email!=''");$s->execute([$em]);
                if($s->fetchColumn()>0)throw new Exception("ইমেইল ইতিমধ্যে ব্যবহৃত");
                $s=$pdo->prepare("SELECT COUNT(*) FROM students WHERE email=? AND email IS NOT NULL AND email!=''");$s->execute([$em]);
                if($s->fetchColumn()>0)throw new Exception("ইমেইল অন্য শিক্ষার্থীর জন্য ব্যবহৃত");
                $un=strtolower(preg_replace('/\s+/','',($fn??'').($ln??'').$rn));
                $phash=password_hash($pw,PASSWORD_DEFAULT);
                $ou=$un;$c=1;$ch=$pdo->prepare("SELECT id FROM users WHERE username=?");
                $ch->execute([$un]);while($ch->fetch()){$un=$ou.$c;$c++;$ch->execute([$un]);}
                try{$s=$pdo->prepare("INSERT INTO users (username,password,email,role) VALUES (?,?,?,'student')");$s->execute([$un,$phash,$em]);$uid=$pdo->lastInsertId();}
                catch(Exception$e){if(strpos($e->getMessage(),'Duplicate')!==false){$s=$pdo->prepare("INSERT INTO users (username,password,email,role) VALUES (?,?,NULL,'student')");$s->execute([$un,$phash]);$uid=$pdo->lastInsertId();$em=null;}else throw$e;}
            }

            $pp=null;
            if(isset($_FILES['photo'])&&$_FILES['photo']['error']==0){
                $ud='../uploads/students/';if(!is_dir($ud))mkdir($ud,0755,true);
                $r=validate_and_compress_image($_FILES['photo'],$ud,100);
                if($r['success'])$pp=str_replace('../','',$r['path']);else throw new Exception($r['error']);
            }

            if ($branch_id) {
                $bchk = $pdo->prepare("SELECT id FROM school_branches WHERE id = ? AND status = 'active' LIMIT 1");
                $bchk->execute([$branch_id]);
                if (!$bchk->fetch()) {
                    throw new Exception('নির্বাচিত শাখা সঠিক নয়');
                }
            }

            $s=$pdo->prepare("INSERT INTO students(user_id,student_id,application_no,customer_number,first_name,last_name,father_name,mother_name,email,phone,address,date_of_birth,gender,blood_group,class_id,branch_id,session,group_name,roll_number,admission_date,guardian_name,guardian_phone,guardian_email,guardian_address,photo)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            $s->execute([$uid,$sid,$ano,$cno,$fn,$ln,$fan,$mon,$em,$ph,$ad,$dob,$gen,$bg,$cid,$branch_id,$ss,$gn,$rn,$adm,$gun,$gup,$gue,$gua,$pp]);
            $did=$pdo->lastInsertId();

            if(!empty($subs)){$s=$pdo->prepare("INSERT INTO student_subjects(student_id,subject_id)VALUES(?,?)");foreach($subs as$sb)$s->execute([$did,$sb]);}

            $ac=false;$aerr='';
            try{$s=$pdo->prepare("INSERT INTO admission_applications(application_no,password,first_name,last_name,date_of_birth,gender,phone,email,present_address,father_name,father_phone,mother_name,applying_for_class_id,applying_for_session,applying_for_group,status,photo_path,selected_subjects,created_at)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'approved',?,?,NOW())");
                $s->execute([$ano,$pw,$fn,$ln,$dob,$gen,$ph,$em,$ad,$fan,$gup,$mon,$cid,$ss,$gn,$pp,!empty($subs)?json_encode($subs):null]);$ac=true;
            }catch(Exception$e){$aerr=$e->getMessage();}

            $pdo->commit();
            $pl=$ac?'<br><br><a href="../admission_form_print.php?application_no='.urlencode($ano).'" target="_blank" class="btn btn-success btn-sm"><i class="fas fa-print"></i> আবেদন ফরম প্রিন্ট করুন</a>':'<br><br><span style="color:orange"><i class="fas fa-exclamation-triangle"></i> আবেদন ফরম তৈরী করা যায়নি<br>কারণ: '.htmlspecialchars($aerr).'</span>';
            $ok='ছাত্র/ছাত্রী সফলভাবে যোগ করা হয়েছে<br>ছাত্র/ছাত্রী আইডি: <strong>'.$sid.'</strong><br>আবেদন নম্বর: <strong>'.$ano.'</strong><br>গ্রাহক নং: <strong>'.$cno.'</strong><br>পাসওয়ার্ড: <strong>'.$pw.'</strong>'.$pl;

            try{require_once __DIR__.'/../includes/sms_helper.php';$c=@sms_config();$nums=[];if(!empty($ph))$nums[]=$ph;if(($c['send_to_guardian_also']??true)&&!empty($gup))$nums[]=$gup;
                if(!empty($nums)){$cs=$pdo->prepare('SELECT name,section FROM classes WHERE id=?');$cs->execute([$cid]);$c2=$cs->fetch();
                    @sms_send_template($pdo,'admission_success',['name'=>trim(($fn??'').' '.($ln??''))?:'নামহীন','student_id'=>$sid,'class'=>$c2['name']??'','section'=>$c2['section']??'','roll'=>$rn],$nums);}
            }catch(Throwable$e){}

            $_POST=[];header('Location: '.(($ur=='teacher')?'../teachers/my_students.php':'list.php'));exit();
        }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>নতুন ছাত্র যোগ - <?=htmlspecialchars($sn)?></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:12px;box-shadow:0 3px 12px rgba(102,126,234,.12)}
.st{display:flex;align-items:center;gap:5px;padding:5px 12px;cursor:pointer;border-radius:6px;font-weight:600;font-size:.82rem;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:22px;height:22px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.7rem;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(8px)}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:8px 14px;font-weight:700;font-size:.9rem}
.fc .cb{padding:12px 14px}
.fl{font-weight:600;color:#495057;margin-bottom:2px;font-size:.82rem}
.fc .fc-i,.fc .fs{border-radius:6px;border:2px solid #e9ecef;padding:6px 10px;transition:.2s;font-size:.85rem}
.fc .fc-i:focus,.fc .fs:focus{border-color:var(--p);box-shadow:0 0 0 3px rgba(102,126,234,.1)}
.pu{border:2px dashed #d0d5e0;border-radius:8px;padding:10px;text-align:center;transition:.3s;background:#fafbff;cursor:pointer}
.pu:hover,.pu.dragover{border-color:var(--p);background:#f0f3ff}
.pu img{max-width:100px;max-height:100px;border-radius:6px;object-fit:cover;margin-top:4px}
.sc{background:#f8f9fa;border:2px solid #e9ecef;border-radius:8px;padding:6px 10px;transition:.2s;cursor:pointer}
.sc:hover{border-color:var(--p);background:#f0f3ff}
.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:6px 18px;font-weight:700;font-size:.85rem;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:6px 0!important}
.sb{background:linear-gradient(135deg,#e8f5e9,#c8e6c9);border-radius:12px;padding:1rem;text-align:center;font-size:.9rem}
.si{font-size:2.5rem;color:#2ecc71}
@media(max-width:576px){.st span{display:none}.st{padding:5px 8px}}
</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:1rem" href="<?=($ur=='teacher')?'../teachers/dashboard.php':'../index.php'?>"><i class="fas fa-graduation-cap me-1"></i><?=htmlspecialchars($sn)?></a><div class="d-flex gap-2"><a class="nav-link text-white py-0" href="<?=($ur=='teacher')?'../teachers/dashboard.php':'../index.php'?>"><i class="fas fa-home"></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">
<?php if($ok): ?>
<div class="sb"><div class="si"><i class="fas fa-check-circle"></i></div><?=$ok?><div class="mt-2"><a href="add.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 class="st" data-s="4"><div class="n">4</div><span>অভিভাবক</span></div>
</div>

<form method="POST" action="add.php" 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><input type="text" class="form-control fc-i" name="first_name" value="<?=isset($_POST['first_name'])?htmlspecialchars($_POST['first_name']):''?>" required></div>
<div class="col-md-6"><label class="fl">নাম (বাংলায়)</label><input type="text" class="form-control fc-i" name="last_name" value="<?=isset($_POST['last_name'])?htmlspecialchars($_POST['last_name']):''?>"></div>
<div class="col-md-6"><label class="fl">পিতার নাম</label><input type="text" class="form-control fc-i" name="father_name" value="<?=isset($_POST['father_name'])?htmlspecialchars($_POST['father_name']):''?>"></div>
<div class="col-md-6"><label class="fl">মাতার নাম</label><input type="text" class="form-control fc-i" name="mother_name" value="<?=isset($_POST['mother_name'])?htmlspecialchars($_POST['mother_name']):''?>"></div>
<div class="col-md-6"><label class="fl">ইমেইল</label><input type="email" class="form-control fc-i" name="email" value="<?=isset($_POST['email'])?htmlspecialchars($_POST['email']):''?>"></div>
<div class="col-md-6"><label class="fl">ফোন</label><input type="tel" class="form-control fc-i" name="phone" value="<?=isset($_POST['phone'])?htmlspecialchars($_POST['phone']):''?>"></div>
<div class="col-md-4"><label class="fl">জন্ম তারিখ</label><input type="date" class="form-control fc-i" name="date_of_birth" value="<?=isset($_POST['date_of_birth'])?$_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"<?=(isset($_POST['gender'])&&$_POST['gender']=='male')?'selected':''?>>পুরুষ</option><option value="female"<?=(isset($_POST['gender'])&&$_POST['gender']=='female')?'selected':''?>>মহিলা</option><option value="other"<?=(isset($_POST['gender'])&&$_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?>"<?=(isset($_POST['blood_group'])&&$_POST['blood_group']==$b)?'selected':''?>><?=$b?></option><?php endforeach;?></select></div>
<div class="col-12"><label class="fl">ঠিকানা</label><textarea class="form-control fc-i" name="address" rows="1"><?=isset($_POST['address'])?htmlspecialchars($_POST['address']):''?></textarea></div>
</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-school me-1"></i>একাডেমিক তথ্য</div><div class="cb"><div class="row g-2">
<div class="col-md-3"><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']?>"<?=(isset($_POST['class_id'])&&$_POST['class_id']==$c['id'])?'selected':''?>><?=$c['name'].' - '.$c['section']?></option><?php endforeach;?></select></div>
<div class="col-md-3"><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']?>"<?=(isset($_POST['session'])&&$_POST['session']==$s['session_name'])?'selected':''?>><?=$s['session_name']?></option><?php endforeach;?></select></div>
<div class="col-md-3"><label class="fl">শাখা</label><select class="form-select fs" name="branch_id"><option value="">শাখা নির্বাচন</option><?php foreach($branches as$b):?><option value="<?=$b['id']?>"<?=(isset($_POST['branch_id'])&&$_POST['branch_id']==$b['id'])?'selected':''?>><?=htmlspecialchars($b['branch_name'])?><?=!empty($b['branch_code'])?' ('.htmlspecialchars($b['branch_code']).')':''?></option><?php endforeach;?></select></div>
<div class="col-md-3"><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']?>"<?=(isset($_POST['group_name'])&&$_POST['group_name']==$g['group_name'])?'selected':''?>><?=$g['group_name'].'('.$g['group_code'].')'?></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="<?=isset($_POST['roll_number'])?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="<?=isset($_POST['admission_date'])?$_POST['admission_date']:date('Y-m-d')?>"></div>
<div class="col-md-6"><label class="fl">ছবি</label><div class="pu" id="pd"><div style="font-size:1.5rem;color:var(--p)"><i class="fas fa-camera"></i></div><small class="text-muted">JPG/PNG/GIF</small><input type="file" class="d-none" id="photo" name="photo" accept="image/*"><div id="ppv"></div></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 me-1"></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-book me-1"></i>বিষয় নির্বাচন</div><div class="cb"><div id="sc"><div class="text-center py-3"><i class="fas fa-arrow-up text-primary"></i><p class="mt-1 text-muted small mb-0">প্রথমে ক্লাস নির্বাচন করুন</p></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 me-1"></i> পূর্ব</button><button type="button" class="btn btn-p btn-sm" onclick="gs(4)">পরবর্তী <i class="fas fa-arrow-right ms-1"></i></button></div></div></div></div>

<div class="sec" data-sec="4"><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><input type="text" class="form-control fc-i" name="guardian_name" value="<?=isset($_POST['guardian_name'])?htmlspecialchars($_POST['guardian_name']):''?>"></div>
<div class="col-md-6"><label class="fl">ফোন</label><input type="tel" class="form-control fc-i" name="guardian_phone" value="<?=isset($_POST['guardian_phone'])?htmlspecialchars($_POST['guardian_phone']):''?>"></div>
<div class="col-md-6"><label class="fl">ইমেইল</label><input type="email" class="form-control fc-i" name="guardian_email" value="<?=isset($_POST['guardian_email'])?htmlspecialchars($_POST['guardian_email']):''?>"></div>
<div class="col-md-6"><label class="fl">ঠিকানা</label><textarea class="form-control fc-i" name="guardian_address" rows="1"><?=isset($_POST['guardian_address'])?htmlspecialchars($_POST['guardian_address']):''?></textarea></div>
</div>
<div class="bg-light rounded-2 p-2 mt-2"><small><i class="fas fa-info-circle text-primary me-1"></i>স্বয়ংক্রিয় ইউজার একাউন্ট ও আবেদন ফরম তৈরী হবে</small></div>
<div class="d-flex justify-content-between mt-2"><button type="button" class="btn btn-outline-secondary btn-sm" onclick="gs(3)"><i class="fas fa-arrow-left me-1"></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;const T=document.getElementById('steps');
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');
T.querySelectorAll('.st').forEach(el=>el.classList.toggle('act',parseInt(el.dataset.s)===n));cs=n;if(n===3){const id=document.getElementById('cid').value;if(id)loadSubs(id);}window.scrollTo({top:0,behavior:'smooth'});}
document.getElementById('cid').addEventListener('change',function(){if(cs===3)loadSubs(this.value)});
function loadSubs(id){const c=document.getElementById('sc');
c.innerHTML='<div class="text-center py-2"><div class="spinner-border spinner-border-sm text-primary"></div></div>';
if(!id){c.innerHTML='<div class="text-center py-3"><i class="fas fa-arrow-up text-primary"></i><p class="mt-1 text-muted small mb-0">প্রথমে ক্লাস নির্বাচন করুন</p></div>';return;}
fetch('../get_class_subjects.php?class_id='+id).then(r=>r.json()).then(d=>{
if(d.success&&d.subjects.length>0){let h='<div class="row g-1">';
d.subjects.forEach(s=>{h+=`<div class="col-md-3 col-sm-4 col-6"><div class="sc"><div class="form-check"><input class="form-check-input" type="checkbox" name="subjects[]" value="${s.subject_id}" id="s_${s.subject_id}"><label class="form-check-label fw-bold small" for="s_${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');cd.classList.toggle('sel',cb.checked);cb.addEventListener('change',function(){cd.classList.toggle('sel',this.checked);});});
}else{c.innerHTML='<div class="alert alert-info py-1 small">কোন বিষয় পাওয়া যায়নি</div>';}
}).catch(()=>c.innerHTML='<div class="alert alert-danger py-1 small">লোড করতে সমস্যা</div>');}
const pd=document.getElementById('pd'),pi=document.getElementById('photo');
pd.addEventListener('click',()=>pi.click());pd.addEventListener('dragover',e=>{e.preventDefault();pd.classList.add('dragover')});pd.addEventListener('dragleave',()=>pd.classList.remove('dragover'));
pd.addEventListener('drop',e=>{e.preventDefault();pd.classList.remove('dragover');if(e.dataTransfer.files.length){pi.files=e.dataTransfer.files;hp(e.dataTransfer.files[0]);}});
pi.addEventListener('change',e=>{if(e.target.files.length)hp(e.target.files[0]);});
function hp(f){if(f.size>5*1024*1024){alert('৫MB এর বেশি');pi.value='';return;}const r=new FileReader();r.onload=function(e){document.getElementById('ppv').innerHTML=`<img src="${e.target.result}">`;};r.readAsDataURL(f);}
document.addEventListener('DOMContentLoaded',()=>{const id=document.getElementById('cid').value;if(id)loadSubs(id);});
</script>
</body></html>