<?php $marksheet_template = $this->marksheet_template_model->getTemplate($templateID, $branchID);





?>

<style type="text/css">
    .mark-container {
        height: 100%;
        min-width: 1000px;
        position: relative;
        z-index: 2;
        margin: 0 auto;
        font-size: 12px;
    
		padding: <?= isset($marksheet_template['top_space']) ? $marksheet_template['top_space'] . 'px' : '0px' ?> 
         <?= isset($marksheet_template['right_space']) ? $marksheet_template['right_space'] . 'px' : '0px' ?> 
         <?= isset($marksheet_template['bottom_space']) ? $marksheet_template['bottom_space'] . 'px' : '0px' ?> 
         <?= isset($marksheet_template['left_space']) ? $marksheet_template['left_space'] . 'px' : '0px' ?>;


    }
    table {
        border-collapse: collapse;
        width: 100%;
        margin: 0 auto;
    }

	



    @page {
        margin: -2px;
        size: <?= $marksheet_template['page_layout'] == 1 ? 'portrait' : 'landscape'; ?>;
    }

    @media print {
        .pagebreak {
            clear: both;
            page-break-before: always;
        }
        .table-bordered > thead > tr > th,
        .table-bordered > tbody > tr > th,
        .table-bordered > tfoot > tr > th,
        .table-bordered > thead > tr > td,
        .table-bordered > tbody > tr > td,
        .table-bordered > tfoot > tr > td {
            border-color: #000 !important;
            background: transparent !important;
        }
    }

    .table-bordered {
        border-color: #000 !important;
    }

    .background {
        position: absolute;
        z-index: 0;
        width: 100%;
        height: 100%;
    <?php if (empty($marksheet_template['background'])) { ?>
        background: #fff;
    <?php } else { ?>
        background-image: url("<?= base_url('uploads/marksheet/' . $marksheet_template['background']) ?>") !important;
        background-repeat: no-repeat !important;
        background-size: 100% 100% !important;
    <?php } ?>
    }

    .subject-row {
        height: 10px;
    }


	.last-page-section {
    page-break-before: always;
}

</style>

<?php
$extINTL = extension_loaded('intl');
if (!empty($student_array)) {
	foreach ($student_array as $sc => $studentID) {
		$result = $this->exam_model->getStudentReportCard($studentID, $examID, $sessionID, $class_id, $section_id);

		$student = $result['student'];
		$getMarksList = $result['exam'];

		// Loop through the array to get subject IDs
$subjectIDs = array_column($getMarksList, 'subject_id');


		
$rankDetails = $this->db->where(array('exam_id' => $examID, 'enroll_id' => $student['enrollID']))->get('exam_rank')->result_array();


		$rankDetail = $this->db->where(array('exam_id' => $examID, 'student_id' => $student['enrollID']))->get('mark')->result_array();
		$subjectAssign = $this->db->select('subject_assign.subject_id, staff.name as teacher_name')
    ->from('subject_assign')
    ->join('staff', 'staff.id = subject_assign.teacher_id', 'left')
    ->where([
        'subject_assign.class_id' => $class_id,
        'subject_assign.branch_id' => $branchID,
        'subject_assign.session_id' => $sessionID,
        'subject_assign.section_id' => $section_id
    ])
    ->where_in('subject_assign.subject_id', $subjectIDs)
    ->get()
    ->result_array();




	$assignedTeachers = $this->db->select('teacher_allocation.teacher_id, staff.name as teacher_name')
    ->from('teacher_allocation')
    ->join('staff', 'staff.id = teacher_allocation.teacher_id', 'left')
    ->where([
        'teacher_allocation.class_id' => $class_id,
        'teacher_allocation.branch_id' => $branchID,
        'teacher_allocation.session_id' => $sessionID,
        'teacher_allocation.section_id' => $section_id
    ])
    ->get()
    ->result_array();


	//$classPosition1 = $this->exam_model->generate_class_position($class_id, $section_id, $sessionID, $examID, $branchID);	
	
	$classPosition1 = $this->exam_model->generate_class_position($class_id, $section_id, $sessionID, $examID, $branchID);


	// Create a mapping: student_id => rank
	
	$studentRanks = array_column($classPosition1, 'rank', 'student_id');


	
	
	// For example, to get the rank for a specific student:
	// $desired_student_id = 510; // change to the student_id you need
	// $rankForStudent = isset($studentRanks[$desired_student_id]) ? $studentRanks[$desired_student_id] : null;
	$rankForStudent = isset($studentRanks[$student['enrollID']]) ? $studentRanks[$student['enrollID']] : null;

	
	//var_dump($rankForStudent);
	

		$getExam = $this->db->where(array('id' => $examID))->get('exam')->row_array();
		$schoolYear = get_type_name_by_id('schoolyear', $sessionID, 'school_year');

		
		$timetable_exam = $this->db->where(array('exam_id' => $examID))->get('timetable_exam')->row_array();


		
		$extendsData = [];
		$extendsData['print_date'] = $print_date;
		$extendsData['schoolYear'] = $schoolYear;
		$extendsData['exam_name'] = $getExam['name'];

		$extendsData['subject_teacher'] = array_column($subjectAssign, 'teacher_id');
		
		$extendsData['assignedTeachers'] = array_column($assignedTeachers, 'teacher_name');
		

		$extendsData['class_position'] = $rankForStudent;

	
		$teacher_comments = [];
		foreach ($rankDetail as $rank) {
			$teacher_comments[$rank['subject_id']] = empty($rank['teacher_comments']) ? '' : $rank['teacher_comments'];
		}


		$teacher_assign = [];
		foreach ($subjectAssign as $teacher) {
			$teacher_assign[$teacher['subject_id']] = empty($teacher['teacher_name']) ? '' : $teacher['teacher_name'];
		}


		//print_r($teacher_assign);die;
		
	
		

		$extendsData['teachers_comments'] = $teacher_comments;

		$extendsData['teacher_assign'] = $teacher_assign;
		//$extendsData['teacher_assign'] = $teacher_assign;

		$extendsData['principal_comments'] = empty($rankDetails[0]['principal_comments']) ? '' : $rankDetails[0]['principal_comments'];
		$extendsData['teacher_comments'] = empty($rankDetails[0]['teacher_comments']) ? '' : $rankDetails[0]['teacher_comments'];

	
		$rank = empty($rankDetails[0]['rank']) ? '' : $rankDetails[0]['rank'];
		$extendsData['class_position'] = !empty($rank) ? ordinal($rank) : '';
		

		$extendsData['teacher_name'] = empty($assignedTeachers[0]['teacher_name']) ? '' : $assignedTeachers[0]['teacher_name'];
		//var_dump($extendsData['teacher_comments']);die;	


	
		//print_r($extendsData['teachers_comments']);die;

		$cover_content = $this->marksheet_template_model->tagsReplace($student, $marksheet_template, $extendsData, 'cover_page');



		$header_content = $this->marksheet_template_model->tagsReplace($student, $marksheet_template, $extendsData, 'header_content');
		$footer_content = $this->marksheet_template_model->tagsReplace($student, $marksheet_template, $extendsData, 'footer_content');
		
		

		?>


<div class="student-marksheet last-page-section">
	

<div style="position: relative; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; max-width: 1200px; margin: 0 auto; top: 0;">
	<!-- Cover Page -->
	<div class="cover-page" style="page-break-after: always; text-align: center; padding: 50px;">
		<?php echo $cover_content; ?>
	</div>
</div>


</div>

<br>
<br>
<br>
<br>


<div style="position: relative; width: 100%; height: 100%;"> 
	<div class="background"></div>
	<div class="mark-container">


		
		<?php echo $header_content ?>
		<table class="table table-condensed table-bordered mt-lg">
			<thead>
				<tr>
					<th>Subjects</th>



				<?php 
				foreach ($getMarksList as $row) {
					$total_obtain_marks = 0;
					$total_full_marks = 0;
					$fullMarkDistribution = json_decode($row['mark_distribution'], true) ?: [];
					$obtainedMark = json_decode($row['get_mark'], true) ?: [];

					foreach ($fullMarkDistribution as $i => $val) {
						$obtained_mark = floatval($obtainedMark[$i]);
						$fullMark = floatval($val['full_mark']);
						$passMark = floatval($val['pass_mark']);
						if ($obtained_mark < $passMark) {
							$result_status = 0;
						}
				
						$total_obtain_marks += $obtained_mark;
						$obtained = $row['get_abs'] == 'on' ? 'Absent' : $obtained_mark;
						$total_full_marks += $fullMark;
					}
				}
				?>
			
			<?php 
$markDistributions = json_decode($timetable_exam['mark_distribution'], true);

foreach ($markDistributions as $id => $data) { 
    $fullMark = isset($data['full_mark']) ? floatval($data['full_mark']) : 0; // Ensure full_mark exists
?>
    <th><?php echo get_type_name_by_id('exam_mark_distribution', $id) . " ($fullMark)"; ?></th>
<?php } ?>

				<?php if ($getExam['type_id'] == 1) { ?>
					<th>Total(100)</th>
				<?php } elseif($getExam['type_id'] == 2) { ?>
					<th>Grade</th>
					<th>Point</th>
<?php if ($marksheet_template['remark'] == 1) { ?>
					<th>Remark</th>
<?php } ?>
				<?php } ?> 
				<?php if ($getExam['type_id'] == 3) { ?>
					<th>Total(100)</th>
					<?php if ($marksheet_template['subject_position'] == 1) { ?>
					<th>Position</th>
<?php } ?>
					<th>Grade</th>
					<!-- <th>Point</th> -->
<?php if ($marksheet_template['remark'] == 1) { ?>
					<th>Remark</th>
<?php } ?>
				<?php } ?>


				</tr>
			</thead>
			<tbody>
			<?php
			$colspan = count($markDistribution) + 1;
			$total_grade_point = 0;
			$grand_obtain_marks = 0;
			$grand_full_marks = 0;
			$result_status = 1;
			foreach ($getMarksList as $row) {
				?>
				<tr style="margin: top 100px;" >
					<td valign="middle" width="35%"><strong><?=$row['subject_name']?></strong></td>
				<?php 
				$total_obtain_marks = 0;
				$total_full_marks = 0;
				// $fullMarkDistribution = json_decode($row['mark_distribution'], true);
				// $obtainedMark = json_decode($row['get_mark'], true);
				$fullMarkDistribution = json_decode($row['mark_distribution'], true) ?: [];
$obtainedMark = json_decode($row['get_mark'], true) ?: [];

				foreach ($fullMarkDistribution as $i => $val) {
					$obtained_mark = floatval($obtainedMark[$i]);
					$fullMark = floatval($val['full_mark']);
					$passMark = floatval($val['pass_mark']);
					if ($obtained_mark < $passMark) {
						$result_status = 0;
					}

					$total_obtain_marks += $obtained_mark;
					$obtained = $row['get_abs'] == 'on' ? 'Absent' : $obtained_mark;
					$total_full_marks += $fullMark;
					?>
				<?php if ($getExam['type_id'] == 1 || $getExam['type_id'] == 3){ ?>
					<td valign="middle">
						<?php 
							if ($row['get_abs'] == 'on') {
								echo 'Absent';
							} else {
								//echo $obtained_mark . '/' . $fullMark;
								echo $obtained_mark;
							}
						?>
					</td>
				<?php } if ($getExam['type_id'] == 2){ ?>
					<td valign="middle">
						<?php 
							if ($row['get_abs'] == 'on') {
								echo 'Absent';
							} else {
								$percentage_grade = ($obtained_mark * 100) / $fullMark;
								//$grade = $this->exam_model->get_grade($percentage_grade, $getExam['branch_id']);
								$grade = $this->exam_model->get_marksheet_grade($percentage_grade, $getExam['branch_id'], $marksheet_template['id']);
					
								echo $grade['name'];
							}
						?>
					</td>
				<?php } ?>
				<?php
				}
				$grand_obtain_marks += $total_obtain_marks;
				$grand_full_marks += $total_full_marks;
				?>
				<?php if($getExam['type_id'] == 1 || $getExam['type_id'] == 3) { ?>
				
					<td valign="middle"><?=$total_obtain_marks ?></td>
					<?php if ($marksheet_template['subject_position'] == 1) {?>


					
					
						<?php
$positions = $this->exam_progress_model->getSubjectPosition(
    $student['class_id'], 
    $student['section_id'], 
    [$examID], 
    $sessionID, 
    [$row['subject_id']] // Ensure subject_id is an array
);

// Default position if student is not found
$student_position = 'Not Available';

// Ensure $positions is an array and contains the student's ID
if (!empty($positions) && isset($positions[$student['id']])) {
    foreach ($positions[$student['id']] as $pos) {
        if ($pos['subject_id'] == $row['subject_id']) {
            $student_position = $pos['position'];
            break; // Stop loop once the position is found
        }
    }
} else {
    echo "Student ID not found in positions list!";
}
?>

<td valign="middle"><?php echo $student_position; ?></td>




<?php } ?>
				<?php } if($getExam['type_id'] == 2) { 
					$colspan += 1;
					$percentage_grade = ($total_obtain_marks * 100) / $total_full_marks;
					//$grade = $this->exam_model->get_grade($percentage_grade, $getExam['branch_id']);
					$grade = $this->exam_model->get_marksheet_grade($percentage_grade, $getExam['branch_id'], $marksheet_template['id']);
					$total_grade_point += $grade['grade_point'];
					?>
					<td valign="middle"><?=$grade['name']?></td>
				
<?php if ($marksheet_template['remark'] == 1) { ?>
					<td valign="middle"><?=$grade['remark']?></td>
<?php } ?>
				<?php } if ($getExam['type_id'] == 3) {
					$colspan += 2;
					$percentage_grade = ($total_obtain_marks * 100) / $total_full_marks;
					//$grade = $this->exam_model->get_grade($percentage_grade, $getExam['branch_id']);
					$grade = $this->exam_model->get_marksheet_grade($percentage_grade, $getExam['branch_id'], $marksheet_template['id']);
					
					$total_grade_point += $grade['grade_point'];
					?>
					<td valign="middle"><?=$grade['name']?></td>
				
<?php if ($marksheet_template['remark'] == 1) { ?>
					<td valign="middle"><?=$grade['remark']?></td>
<?php } ?>
				<?php } ?>

				</tr>
				<?php if ($marksheet_template['comments'] == 1) { 
					$comments = $this->db->where(array('student_id' => $studentID, 'subject_id' => $row['subject_id']))->get('commentary')->result_array();
					foreach ($comments as $comment) {
					?>
					<tr>
						<td colspan="4" valign="middle">
							<?php 
							if (!empty($comment['comment_value'])) {
								echo nl2br($comment['comment_value']); 
							} else {
								echo 'No comments';
							}
							?>
						</td>
						



						<td colspan="5" valign="middle">
							<?php 
							if (!empty($comment['comment_remarks'])) {
								echo nl2br($comment['comment_remarks']); 
							} else {
								echo 'No comments';
							}
							?>
						</td>


					</tr>
					<?php } ?>
				<?php } ?>

				<tr class="text-weight-semibold">
				<td colspan="9" valign="top">Teacher's Comment :
					<?php 
					if (isset($extendsData['teachers_comments'][$row['subject_id']])) {
						echo nl2br($extendsData['teachers_comments'][$row['subject_id']]);
					} else {
						echo 'No comments';
					}
					?>
				</td>
				
			</tr>
			

			<tr class="text-weight-semibold">
    <td valign="top">SUBJECT TEACHER'S NAME :</td>
   
        <td valign="top">
		<?php 
					if (isset($extendsData['teacher_assign'][$row['subject_id']])) {
						echo nl2br($extendsData['teacher_assign'][$row['subject_id']]);
					} else {
						echo 'No comments';
					}
					?>;
           
        </td>
  
</tr>


<tr class="subject-row">
        <td valign="middle" colspan="<?= $colspan + 9 ?>" style="height: 30%;"></td>
    </tr>

			
	
			<?php } ?>

			





			

			<div class="student-marksheet last-page-section">
	



		<?php if ($getExam['type_id'] == 1 || $getExam['type_id'] == 3) { ?>
		
			<tr class="text-weight-semibold">
				<td valign="top" >GRAND TOTAL :</td>
				<td valign="top" colspan="<?=$colspan?>"><?=$grand_obtain_marks . '/' . $grand_full_marks; ?>, Average : <?php $percentage = ($grand_obtain_marks * 100) / $grand_full_marks; echo number_format($percentage, 2, '.', '')?>%</td>
			</tr>
		<?php if ($extINTL == true) { ?>
			<tr class="text-weight-semibold">
				<td valign="top" >GRAND TOTAL IN WORDS :</td>
				<td valign="top" colspan="<?=$colspan?>">
					<?php
					$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
					echo ucwords($f->format($grand_obtain_marks));
					?>
				</td>
			</tr>
		<?php } ?>
		<?php } if ($getExam['type_id'] == 2) { ?>
			
		<?php } if ($getExam['type_id'] == 1 || $getExam['type_id'] == 3) { ?>
<?php if ($marksheet_template['result'] == 1) { ?>
			<tr class="text-weight-semibold">
				<td valign="top" >RESULT :</td>
				<td valign="top" colspan="<?=$colspan?>"><?=$result_status == 0 ? 'Fail' : 'Pass'; ?></td>
			</tr>
		<?php } } ?>
<?php if ($marksheet_template['position'] == 1) { ?>
			<tr class="text-weight-semibold">
				<td valign="top">Position :</td>
				<td valign="top" colspan="<?=$colspan?>"> <?php echo (!empty($rankDetail->rank) ? $rankDetail->rank : translate("not_generated"));?></td>
			</tr>
<?php } ?>
		</tbody>
	</table>
	
	<div class="last-page-section" style="width: 100%; display: flex;">
		<div style="width: 50%; padding-right: 15px;">
<?php
if ($marksheet_template['attendance_percentage'] == 1) {
				$year = explode('-', $schoolYear);
				$getTotalWorking = $this->db->where(array('enroll_id' => $student['enrollID'], 'year(date)' => $year[0]))->get('student_attendance')->num_rows();
				$getTotalAttendance = $this->db->where(array('enroll_id' => $student['enrollID'], 'status' => 'P', 'year(date)' => $year[0]))->get('student_attendance')->num_rows();
				$attenPercentage = empty($getTotalWorking) ? '0.00' : ($getTotalAttendance * 100) / $getTotalWorking;
				?>
			<table class="table table-bordered table-condensed">
				<tbody>
					<tr>
						<th colspan="2" class="text-center">Attendance</th>
					</tr>
					<tr>
						<th style="width: 65%;">No. of working days</th>
						<td><?=$getTotalWorking?></td>
					</tr>
					<tr>
						<th style="width: 65%;">No. of days attended</th>
						<td><?=$getTotalAttendance?></td>
					</tr>
					<tr>
						<th style="width: 65%;">Attendance Percentage</th>
						<td><?=number_format($attenPercentage, 2, '.', '') ?>%</td>
					</tr>
				</tbody>
			</table>
<?php } ?>
		</div>
<?php
if ($marksheet_template['grading_scale'] == 1) {
	if ($getExam['type_id'] != 1) {
		?>
		<div style="width: 50%; padding-left: 15px;">
			<table class="table table-condensed table-bordered">
				<tbody>
					<tr>
						<th colspan="3" class="text-center">Grading Scale</th>
					</tr>
					<tr>
						<th>Grade</th>
						<th>Min Percentage</th>
						<th>Max Percentage</th>
					</tr>
				<?php 
				$grade = $this->db->where('branch_id', $getExam['branch_id'])->get('grade')->result_array();
				foreach ($grade as $key => $row) {
				?>
					<tr>
						<td style="width: 30%;"><?=$row['name']?></td>
						<td style="width: 30%;"><?=$row['lower_mark']?>%</td>
						<td style="width: 30%;"><?=$row['upper_mark']?>%</td>
					</tr>
				<?php } ?>
				</tbody>
			</table>
		</div>
<?php } } ?>
	</div>
	

<?php echo $footer_content; ?>

</div>
</div>
<div class="pagebreak"> </div> 
</div>
<?php }
 } ?>
