<?php session_start();require_once'../config/database.php';require_once'../includes/site_settings.php';
if(!isset($_SESSION['user_id'])){header('Location: ../login.php');exit;}
$set=get_all_settings($pdo);$sn=$set['site_name']??'বিদ্যালয়';$sa=$set['site_address']??'';$li=$set['logo_image']??null;
$tid=null;$ac=[];if($_SESSION['user_role']=='teacher'){$q=$pdo->prepare("SELECT id FROM teachers WHERE user_id=?");$q->execute([$_SESSION['user_id']]);$t=$q->fetch();if($t){$tid=$t['id'];$q=$pdo->prepare("SELECT DISTINCT c.id FROM classes c WHERE(c.class_teacher_id=? OR c.id IN(SELECT class_id FROM class_subjects WHERE teacher_id=?))AND c.status='active'");$q->execute([$tid,$tid]);$ac=array_column($q->fetchAll(),'id');}}
$ci=$_GET['class_id']??'';$sn_=$_GET['session']??date('Y');$et=$_GET['exam_type']??'';
if($_SESSION['user_role']=='teacher'&&!empty($ac)){$pl=str_repeat('?,',count($ac)-1).'?';$q=$pdo->prepare("SELECT id,name,section FROM classes WHERE id IN($pl)AND status='active' ORDER BY name,section");$q->execute($ac);$cs=$q->fetchAll();}else{$cs=$pdo->query("SELECT id,name,section FROM classes WHERE status='active' ORDER BY name,section")->fetchAll();}
$ss=$pdo->query("SELECT DISTINCT session FROM results ORDER BY session DESC")->fetchAll();
$ets=$pdo->query("SELECT DISTINCT exam_type FROM results ORDER BY exam_type")->fetchAll();

function gpa($rs){$tg=0;$gc=0;$hf=false;$fs=false;foreach($rs as$r){$g=$r['grade']??'';$gp=$r['grade_point']??0;if($g!='F'){if(!empty($r['is_fourth_subject'])){$hf=true;if($gp>2)$tg+=$gp-2;}else{$tg+=$gp;$gc++;}}elseif(empty($r['is_fourth_subject'])){$fs=true;}}return$fs?0:($gc?min(round($tg/$gc,2),5):0);}
function gp($g){switch($g){case'A+':return 5;case'A':return 4;case'A-':return 3.5;case'B':return 3;case'C':return 2;case'D':return 1;default:return 0;}}
function cg($g){if($g>=5)return'A+';if($g>=4)return'A';if($g>=3.5)return'A-';if($g>=3)return'B';if($g>=2)return'C';if($g>=1)return'D';return'F';}
function cbg($ca,$mc,$tm,$pm){$av=count($ca)>=2?($ca[0]+$ca[1])/2:(count($ca)==1?$ca[0]:0);if($av>22&&$mc>9){$p=($av+$mc)/$tm*100;if($p>=80)return'A+';if($p>=70)return'A';if($p>=60)return'A-';if($p>=50)return'B';if($p>=40)return'C';if($p>=33)return'D';}return'F';}
function ceg($ca,$tm,$pm){$av=count($ca)>=2?($ca[0]+$ca[1])/2:(count($ca)==1?$ca[0]:0);if($av>32){$p=$av/$tm*100;if($p>=80)return'A+';if($p>=70)return'A';if($p>=60)return'A-';if($p>=50)return'B';if($p>=40)return'C';if($p>=33)return'D';}return'F';}
function cbs($br,$cc1=null,$cc2=null,$cm1=null,$cm2=null,$ct=null){
	if(empty($br))return null;
	if(count($br)==1){$r=$br[0];$r['subject_name']='বাংলা(একত্রে)';$r['cq_marks_array']=[$r['cq_marks']];if(!isset($r['full_marks']))$r['full_marks']=100;if(!isset($r['pass_marks']))$r['pass_marks']=33;if(!isset($r['subject_id']))$r['subject_id']='combined_bangla';
		if($cc1!==null||$cc2!==null){$r['cq_marks']=$cc1!==null&&$cc2!==null?($cc1+$cc2)/2:($cc1??$cc2);$r['cq_marks_array']=$cc1!==null&&$cc2!==null?[$cc1,$cc2]:[$cc1??$cc2];}
		if($cm1!==null||$cm2!==null){$r['mcq_marks']=$cm1!==null&&$cm2!==null?($cm1+$cm2)/2:($cm1??$cm2);$r['mcq_marks_array']=$cm1!==null&&$cm2!==null?[$cm1,$cm2]:[$cm1??$cm2];}
		$r['marks_obtained']=$ct!==null?$ct:($r['cq_marks']+$r['mcq_marks']);return$r;}
	$cb=['subject_name'=>'বাংলা(একত্রে)','subject_code'=>'CBAN','subject_id'=>'combined_bangla','cq_marks'=>0,'cq_marks_array'=>[],'mcq_marks'=>0,'mcq_marks_array'=>[],'practical_marks'=>0,'assignment_marks'=>0,'attendance_marks'=>0,'marks_obtained'=>0,'full_marks'=>0,'pass_marks'=>0,'grade'=>'F','grade_point'=>0];
	$cr=array_slice($br,0,2);foreach($br as$r){$cb['practical_marks']+=$r['practical_marks'];$cb['assignment_marks']+=$r['assignment_marks'];$cb['attendance_marks']+=$r['attendance_marks'];$cb['full_marks']+=$r['full_marks']??100;$cb['pass_marks']+=$r['pass_marks']??33;}
	$cq=0;$mc=0;foreach($cr as$r){$cq+=$r['cq_marks'];$cb['cq_marks_array'][]=$r['cq_marks'];$mc+=$r['mcq_marks'];$cb['mcq_marks_array'][]=$r['mcq_marks'];}
	$cn=count($cr);if($cn>0){$cb['cq_marks']=$cq/$cn;$cb['mcq_marks']=$mc/$cn;}
	if($cc1!==null||$cc2!==null){$cb['cq_marks']=$cc1!==null&&$cc2!==null?($cc1+$cc2)/2:($cc1??$cc2);$cb['cq_marks_array']=$cc1!==null&&$cc2!==null?[$cc1,$cc2]:(count($cb['cq_marks_array'])>0?[$cc1??$cc2]:[0,$cc2??$cc1]);}
	if($cm1!==null||$cm2!==null){$cb['mcq_marks']=$cm1!==null&&$cm2!==null?($cm1+$cm2)/2:($cm1??$cm2);$cb['mcq_marks_array']=$cm1!==null&&$cm2!==null?[$cm1,$cm2]:(count($cb['mcq_marks_array'])>0?[$cm1??$cm2]:[0,$cm2??$cm1]);}
	$cb['marks_obtained']=$ct!==null?$ct:($cb['cq_marks']+$cb['mcq_marks']);$tc=count($br);if($tc>0){$cb['full_marks']/=$tc;$cb['pass_marks']/=$tc;}return$cb;}
function ces($er,$cc1=null,$cc2=null,$cm1=null,$cm2=null,$ct=null){
	if(empty($er))return null;
	if(count($er)==1){$r=$er[0];$r['subject_name']='ইংরেজি(একত্রে)';$r['cq_marks_array']=[$r['cq_marks']];$r['mcq_marks_array']=[$r['mcq_marks']];if(!isset($r['full_marks']))$r['full_marks']=100;if(!isset($r['pass_marks']))$r['pass_marks']=33;if(!isset($r['subject_id']))$r['subject_id']='combined_english';
		if($cc1!==null||$cc2!==null){$r['cq_marks']=$cc1!==null&&$cc2!==null?($cc1+$cc2)/2:($cc1??$cc2);$r['cq_marks_array']=$cc1!==null&&$cc2!==null?[$cc1,$cc2]:[$cc1??$cc2];}
		if($cm1!==null||$cm2!==null){$r['mcq_marks']=$cm1!==null&&$cm2!==null?($cm1+$cm2)/2:($cm1??$cm2);$r['mcq_marks_array']=$cm1!==null&&$cm2!==null?[$cm1,$cm2]:[$cm1??$cm2];}
		$r['marks_obtained']=$ct!==null?$ct:($r['cq_marks']+$r['mcq_marks']);return$r;}
	$ce=['subject_name'=>'ইংরেজি(একত্রে)','subject_code'=>'CENG','subject_id'=>'combined_english','cq_marks'=>0,'cq_marks_array'=>[],'mcq_marks'=>0,'mcq_marks_array'=>[],'practical_marks'=>0,'assignment_marks'=>0,'attendance_marks'=>0,'marks_obtained'=>0,'full_marks'=>0,'pass_marks'=>0,'grade'=>'F','grade_point'=>0];
	foreach($er as$r){$ce['cq_marks']+=$r['cq_marks'];$ce['cq_marks_array'][]=$r['cq_marks'];$ce['mcq_marks']+=$r['mcq_marks'];$ce['mcq_marks_array'][]=$r['mcq_marks'];$ce['practical_marks']+=$r['practical_marks'];$ce['assignment_marks']+=$r['assignment_marks'];$ce['attendance_marks']+=$r['attendance_marks'];$ce['marks_obtained']+=$r['marks_obtained'];$ce['full_marks']+=$r['full_marks']??100;$ce['pass_marks']+=$r['pass_marks']??33;}
	$cn=count($er);if($cn>0){$ce['cq_marks']/=$cn;$ce['mcq_marks']/=$cn;$ce['marks_obtained']=$ce['cq_marks']+$ce['mcq_marks'];$ce['full_marks']/=$cn;$ce['pass_marks']/=$cn;}
	if($cc1!==null||$cc2!==null){$ce['cq_marks']=$cc1!==null&&$cc2!==null?($cc1+$cc2)/2:($cc1??$cc2);$ce['cq_marks_array']=$cc1!==null&&$cc2!==null?[$cc1,$cc2]:(count($ce['cq_marks_array'])>0?[$cc1??$cc2]:[0,$cc2??$cc1]);}
	if($cm1!==null||$cm2!==null){$ce['mcq_marks']=$cm1!==null&&$cm2!==null?($cm1+$cm2)/2:($cm1??$cm2);$ce['mcq_marks_array']=$cm1!==null&&$cm2!==null?[$cm1,$cm2]:(count($ce['mcq_marks_array'])>0?[$cm1??$cm2]:[0,$cm2??$cm1]);}
	$ce['marks_obtained']=$ct!==null?$ct:($ce['cq_marks']+$ce['mcq_marks']);return$ce;}
function h($s){return htmlspecialchars((string)$s,ENT_QUOTES,'UTF-8');}

$sd=[];$mp=[];
if($ci&&$sn_&&$et){
	$s=$pdo->prepare("SELECT s.id,s.student_id,s.first_name,s.last_name,s.roll_number,s.photo,s.father_name,s.mother_name,s.class_id,c.name AS cn,c.section FROM students s JOIN classes c ON s.class_id=c.id WHERE s.class_id=? AND s.status='active' ORDER BY s.roll_number,s.first_name,s.last_name");$s->execute([$ci]);$al=$s->fetchAll();
	foreach($al as$si){
		$s=$pdo->prepare("SELECT ss.subject_id,ss.is_fourth_subject,s.name AS sn,s.code AS sc FROM student_subjects ss JOIN subjects s ON ss.subject_id=s.id WHERE ss.student_id=? AND s.status='active' ORDER BY s.name");$s->execute([$si['id']]);$as=$s->fetchAll();
		$s=$pdo->prepare("SELECT r.*,sub.name AS sn,sub.code AS sc,ss.is_fourth_subject FROM results r LEFT JOIN subjects sub ON r.subject_id=sub.id LEFT JOIN student_subjects ss ON r.subject_id=ss.subject_id AND r.student_id=ss.student_id WHERE r.student_id=? AND r.session=? AND r.exam_type=? AND r.id IN(SELECT MAX(id)FROM results WHERE student_id=? AND session=? AND exam_type=? GROUP BY subject_id)ORDER BY sub.name");$s->execute([$si['id'],$sn_,$et,$si['id'],$sn_,$et]);$rm=$s->fetchAll();
		$mp_=[];foreach($rm as$r)$mp_[$r['subject_id']]=$r;$rs=[];$hm=false;
		foreach($as as$sb){$sid=$sb['subject_id'];
			if(isset($mp_[$sid])){$rs[]=$mp_[$sid];continue;}
			$pr=['subject_id'=>$sid,'subject_name'=>$sb['sn'],'subject_code'=>$sb['sc'],'cq_marks'=>0,'cq_marks_array'=>[],'mcq_marks'=>0,'mcq_marks_array'=>[],'practical_marks'=>0,'assignment_marks'=>0,'attendance_marks'=>0,'marks_obtained'=>0,'full_marks'=>100,'pass_marks'=>33,'grade'=>'F','grade_point'=>0,'class_max_marks'=>0,'is_fourth_subject'=>$sb['is_fourth_subject']??false];
			$q=$pdo->prepare("SELECT total_marks,overall_pass_marks FROM subject_mark_distribution WHERE subject_id=? AND class_id=? AND session=? AND exam_type=? LIMIT 1");$q->execute([$sid,$si['class_id']??$ci,$sn_,$et]);$md=$q->fetch();
			if($md){$pr['full_marks']=$md['total_marks'];$pr['pass_marks']=$md['overall_pass_marks'];}else{$q=$pdo->prepare("SELECT total_marks,pass_marks AS overall_pass_marks FROM mark_distributions WHERE subject_id=? AND class_id=? AND session=? AND exam_type=? LIMIT 1");$q->execute([$sid,$si['class_id']??$ci,$sn_,$et]);$md=$q->fetch();if($md){$pr['full_marks']=$md['total_marks'];$pr['pass_marks']=$md['overall_pass_marks'];}}
			$rs[]=$pr;$hm=true;}
		$br=[];$er=[];$sci=[];$mid=[];$eco=[];$car=[];$agr=[];
		foreach($rs as$r){$nl=strtolower($r['subject_name']);
			if((stripos($r['subject_name'],'বাংলা')!==false||stripos($r['subject_name'],'Bangla')!==false)&&stripos($r['subject_name'],'বাংলাদেশ')===false&&stripos($r['subject_name'],'Bangladesh')===false)$br[]=$r;
			elseif(stripos($r['subject_name'],'ইংরেজি')!==false||(stripos($r['subject_name'],'English')!==false&&stripos($r['subject_name'],'Paper')!==false))$er[]=$r;
			elseif(strpos($nl,'science')!==false||strpos($nl,'বিজ্ঞান')!==false||strpos($nl,'math')!==false||strpos($nl,'গণিত')!==false||strpos($nl,'ict')!==false)$sci[]=$r;
			elseif(strpos($nl,'economics')!==false||strpos($nl,'অর্থনীতি')!==false)$eco[]=$r;
			elseif(strpos($nl,'career')!==false||strpos($nl,'ক্যারিয়ার')!==false)$car[]=$r;
			elseif(strpos($nl,'agricultural')!==false||strpos($nl,'কৃষি')!==false)$agr[]=$r;
			else$mid[]=$r;}
		$obr=$br;$oer=$er;$top=[];
		if(!empty($br))$top[]=cbs($br);if(!empty($er))$top[]=ces($er);
		usort($sci,fn($a,$b)=>strcmp($a['subject_name'],$b['subject_name']));usort($eco,fn($a,$b)=>strcmp($a['subject_name'],$b['subject_name']));
		$cm=array_merge($sci,$mid,$eco);usort($car,fn($a,$b)=>strcmp($a['subject_name'],$b['subject_name']));if(!empty($car))$cm=array_merge($cm,$car);
		usort($agr,fn($a,$b)=>strcmp($a['subject_name'],$b['subject_name']));if(!empty($agr))$cm=array_merge($cm,$agr);$rs=array_merge($top,$cm);
		$ns=[];$fs=[];foreach($rs as$r){(isset($r['is_fourth_subject'])&&$r['is_fourth_subject'])?$fs[]=$r:$ns[]=$r;}$rs=array_merge($ns,$fs);
		foreach($rs as&$r){
			if($r['subject_id']=='combined_bangla'||$r['subject_id']=='combined_english'){$sid_=null;if($r['subject_id']=='combined_bangla'&&!empty($obr))$sid_=$obr[0]['subject_id'];elseif($r['subject_id']=='combined_english'&&!empty($oer))$sid_=$oer[0]['subject_id'];
				if($sid_){$q=$pdo->prepare("SELECT total_marks,overall_pass_marks FROM subject_mark_distribution WHERE subject_id=? AND class_id=? AND session=? AND exam_type=? LIMIT 1");$q->execute([$sid_,$si['class_id']??$ci,$sn_,$et]);$md=$q->fetch();
					if($md){$r['full_marks']=$md['total_marks'];$r['pass_marks']=$md['overall_pass_marks'];}else{if(!isset($r['full_marks'])||!$r['full_marks'])$r['full_marks']=100;if(!isset($r['pass_marks'])||!$r['pass_marks'])$r['pass_marks']=40;}}
				else{if(!isset($r['full_marks'])||!$r['full_marks'])$r['full_marks']=100;if(!isset($r['pass_marks'])||!$r['pass_marks'])$r['pass_marks']=40;}}
			$q=$pdo->prepare("SELECT total_marks,overall_pass_marks FROM subject_mark_distribution WHERE subject_id=? AND class_id=? AND session=? AND exam_type=? LIMIT 1");$q->execute([$r['subject_id'],$si['class_id']??$ci,$sn_,$et]);$md=$q->fetch();
			if($md){$r['full_marks']=$md['total_marks'];$r['pass_marks']=$md['overall_pass_marks'];}else{$q=$pdo->prepare("SELECT total_marks,pass_marks AS overall_pass_marks FROM mark_distributions WHERE subject_id=? AND class_id=? AND session=? AND exam_type=? LIMIT 1");$q->execute([$r['subject_id'],$si['class_id']??$ci,$sn_,$et]);$md=$q->fetch();
				if($md){$r['full_marks']=$md['total_marks'];$r['pass_marks']=$md['overall_pass_marks'];}else{$r['full_marks']=100;$r['pass_marks']=33;}}
			$r['grade_point']=gp($r['grade']);
			if($r['subject_id']=='combined_bangla'){$q=$pdo->prepare("SELECT id FROM students WHERE class_id=? AND status='active'");$q->execute([$si['class_id']??$ci]);$st=$q->fetchAll();$mx=0;$ids=array_column($obr,'subject_id');
				if(!empty($ids)){foreach($st as$sr){$pl=str_repeat('?,',count($ids)-1).'?';$q=$pdo->prepare("SELECT r.*,sub.name AS sn,ss.is_fourth_subject FROM results r LEFT JOIN subjects sub ON r.subject_id=sub.id LEFT JOIN student_subjects ss ON r.subject_id=ss.subject_id AND r.student_id=ss.student_id WHERE r.student_id=? AND r.subject_id IN($pl)AND r.session=? AND r.exam_type=? AND r.id IN(SELECT MAX(id)FROM results WHERE student_id=? AND subject_id IN($pl)AND session=? AND exam_type=? GROUP BY subject_id)");
					$pa=array_merge([$sr['id']],$ids,[$sn_,$et],[$sr['id']],$ids,[$sn_,$et]);$q->execute($pa);$sr_=$q->fetchAll();if(!empty($sr_)){$cb_=cbs($sr_);if($cb_&&$cb_['marks_obtained']>$mx)$mx=$cb_['marks_obtained'];}}$r['class_max_marks']=$mx;}else$r['class_max_marks']=0;}
			elseif($r['subject_id']=='combined_english'){$q=$pdo->prepare("SELECT id FROM students WHERE class_id=? AND status='active'");$q->execute([$si['class_id']??$ci]);$st=$q->fetchAll();$mx=0;$ids=array_column($oer,'subject_id');
				if(!empty($ids)){foreach($st as$sr){$pl=str_repeat('?,',count($ids)-1).'?';$q=$pdo->prepare("SELECT r.*,sub.name AS sn,ss.is_fourth_subject FROM results r LEFT JOIN subjects sub ON r.subject_id=sub.id LEFT JOIN student_subjects ss ON r.subject_id=ss.subject_id AND r.student_id=ss.student_id WHERE r.student_id=? AND r.subject_id IN($pl)AND r.session=? AND r.exam_type=? AND r.id IN(SELECT MAX(id)FROM results WHERE student_id=? AND subject_id IN($pl)AND session=? AND exam_type=? GROUP BY subject_id)");
					$pa=array_merge([$sr['id']],$ids,[$sn_,$et],[$sr['id']],$ids,[$sn_,$et]);$q->execute($pa);$sr_=$q->fetchAll();if(!empty($sr_)){$ce_=ces($sr_);if($ce_&&$ce_['marks_obtained']>$mx)$mx=$ce_['marks_obtained'];}}$r['class_max_marks']=$mx;}else$r['class_max_marks']=0;}
			else{$q=$pdo->prepare("SELECT MAX(cq_marks+mcq_marks)AS max_marks FROM results WHERE subject_id=? AND session=? AND exam_type=? AND student_id IN(SELECT id FROM students WHERE class_id=? AND status='active')");$q->execute([$r['subject_id'],$sn_,$et,$si['class_id']??$ci]);$mx=$q->fetch();$r['class_max_marks']=$mx['max_marks']??0;}
			if($r['subject_name']=='বাংলা(একত্রে)'){$g=cbg($r['cq_marks_array'],$r['mcq_marks'],$r['full_marks'],$r['pass_marks']);$r['grade']=$g;$r['grade_point']=gp($g);}
			elseif($r['subject_name']=='ইংরেজি(একত্রে)'){$g=ceg($r['cq_marks_array'],$r['full_marks'],$r['pass_marks']);$r['grade']=$g;$r['grade_point']=gp($g);}}
		unset($r);
		$tm=0;$to=0;$tg=0;$gc=0;$ts=count($rs);$hs=false;$ff=false;
		foreach($rs as$r){$tm+=$r['full_marks'];$to+=$r['marks_obtained'];if($r['grade']=='F'&&!$r['is_fourth_subject'])$hs=true;if($r['grade']!='F'){if($r['is_fourth_subject']){$ff=true;if($r['grade_point']>2)$tg+=$r['grade_point']-2;}else{$tg+=$r['grade_point'];$gc++;}}}
		$gpa_val=$hs||$hm?0:($gc>0?min(round($tg/$gc,2),5):0);
		$sd[]=['student'=>$si,'results'=>$rs,'total_marks'=>$tm,'total_obtained'=>$to,'percentage'=>$tm>0?round($to/$tm*100,2):0,'gpa'=>$gpa_val,'total_subjects'=>$ts];}
	if(!empty($sd)){$md_=[];foreach($sd as$i=>$d)$md_[$d['student']['id']]=['total_obtained'=>$d['total_obtained'],'gpa'=>$d['gpa'],'index'=>$i];
		uasort($md_,fn($a,$b)=>$a['gpa']!=$b['gpa']?($b['gpa']<=>$a['gpa']):($b['total_obtained']<=>$a['total_obtained']));$pos=1;foreach($md_ as$sid=>$d){if($d['gpa']>0)$mp[$sid]=$pos++;}
		foreach($sd as$i=>&$d){$d['merit_position']=$mp[$d['student']['id']]??null;}unset($d);}}

if(isset($_GET['generate_pdf'])&&$ci&&$sn_&&$et){
	header('Content-Type: application/pdf');header('Content-Disposition: attachment; filename="merit_position_marksheets_'.$ci.'_'.$sn_.'_'.$et.'.pdf"');header('Cache-Control: private, no-cache, must-revalidate');header('Pragma: no-cache');
	ob_start();?><html lang="bn"><meta charset="UTF-8"><title>মার্কশীট</title><style>body{font-family:sans-serif;font-size:12px;margin:0;padding:0}.ms{border:2px solid #2c3e50;padding:15px;margin:15px auto;background:#fff;border-radius:8px;max-width:800px;page-break-inside:avoid}.shd{text-align:center;border-bottom:2px double #3498db;padding-bottom:10px;margin-bottom:15px}.logo{width:60px;height:60px;border:2px solid #3498db;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;overflow:hidden}.shd h3{color:#2c3e50;font-size:18px;margin:5px 0}.shd h4{color:#e74c3c;font-size:15px;margin:5px 0;text-decoration:underline}.tb{width:100%;border-collapse:collapse;margin:10px 0;font-size:10px}.tb th,.tb td{border:1px solid #dee2e6;padding:4px;text-align:center;font-size:10px}.tb th{background:linear-gradient(135deg,#3498db,#2980b9);color:#fff;font-weight:600}.tb tr:nth-child(even){background:#f8f9fa}.rs{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px;padding:10px;border-top:1px dashed #3498db;background:#f8f9fa;border-radius:6px}.fs{border:2px solid #000;border-radius:8px;padding:12px;margin-top:15px;background:#e3f2fd}.fs th{background:#3498db;color:#fff;border:1px solid #000;padding:4px}.fs td{border:1px solid #000;padding:4px}.sg{display:flex;justify-content:space-between;margin-top:20px;text-align:center}.sg>div{border-top:1px solid #3498db;padding-top:6px;font-weight:600;width:30%}.si{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px;background:#f8f9fa;padding:10px;border-radius:6px;border:1px solid #e9ecef}.ir{display:flex;margin-bottom:3px}.il{font-weight:600;min-width:90px;font-size:11px}.iv{border-bottom:1px dotted #3498db;flex:1;padding-left:5px;font-size:11px}@page{margin:0.5cm}@media print{.no-print{display:none!important}.pb{page-break-after:always;page-break-inside:avoid}body{font-size:10px}.ms{box-shadow:none;border:2px solid #000!important;padding:10px;background:#fff}.shd{border-bottom:2px solid #000!important;background:#fff}.logo{border:1px solid #000;box-shadow:none}.tb th{background:#f8f9fa;color:#000}}</style><body>
<?php foreach($sd as$i=>$d):$s=$d['student'];$r=$d['results'];$tm=$d['total_marks'];$to=$d['total_obtained'];$pct=$d['percentage'];$gpa_val=$d['gpa'];$mp_=$d['merit_position']??null;?>
<div class="ms"><div class="shd"><div style="display:flex;justify-content:space-between;align-items:center"><div class="logo"><?=$li?'<img src="../'.h($li).'" style="max-height:60px">':'<i class="fas fa-graduation-cap"></i>'?></div><div style="flex:1;text-align:center"><h3><?=h($sn)?></h3><p style="color:#7f8c8d;margin:0;font-size:13px"><?=h($sa)?></p><h4>একাডেমিক মার্কশীট</h4></div><div><?php if(!empty($s['photo'])&&file_exists(__DIR__.'/'.$s['photo'])):?><img src="<?=h($s['photo'])?>" style="max-width:80px;max-height:100px;border:2px solid #3498db;border-radius:5px"><?php else:?><div style="width:80px;height:100px;border:2px dashed #3498db;border-radius:5px;display:flex;align-items:center;justify-content:center;background:#f8f9fa"><i class="fas fa-user-graduate" style="font-size:28px;color:#3498db"></i></div><?php endif;?></div></div><hr style="border-top:2px solid #2c3e50"></div>
<div class="si"><div><div class="ir"><span class="il">আইডি</span><span class="iv"><?=h($s['student_id'])?></span></div><div class="ir"><span class="il">নাম</span><span class="iv"><?=h($s['first_name'].' '.$s['last_name'])?></span></div><div class="ir"><span class="il">পিতার নাম</span><span class="iv"><?=h($s['father_name']??'')?></span></div><div class="ir"><span class="il">মাতার নাম</span><span class="iv"><?=h($s['mother_name']??'')?></span></div></div><div><div class="ir"><span class="il">রোল</span><span class="iv"><?=h($s['roll_number'])?></span></div><div class="ir"><span class="il">শ্রেণী</span><span class="iv"><?=h($s['cn'].' '.$s['section'])?><?php if(!empty($s['group_name'])):?> (<?=h($s['group_name'])?>)<?php endif;?></span></div><div class="ir"><span class="il">সেশন</span><span class="iv"><?=h($sn_)?></span></div><div class="ir"><span class="il">পরীক্ষা</span><span class="iv"><?=h(ucfirst($et))?></span></div></div></div>
<table class="tb"><thead><tr><th rowspan="2">বিষয়</th><th colspan="5">প্রাপ্ত নম্বর</th><th rowspan="2">প্রাপ্ত</th><th rowspan="2">পাস</th><th rowspan="2">গ্রেড</th><th rowspan="2">জিপি</th></tr><tr><th>সিকিউ</th><th>এমসিকিউ</th><th>প্র্যাক</th><th>অ্যাসা</th><th>অ্যাটেন</th></tr></thead><tbody>
<?php $tfm=0;$tom=0;$sc=0;$ps=0;$fsd=null;$fsn='';foreach($r as$re):$sfm=$re['full_marks']??100;$som=$re['marks_obtained']??0;$gp_=$re['grade_point']??0;if($sfm<=0)continue;
if(($re['subject_name']=='বাংলা(একত্রে)'||$re['subject_name']=='ইংরেজি(একত্রে)')&&isset($re['cq_marks_array'])&&count($re['cq_marks_array'])>0){$av=array_sum($re['cq_marks_array'])/count($re['cq_marks_array']);$som=$av+$re['mcq_marks'];}
if($re['is_fourth_subject']??false){$fsd=$re;$fsn=$re['subject_id']=='combined_bangla'?'বাংলা (১ম ও ২য় পত্র)':($re['subject_id']=='combined_english'?'ইংরেজি (১ম ও ২য় পত্র)':($re['subject_name']??''));continue;}
$tfm+=$sfm;$tom+=$som;$sc++;if($re['grade']!='F')$ps++;
$dn=$re['subject_name'];if($re['subject_id']=='combined_bangla')$dn='বাংলা (১ম ও ২য় পত্র)';elseif($re['subject_id']=='combined_english')$dn='ইংরেজি (১ম ও ২য় পত্র)';
$cq=$re['cq_marks']??0;$mc=$re['mcq_marks']??0;$nq='';$nm='';
if(($re['subject_name']=='বাংলা(একত্রে)'||$re['subject_name']=='ইংরেজি(একত্রে)')&&isset($re['cq_marks_array'])){$ics=[];foreach($re['cq_marks_array'] as$m)$ics[]=floor($m);$avg=array_sum($re['cq_marks_array'])/count($re['cq_marks_array']);$nq=implode(', ',$ics).' ('.floor($avg).')';$ims=[];foreach($re['mcq_marks_array'] as$m)$ims[]=floor($m);$nm=implode(', ',$ims).' ('.floor($re['mcq_marks']).')';$cq=$nq;$mc=$nm;}
$dn=h($dn);if(!empty($re['subject_code']))$dn.=' <small>('.h($re['subject_code']).')</small>';
?><tr><td><?=$dn?></td><td><?=$cq?></td><td><?=$mc?></td><td><?=$re['practical_marks']??0?></td><td><?=$re['assignment_marks']??0?></td><td><?=$re['attendance_marks']??0?></td><td><?=floor($som)?></td><td><?=$re['pass_marks']??33?></td><td><?=$re['grade']??'F'?></td><td><?=number_format($gp_,2)?></td></tr><?php endforeach;?>
</tbody><tfoot><tr><th colspan="6">মোট</th><th><?=$tom?></th><th><?=$tfm?></th><th colspan="2"></th></tr><tr><th colspan="8">পাস: <?=$ps?>/<?=$sc?><?php if($mp_!==null&&$mp_>0):?> (মেরিট: <?=$mp_?>)<?php endif;?></th><th colspan="2">GPA: <?=number_format($gpa_val,2)?></th></tr></tfoot></table>
<?php if($fsd):?><div class="fs"><table style="width:100%;border-collapse:collapse"><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><tr><td style="border:1px solid #000;padding:4px;font-weight:500"><?=h($fsn)?><?php if(!empty($fsd['subject_code'])):?> (<?=h($fsd['subject_code'])?>)<?php endif;?></td><td style="border:1px solid #000;padding:4px;text-align:center"><?=$fsd['cq_marks']??0?></td><td style="border:1px solid #000;padding:4px;text-align:center"><?=$fsd['mcq_marks']??0?></td><td style="border:1px solid #000;padding:4px;text-align:center"><?=$fsd['practical_marks']??0?></td><td style="border:1px solid #000;padding:4px;text-align:center"><?=$fsd['assignment_marks']??0?></td><td style="border:1px solid #000;padding:4px;text-align:center"><?=$fsd['attendance_marks']??0?></td><td style="border:1px solid #000;padding:4px;text-align:center;font-weight:600"><?=floor($fsd['marks_obtained']??0)?></td><td style="border:1px solid #000;padding:4px;text-align:center"><?=$fsd['pass_marks']??33?></td><td style="border:1px solid #000;padding:4px;text-align:center;font-weight:700;color:<?=($fsd['grade']??'F')=='A+'?'#27ae60':(($fsd['grade']??'F')=='A'?'#2ecc71':(($fsd['grade']??'F')=='A-'?'#3498db':(($fsd['grade']??'F')=='B'?'#9b59b6':(($fsd['grade']??'F')=='C'?'#f39c12':(($fsd['grade']??'F')=='D'?'#e67e22':'#e74c3c')))))?>"><?=$fsd['grade']??'F'?></td><td style="border:1px solid #000;padding:4px;text-align:center"><?=number_format($fsd['grade_point']??0,2)?></td></tr></tbody></table></div><?php endif;?>
<div class="rs"><div><div class="ir"><span class="il">মোট</span><span class="iv" style="font-weight:700"><?=$tom?>/<?=$tfm?></span></div><div class="ir"><span class="il">শতাংশ</span><span class="iv" style="font-weight:700;color:#3498db"><?=$pct?>%</span></div><div class="ir"><span class="il">গ্রেড</span><span class="iv" style="font-weight:700;font-size:16px;color:<?php $gb=cg($gpa_val);echo$gb=='A+'?'#27ae60':($gb=='A'?'#2ecc71':($gb=='A-'?'#3498db':($gb=='B'?'#9b59b6':($gb=='C'?'#f39c12':($gb=='D'?'#e67e22':'#e74c3c')))))?>"><?=$gb?></span></div></div><div><div class="ir"><span class="il">জিপিএ</span><span class="iv" style="font-weight:700"><?=number_format($gpa_val,2)?></span></div><?php if($mp_):?><div class="ir"><span class="il">মেরিট</span><span class="iv" style="font-weight:700;<?=$mp_==1?'color:#f1c40f;font-size:18px':($mp_<=3?'color:#9b59b6;font-size:16px':'color:#3498db')?>"><?=$mp_?></span></div><?php endif;?></div></div>
<div style="margin-top:25px;display:flex;justify-content:space-between"><div><strong>মন্তব্য:</strong> _________________</div><div style="text-align:center"><p>___________________________</p><strong>পরীক্ষা নিয়ন্ত্রক</strong></div><div style="text-align:center"><p>___________________________</p><strong>প্রধান শিক্ষক</strong></div></div></div>
<?php if($i<count($sd)-1):?><div class="pb"></div><?php endif;?><?php endforeach;?></body></html>
<?php $hc=ob_get_contents();ob_end_clean();
header('Content-Type: text/html; charset=utf-8');?><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>PDF জেনারেট হচ্ছে...</title>
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js"></script>
<style>body{font-family:sans-serif;font-size:12px;margin:0;padding:0;background:#fff}.ms{border:2px solid #2c3e50;padding:15px;margin:15px auto;background:#fff;border-radius:8px;max-width:800px}.shd{text-align:center;border-bottom:2px double #3498db;padding-bottom:10px;margin-bottom:15px}.logo{width:60px;height:60px;border:2px solid #3498db;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;overflow:hidden}.shd h3{color:#2c3e50;font-size:18px;margin:5px 0}.shd h4{color:#e74c3c;font-size:15px;margin:5px 0;text-decoration:underline}.tb{width:100%;border-collapse:collapse;margin:10px 0;font-size:10px}.tb th,.tb td{border:1px solid #dee2e6;padding:4px;text-align:center;font-size:10px}.tb th{background:linear-gradient(135deg,#3498db,#2980b9);color:#fff;font-weight:600}.tb tr:nth-child(even){background:#f8f9fa}.rs{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px;padding:10px;border-top:1px dashed #3498db;background:#f8f9fa;border-radius:6px}@media print{.no-print{display:none!important}body{font-size:10px}.ms{box-shadow:none;border:2px solid #000!important;padding:10px;background:#fff}.shd{border-bottom:2px solid #000!important;background:#fff}.tb th{background:#f8f9fa;color:#000}}</style></head><body>
<div id="pdfContainer"><?=$hc?></div><div class="no-print" style="text-align:center;padding:20px"><h3>PDF জেনারেট হচ্ছে...</h3></div>
<script>function gPDF(){const{jsPDF}=window.jspdf,c=document.getElementById('pdfContainer'),m=c.querySelectorAll('.ms');if(!m.length){alert('কোন মার্কশীট নেই');return}
const p=new jsPDF('p','mm','a4'),pw=p.internal.pageSize.getWidth(),ph=p.internal.pageSize.getHeight();let idx=0;function n(i){if(i>=m.length){p.save('merit_position_marksheets_<?=$ci?>_<?=$sn_?>_<?=$et?>.pdf');document.querySelector('.no-print').style.display='none';return}
html2canvas(m[i],{scale:2,useCORS:true,logging:false}).then(c=>{const d=c.toDataURL('image/jpeg',1),ip=p.getImageProperties(d),pw_=pw-20,ph_=(ip.height*pw_)/ip.width;if(i>0)p.addPage();p.addImage(d,'JPEG',10,10,pw_,Math.min(ph_,ph-20));n(i+1)}).catch(()=>n(i+1))}n(0)}
window.onload=function(){setTimeout(gPDF,1000)};</script></body></html>
<?php exit();} ?>
<!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>মেরিট পজিশন PDF</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="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
<style>:root{--p:#6C63FF;--s:#A855F7}*{-webkit-font-smoothing:antialiased}body{font-family:'Hind Siliguri',sans-serif;background:linear-gradient(135deg,#0F0C29,#302B63,#24243E);min-height:100vh;color:#fff;font-size:.85rem}
.navbar{background:linear-gradient(135deg,#1a1a3e,#2d1b69)!important;padding:5px 0!important;border-bottom:1px solid rgba(168,85,247,.2)}
.fc{background:rgba(255,255,255,.06);border-radius:14px;box-shadow:0 8px 32px rgba(0,0,0,.25);border:1px solid rgba(255,255,255,.08);overflow:hidden;margin-bottom:14px}.fc .ch{background:linear-gradient(135deg,rgba(108,99,255,.35),rgba(168,85,247,.25));padding:7px 12px;font-weight:700;font-size:.88rem}.fc .cb{padding:10px 12px}
.fl{font-weight:600;color:#e2e8f0!important;margin-bottom:2px;font-size:.78rem}
.fs{background:rgba(30,41,59,.85);border:1px solid rgba(255,255,255,.12);border-radius:8px;padding:5px 9px;font-size:.82rem;width:100%;color:#fff!important}.fs:focus{background:rgba(30,41,59,.95)!important;border-color:var(--p);box-shadow:0 0 0 3px rgba(108,99,255,.2);outline:none}.fs option{background:#1e1b4b;color:#fff}
.btn-p{background:linear-gradient(135deg,var(--p),var(--s));border:none;border-radius:8px;padding:5px 16px;font-weight:700;font-size:.82rem;box-shadow:0 4px 14px rgba(108,99,255,.3);color:#fff!important}.btn-p:hover{transform:translateY(-1px);box-shadow:0 6px 20px rgba(108,99,255,.4);color:#fff!important}
.btn-o{background:rgba(108,99,255,.12);border:1px solid rgba(108,99,255,.3);border-radius:8px;padding:4px 10px;font-size:.72rem;color:#fff!important}.btn-o:hover{background:rgba(108,99,255,.25);color:#fff!important}
.btn-d{background:rgba(239,68,68,.15);border:1px solid rgba(239,68,68,.3);border-radius:8px;padding:4px 10px;font-size:.72rem;color:#fff!important}
.tb{width:100%;border-collapse:collapse;font-size:.78rem}.tb th{padding:5px 7px;font-weight:700;font-size:.72rem;border-bottom:1px solid rgba(255,255,255,.08);background:rgba(108,99,255,.12);color:#fff!important}.tb td{padding:5px 7px;border-bottom:1px solid rgba(255,255,255,.04);color:#fff!important}.tb tr:hover{background:rgba(255,255,255,.03)}
.badge{color:#fff!important;font-weight:600;font-size:.72rem;padding:3px 8px}.text-muted{color:rgba(255,255,255,.5)!important}.alert{border-radius:8px;color:#fff;padding:8px 12px;font-size:.8rem}.alert-info{background:rgba(14,165,233,.18)}.alert-success{background:rgba(16,185,129,.18)}
@media(max-width:768px){.fs{font-size:.75rem}.tb{font-size:.72rem}}</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-file-pdf me-1"></i>মেরিট পজিশন PDF</a>
<div class="navbar-nav ms-auto flex-row gap-1"><a class="nav-link text-white py-0 px-2" href="../index.php"><i class="fas fa-home"></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-fluid py-2">
<div class="fc"><div class="ch"><i class="fas fa-file-pdf me-1"></i>মেরিট পজিশন সহ মার্কশীট PDF জেনারেট</div><div class="cb">
<form method="GET" class="row g-2 align-items-end"><div class="col-md-3"><label class="fl">শ্রেণী</label><select class="form-select fs" name="class_id" required><option value="">নির্বাচন</option><?php foreach($cs as$c):?><option value="<?=$c['id']?>" <?=$ci==$c['id']?'selected':''?>><?=h($c['name'].' '.$c['section'])?></option><?php endforeach;?></select></div>
<div class="col-md-3"><label class="fl">সেশন</label><select class="form-select fs" name="session" required><option value="">নির্বাচন</option><?php foreach($ss as$s):?><option value="<?=h($s['session'])?>" <?=$sn_==$s['session']?'selected':''?>><?=h($s['session'])?></option><?php endforeach;?></select></div>
<div class="col-md-3"><label class="fl">পরীক্ষার ধরন</label><select class="form-select fs" name="exam_type" required><option value="">নির্বাচন</option><?php foreach($ets as$e):?><option value="<?=h($e['exam_type'])?>" <?=$et==$e['exam_type']?'selected':''?>><?=h($e['exam_type'])?></option><?php endforeach;?></select></div>
<div class="col-md-3 d-flex gap-1 align-items-end pb-1"><button type="submit" class="btn btn-p btn-sm"><i class="fas fa-search"></i> প্রিভিউ</button>
<?php if($ci&&$sn_&&$et):?><a href="?class_id=<?=$ci?>&session=<?=$sn_?>&exam_type=<?=$et?>&generate_pdf=1" class="btn btn-d btn-sm"><i class="fas fa-download"></i> PDF</a><?php endif;?></div></form></div></div>
<?php if($ci&&$sn_&&$et):?><div class="fc"><div class="ch"><i class="fas fa-list me-1"></i>প্রিভিউ - <?=count($sd)?> জন শিক্ষার্থী</div><div class="cb p-0">
<?php if(!empty($sd)):?><div class="alert alert-info mx-2 mt-2 py-1 small"><i class="fas fa-info-circle"></i> প্রথম: <?=h($sd[0]['student']['first_name'].' '.$sd[0]['student']['last_name'])?> (রোল: <?=$sd[0]['student']['roll_number']?>)</div>
<div style="overflow-x:auto"><table class="tb"><thead><tr><th>ক্রম</th><th>রোল</th><th>নাম</th><th>জিপিএ</th><th>মেরিট</th><th>মোট</th></tr></thead><tbody>
<?php foreach($sd as$i=>$d):$mp_=$d['merit_position']??null;?><tr><td><?=$i+1?></td><td><?=h($d['student']['roll_number'])?></td><td><?=h($d['student']['first_name'].' '.$d['student']['last_name'])?></td><td><?=number_format($d['gpa'],2)?></td><td><span class="badge bg-<?=$mp_?'primary':'secondary'?>"><?=$mp_??'-'?></span></td><td><?=$d['total_obtained']?></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>