<?php
session_start();
require_once '../config/database.php';
if(!isset($_SESSION['user_id'])||($_SESSION['user_role']!='admin'&&$_SESSION['user_role']!='teacher')){header('Location: ../login.php');exit();}
$ok='';$err='';
$sid=isset($_GET['id'])?(int)$_GET['id']:0;
if($sid<=0){header('Location: list.php');exit();}
$s=$pdo->prepare("SELECT * FROM students WHERE id=?");$s->execute([$sid]);$st=$s->fetch();
if(!$st){header('Location: list.php');exit();}
$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,description FROM student_groups WHERE status='active' ORDER BY group_name")->fetchAll();
$all_subjects=$pdo->query("SELECT id,name,code FROM subjects WHERE status='active' ORDER BY name")->fetchAll();
$branches=$pdo->query("SELECT id,branch_name FROM school_branches WHERE status='active' ORDER BY branch_name")->fetchAll();
$csm=[];$sd=$pdo->query("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 s.status='active' ORDER BY s.name")->fetchAll();foreach($sd as$cs)$csm[$cs['class_id']][]=$cs;
$s=$pdo->prepare("SELECT subject_id FROM student_subjects WHERE student_id=?");$s->execute([$sid]);$csub=$s->fetchAll(PDO::FETCH_COLUMN);

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'];
$bid=!empty($_POST['branch_id'])?(int)$_POST['branch_id']:null;
$adm=$_POST['admission_date'];$gun=trim($_POST['guardian_name']);$gup=trim($_POST['guardian_phone']);
$gue=trim($_POST['guardian_email']);$gua=trim($_POST['guardian_address']);$stat=$_POST['status'];$sch=$_POST['scholarship']??'no';
$subs=$_POST['subjects']??[];
if(empty($fn)||empty($cid)||empty($ss)||empty($rn)){$err='প্রয়োজনীয় ক্ষেত্রগুলো পূরণ করুন';}
else{try{
$pdo->beginTransaction();
$s=$pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id=? AND session=? AND (COALESCE(group_name,'')=? OR UPPER(COALESCE(group_name,''))=UPPER(?)) AND roll_number=? AND status='active' AND id!=?");
$s->execute([$cid,$ss,$gn?:'',$gn?:'',$rn,$sid]);if($s->fetchColumn()>0)throw new Exception("এই রোল নম্বর ইতিমধ্যে ব্যবহৃত".($gn?" ($gn গ্রুপে)":""));
if(!empty($em)&&$em!=$st['email']){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!='' AND id!=(SELECT user_id FROM students WHERE id=?)");$s->execute([$em,$sid]);
if($s->fetchColumn()>0)throw new Exception("ইমেইল ইতিমধ্যে ব্যবহৃত");if($st['user_id']){$s=$pdo->prepare("UPDATE users SET email=? WHERE id=?");$s->execute([$em,$st['user_id']]);}}
$pp=$st['photo'];
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_'.$sid.'_'.time().'.'.$ex;
if(move_uploaded_file($_FILES['photo']['tmp_name'],$ud.$nf)){if($st['photo']&&file_exists('../'.$st['photo']))unlink('../'.$st['photo']);$pp='uploads/students/'.$nf;}}}
$s=$pdo->prepare("UPDATE students SET 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=?,status=?,scholarship=?,photo=?,updated_at=NOW() WHERE id=?");
$s->execute([$fn,$ln,$fan,$mon,$em,$ph,$ad,$dob?:null,$gen,$bg,$cid,$bid,$ss,$gn?:null,$rn,$adm?:null,$gun,$gup,$gue,$gua,$stat,$sch,$pp,$sid]);
$s=$pdo->prepare("DELETE FROM student_subjects WHERE student_id=?");$s->execute([$sid]);
if(!empty($subs)){$s=$pdo->prepare("INSERT INTO student_subjects(student_id,subject_id,is_fourth_subject)VALUES(?,?,?)");foreach($subs as$sb)$s->execute([$sid,$sb,0]);}
$pdo->commit();$ok='ছাত্র তথ্য আপডেট হয়েছে';
$s=$pdo->prepare("SELECT * FROM students WHERE id=?");$s->execute([$sid]);$st=$s->fetch();
$s=$pdo->prepare("SELECT subject_id FROM student_subjects WHERE student_id=?");$s->execute([$sid]);$csub=$s->fetchAll(PDO::FETCH_COLUMN);
}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)}
.fc .fc-i:readonly,.fc .fc-i[readonly]{background:#f8f9fa;cursor:not-allowed}
.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)}
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}
.cp{max-width:60px;max-height:60px;border-radius:6px;object-fit:cover;border:2px solid #e9ecef}
@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="<?=($_SESSION['user_role']=='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="list.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="list.php" class="btn btn-primary btn-sm"><i class="fas fa-list"></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" 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="<?=htmlspecialchars($st['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="<?=htmlspecialchars($st['last_name'])?>"></div>
<div class="col-md-6"><label class="fl">পিতার নাম</label><input type="text" class="form-control fc-i" name="father_name" value="<?=htmlspecialchars($st['father_name']??'')?>"></div>
<div class="col-md-6"><label class="fl">মাতার নাম</label><input type="text" class="form-control fc-i" name="mother_name" value="<?=htmlspecialchars($st['mother_name']??'')?>"></div>
<div class="col-md-6"><label class="fl">ইমেইল</label><input type="email" class="form-control fc-i" name="email" value="<?=htmlspecialchars($st['email'])?>"></div>
<div class="col-md-6"><label class="fl">ফোন</label><input type="tel" class="form-control fc-i" name="phone" value="<?=htmlspecialchars($st['phone'])?>"></div>
<div class="col-md-4"><label class="fl">জন্ম তারিখ</label><input type="date" class="form-control fc-i" name="date_of_birth" value="<?=$st['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"<?=$st['gender']=='male'?'selected':''?>>পুরুষ</option><option value="female"<?=$st['gender']=='female'?'selected':''?>>মহিলা</option><option value="other"<?=$st['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?>"<?=$st['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"><?=htmlspecialchars($st['address'])?></textarea></div>
<div class="col-12"><label class="fl">ছবি</label><div class="d-flex align-items-center gap-2"><?php if($st['photo']):?><img src="../<?=$st['photo']?>" class="cp"><?php endif;?><input type="file" class="form-control fc-i" name="photo" accept="image/*"></div></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-graduation-cap me-1"></i>একাডেমিক তথ্য</div><div class="cb"><div class="row g-2">
<div class="col-md-3"><label class="fl">ছাত্র আইডি</label><input type="text" class="form-control fc-i" value="<?=htmlspecialchars($st['student_id'])?>" readonly></div>
<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']?>"<?=$st['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']?>"<?=$st['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="group_name"><option value="">গ্রুপ নেই</option><?php foreach($grp as$g):?><option value="<?=$g['group_name']?>"<?=$st['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="number" class="form-control fc-i" name="roll_number" value="<?=$st['roll_number']?>" required min="1"></div>
<div class="col-md-3"><label class="fl">ভর্তি তারিখ</label><input type="date" class="form-control fc-i" name="admission_date" value="<?=$st['admission_date']?>"></div>
<div class="col-md-3"><label class="fl">অবস্থা</label><select class="form-select fs" name="status"><option value="active"<?=$st['status']=='active'?'selected':''?>>সক্রিয়</option><option value="inactive"<?=$st['status']=='inactive'?'selected':''?>>নিষ্ক্রিয়</option><option value="graduated"<?=$st['status']=='graduated'?'selected':''?>>স্নাতক</option><option value="transferred"<?=$st['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"<?=$st['scholarship']=='no'?'selected':''?>>না</option><option value="yes"<?=$st['scholarship']=='yes'?'selected':''?>>হ্যাঁ</option></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$br):?><option value="<?=$br['id']?>"<?=$st['branch_id']==$br['id']?'selected':''?>><?=$br['branch_name']?></option><?php endforeach;?></select></div>
</div>
<div class="mt-2"><label class="fl">বিষয়</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><input type="text" class="form-control fc-i" name="guardian_name" value="<?=htmlspecialchars($st['guardian_name'])?>"></div>
<div class="col-md-6"><label class="fl">ফোন</label><input type="tel" class="form-control fc-i" name="guardian_phone" value="<?=htmlspecialchars($st['guardian_phone'])?>"></div>
<div class="col-md-6"><label class="fl">ইমেইল</label><input type="email" class="form-control fc-i" name="guardian_email" value="<?=htmlspecialchars($st['guardian_email'])?>"></div>
<div class="col-12"><label class="fl">ঠিকানা</label><textarea class="form-control fc-i" name="guardian_address" rows="1"><?=htmlspecialchars($st['guardian_address'])?></textarea></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-save 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>
const csm=<?=json_encode($csm)?>,csub=<?=json_encode($csub)?>;
let cs=1;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)ld(id);}}
document.getElementById('cid').addEventListener('change',function(){ld(this.value)});
function ld(id){const c=document.getElementById('sc');if(!id){c.innerHTML='<div class="alert alert-info py-1 small">ক্লাস নির্বাচন করুন</div>';return;}
const sb=csm[id]||[];if(!sb.length){c.innerHTML='<p class="text-muted small">কোন বিষয় নেই</p>';return;}
let h='<div class="row g-1">';
sb.forEach(s=>{const ch=csub.map(String).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._ls){cb.addEventListener('change',function(){this.closest('.sc').classList.toggle('sel',this.checked);});cb._ls=true;}});}
document.addEventListener('DOMContentLoaded',()=>{const id=document.getElementById('cid').value;if(id)ld(id);});
</script>
</body></html>