<?php
session_start();
require_once '../config/database.php';
require_once '../includes/branch_helper.php';
if(!isset($_SESSION['user_id'])){header('Location: ../login.php');exit();}
$ur=$_SESSION['user_role'];
$sessions=$pdo->query("SELECT id,session_name FROM academic_sessions WHERE status='active' ORDER BY is_current DESC,start_date DESC")->fetchAll();
$classes=$pdo->query("SELECT id,name,section FROM classes WHERE status='active' ORDER BY name,section")->fetchAll();
ensure_school_branches_schema($pdo);
$branches=get_active_school_branches($pdo);
$results=[];$done=false;

if(isset($_GET['search'])){
try{$hss=$pdo->query("SHOW COLUMNS FROM students LIKE 'session'")->rowCount()>0;}catch(Exception$e){$hss=false;}
try{$hs=$pdo->query("SHOW COLUMNS FROM students LIKE 'session_id'")->rowCount()>0;}catch(Exception$e){$hs=false;}
$sid=(int)($_GET['session_id']??0);$cid=(int)($_GET['class_id']??0);$gn=trim($_GET['group_name']??'');
$stu=trim($_GET['student_id']??'');$rn=trim($_GET['roll_number']??'');$bid=(int)($_GET['branch_id']??0);
$w=["s.status='active'"];$p=[];$i=0;
/* session filter: look up name from academic_sessions and match s.session (text), since session_id is NULL for all students */
if($sid>0){
    if($hss){try{$sn=$pdo->prepare("SELECT session_name FROM academic_sessions WHERE id=?");$sn->execute([$sid]);$sn2=$sn->fetchColumn();if($sn2){$w[]="s.session=:s$i";$p[":s$i"]=$sn2;$i++;}}catch(Exception$e){}}
    elseif($hs){$w[]="s.session_id=:s$i";$p[":s$i"]=$sid;$i++;}
}
if($cid>0){$w[]="s.class_id=:c$i";$p[":c$i"]=$cid;$i++;}
if($gn!=''){$w[]="s.group_name=:g$i";$p[":g$i"]=$gn;$i++;}
if($stu!=''){$w[]="s.student_id LIKE :st$i";$p[":st$i"]="%$stu%";$i++;}
if($rn!=''){$w[]="s.roll_number=:r$i";$p[":r$i"]=$rn;$i++;}
if($bid>0){$w[]="s.branch_id=:b$i";$p[":b$i"]=$bid;$i++;}
/* prefer s.session (has data) over session_id join (all NULL on this server) */
if($hss){$sel="s.*,c.name class_name,c.section class_section,s.session session_name";$join="LEFT JOIN classes c ON s.class_id=c.id";}
elseif($hs){$sel="s.*,c.name class_name,c.section class_section,ses.session_name";$join="LEFT JOIN classes c ON s.class_id=c.id LEFT JOIN academic_sessions ses ON s.session_id=ses.id";}
else{$sel="s.*,c.name class_name,c.section class_section,NULL session_name";$join="LEFT JOIN classes c ON s.class_id=c.id";}
$sql="SELECT $sel FROM students s $join WHERE ".implode(' AND ',$w)." ORDER BY s.class_id,s.roll_number";
try{$s=$pdo->prepare($sql);foreach($p as$k=>$v)$s->bindValue($k,$v);$s->execute();$results=$s->fetchAll();}catch(Exception$e){}
$done=true;}
?><!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}
.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)}
.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}
table{font-size:.85rem}.table th{background:linear-gradient(135deg,var(--p),var(--s));color:#fff;font-weight:600;font-size:.78rem;padding:6px 8px!important;border:none}
.table td{padding:5px 8px!important;vertical-align:middle}
.table tbody tr:hover{background:#f0f3ff}
.pis{width:32px;height:32px;border-radius:50%;object-fit:cover;border:2px solid #fff;box-shadow:0 2px 6px rgba(0,0,0,.1)}
.pid{width:32px;height:32px;border-radius:50%;background:#adb5bd;display:flex;align-items:center;justify-content:center;color:#fff;font-size:.8rem}
.pid{background:linear-gradient(135deg,#667eea,#764ba2)}
@media(max-width:576px){table{font-size:.75rem}}
</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="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">

<div class="fc mb-2"><div class="ch"><i class="fas fa-search me-1"></i>শিক্ষার্থী অনুসন্ধান</div><div class="cb">
<form method="GET"><div class="row g-1">
<div class="col-md-2"><label class="fl">সেশন</label><select class="form-select fs" name="session_id"><option value="0">সব</option><?php foreach($sessions as$s):?><option value="<?=$s['id']?>"<?=(isset($_GET['session_id'])&&$_GET['session_id']==$s['id'])?'selected':''?>><?=$s['session_name']?></option><?php endforeach;?></select></div>
<div class="col-md-2"><label class="fl">ক্লাস</label><select class="form-select fs" name="class_id"><option value="0">সব</option><?php foreach($classes as$c):?><option value="<?=$c['id']?>"<?=(isset($_GET['class_id'])&&$_GET['class_id']==$c['id'])?'selected':''?>><?=$c['name']?></option><?php endforeach;?></select></div>
<div class="col-md-2"><label class="fl">গ্রুপ</label><select class="form-select fs" name="group_name"><option value="">সব</option><option value="Science"<?=(isset($_GET['group_name'])&&$_GET['group_name']=='Science')?'selected':''?>>Science</option><option value="Arts"<?=(isset($_GET['group_name'])&&$_GET['group_name']=='Arts')?'selected':''?>>Arts</option><option value="Commerce"<?=(isset($_GET['group_name'])&&$_GET['group_name']=='Commerce')?'selected':''?>>Commerce</option><option value="General"<?=(isset($_GET['group_name'])&&$_GET['group_name']=='General')?'selected':''?>>General</option></select></div>
<div class="col-md-2"><label class="fl">শাখা</label><select class="form-select fs" name="branch_id"><option value="0">সব</option><?php foreach($branches as$br):?><option value="<?=$br['id']?>"<?=(isset($_GET['branch_id'])&&$_GET['branch_id']==$br['id'])?'selected':''?>><?=$br['branch_name']?></option><?php endforeach;?></select></div>
<div class="col-md-1"><label class="fl">আইডি</label><input type="text" class="form-control fc-i" name="student_id" placeholder="আইডি" value="<?=htmlspecialchars($_GET['student_id']??'')?>"></div>
<div class="col-md-1"><label class="fl">রোল</label><input type="text" class="form-control fc-i" name="roll_number" placeholder="রোল" value="<?=htmlspecialchars($_GET['roll_number']??'')?>"></div>
<div class="col-md-2 d-flex align-items-end gap-1"><button type="submit" name="search" class="btn btn-p btn-sm flex-fill"><i class="fas fa-search"></i> খুঁজুন</button><a href="search.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-redo"></i></a></div>
</div></form>
</div></div>

<?php if($done):?>
<div class="fc"><div class="ch"><i class="fas fa-list me-1"></i>ফলাফল<?php if(!empty($results)):?> <span class="badge bg-light text-dark ms-1"><?=count($results)?> জন</span><?php endif;?></div><div class="cb">
<?php if(empty($results)):?>
<div class="alert alert-warning py-1 small mb-0">কোন শিক্ষার্থী পাওয়া যায়নি</div>
<?php else:?>
<div class="table-responsive"><table class="table table-hover mb-0"><thead><tr><th></th><th>আইডি</th><th>নাম</th><th>ক্লাস</th><th>শাখা</th><th>সেশন</th><th>গ্রুপ</th><th>রোল</th><th>ফোন</th><th></th></tr></thead><tbody>
<?php foreach($results as$st):?><tr>
<td><?php if($st['photo']):?><img src="../<?=$st['photo']?>" class="pis"><?php else:?><div class="pid"><i class="fas fa-user"></i></div><?php endif;?></td>
<td><strong class="small"><?=$st['student_id']?></strong></td>
<td><?=$st['first_name']?> <?=$st['last_name']?><?php if($st['email']):?><br><small class="text-muted"><?=$st['email']?></small><?php endif;?></td>
<td><?php if($st['class_name']):?><span class="badge bg-primary" style="font-size:.7rem"><?=$st['class_name']?> - <?=$st['class_section']?></span><?php else:?><span class="text-muted">-</span><?php endif;?></td>
<td><?php if(!empty($st['branch_id'])){$bn='';foreach($branches as$b){if($b['id']==$st['branch_id']){$bn=$b['branch_name'];break;}}echo '<span class="badge bg-success" style="font-size:.7rem">'.htmlspecialchars($bn).'</span>';}else{echo '-';}?></td>
<td><?=$st['session_name']?:'-'?></td>
<td><?=$st['group_name']?:'-'?></td>
<td><span class="badge bg-info" style="font-size:.7rem"><?=$st['roll_number']?></span></td>
<td><?=$st['phone']?:'-'?></td>
<td><div class="btn-group btn-group-sm"><?php if($ur=='admin'||$ur=='teacher'):?><a href="edit.php?id=<?=$st['id']?>" class="btn btn-outline-warning" title="সম্পাদনা"><i class="fas fa-edit"></i></a><?php endif;?><a href="view.php?id=<?=$st['id']?>" class="btn btn-outline-info" title="দেখুন"><i class="fas fa-eye"></i></a><a href="id_card.php?id=<?=$st['id']?>" target="_blank" class="btn btn-outline-primary" title="আইডি কার্ড"><i class="fas fa-id-card"></i></a></div></td>
</tr><?php endforeach;?></tbody></table></div>
<?php endif;?>
</div></div>
<?php endif;?>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body></html>