<?php $widget = (is_superadmin_loggedin() ? 3 : 4); ?>
<section class="panel">
	<?php echo form_open($this->uri->uri_string());?>
	<header class="panel-heading">
		<h4 class="panel-title"><?=translate('select_ground')?></h4>
	</header>
	<div class="panel-body">
		<div class="row mb-sm">
		<?php if (is_superadmin_loggedin() ): ?>
			<div class="col-md-3 mb-sm">
				<div class="form-group">
					<label class="control-label"><?=translate('branch')?> <span class="required">*</span></label>
					<?php
						$arrayBranch = $this->app_lib->getSelectList('branch');
						echo form_dropdown("branch_id", $arrayBranch, set_value('branch_id'), "class='form-control' onchange='getClassByBranch(this.value)'
						data-plugin-selectTwo data-width='100%' data-minimum-results-for-search='Infinity' id='branch_id'");
					?>
				</div>
				<span class="error"><?=form_error('branch_id')?></span>
			</div>
		<?php endif; ?>
			<div class="col-md-<?php echo $widget; ?> mb-sm">
				<div class="form-group">
					<label class="control-label"><?=translate('group_type')?> <span class="required">*</span></label>
					<?php
						$arrayClass = $this->app_lib->getSubjectAssign($branch_id);
						echo form_dropdown("class_id", $arrayClass, set_value('class_id'), "class='form-control' id='class_id' onchange='getSectionByClass(this.value,0)'
					 	data-plugin-selectTwo data-width='100%' data-minimum-results-for-search='Infinity' ");
					?>
					<span class="error"><?=form_error('class_id')?></span>
				</div>
			</div>
			<div class="col-md-<?php echo $widget; ?> mb-sm">
				<div class="form-group">
					<label class="control-label"><?=translate('group_name')?> <span class="required">*</span></label>
					<?php
						$arraySection = $this->app_lib->getSections(set_value('class_id'), false);
						echo form_dropdown("section_id", $arraySection, set_value('section_id'), "class='form-control' id='section_id'
						data-plugin-selectTwo data-width='100%' data-minimum-results-for-search='Infinity' ");
					?>
					<span class="error"><?=form_error('section_id')?></span>
				</div>
			</div>




			<div class="col-md-<?php echo $widget; ?> mb-sm">
				<div class="form-group" id="monthlyBox">
					<label class="control-label"><?=translate('month')?> <span class="required">*</span></label>
					<div class="input-group">
						<input type="text" class="form-control" name="timestamp" value="<?=set_value('timestamp', date('Y-F'))?>" data-plugin-datepicker required
						data-plugin-options='{ "format": "yyyy-MM", "minViewMode": "months", "orientation": "bottom"}' />
						<span class="input-group-addon"><i class="icon-event icons"></i></span>
					</div>
				</div>



				
				<!-- <div class="form-group" id="termlyBox" hidden>
					<label class="control-label"><?=translate('session_term')?> <span class="required">*</span></label>
					<?php
   $terms = $this->app_lib->getSessionTerms($branch_id, true, false);
   echo form_dropdown('term_id', $terms, set_value('term_id'),
	"class='form-control' id='session_term' data-width='100%' "
   );


   
   
   ?>
				</div> -->




				
						<div class="form-group" id="termlyBox" hidden>
							<label class="control-label"><?=translate('exam')?> <span class="required">*</span></label>
							<?php
								if(isset($branch_id)){
									$arrayExam = array("" => translate('select'));
									$exams = $this->db->get_where('exam', array('branch_id' => $branch_id,'session_id' => get_session_id()))->result();
									foreach ($exams as $row){
										$arrayExam[$row->id] = $this->application_model->exam_name_by_id($row->id);
									}
								} else {
									$arrayExam = array("" => translate('select_branch_first'));
								}
								echo form_dropdown("exam_id", $arrayExam, set_value('exam_id'), "class='form-control' id='exam_id' required data-plugin-selectTwo
								data-width='100%' data-minimum-results-for-search='Infinity' ");
							?>
						</div>
				



			





				<div class="form-group">
    
    <div>
        <label>
            <input type="radio" name="report_type" value="monthly" checked onclick="toggleMode('monthly')"> <?=translate('Monthly')?>
        </label>
        <label>
            <input type="radio" name="report_type" value="termly" onclick="toggleMode('termly')"> <?=translate('Termly')?>
        </label>
    </div>
</div>






			</div>





			
		</div>
	</div>






	<footer class="panel-footer">
		<div class="row">
			<div class="col-md-offset-10 col-md-2">
				<button type="submit" name="submit" value="search" class="btn btn btn-default btn-block"> <i class="fas fa-filter"></i> <?=translate('filter')?></button>
			</div>
		</div>
	</footer>
    <?php echo form_close();?>
</section>

<?php if (isset($studentlist)): ?>
	<section class="panel appear-animation mt-sm" data-appear-animation="<?=$global_config['animations'] ?>" data-appear-animation-delay="100">
		<header class="panel-heading">
			<h4 class="panel-title"><i class="fas fa-users"></i> <?=translate('attendance_report')?></h4>
		</header>
		<div class="panel-body">
			<style type="text/css">
				table.dataTable.table-condensed > thead > tr > th {
				  padding-right: 3px !important;
				}
			</style>
			<!-- hidden school information prints -->
			<div class="export_title">Monthly Attendance Sheet on <?=date("F Y", strtotime($year.'-'.$month)); ?> <?php 
				echo translate('group_type') .' : '. get_type_name_by_id('class', $class_id);
				echo ' ( ' .translate('group_name'). ' : ' .get_type_name_by_id('section', $section_id).' )';
				?></div>
			<div class="row mt-sm">
				<div class="col-md-offset-8 col-md-4">
					<table class="table table-condensed table-bordered text-dark text-center">
						<tbody>
							<tr>
								<td><strong>Weekends :</strong> W<span class="visible-print">W</span></td>
								<td><strong>Present :</strong> <i class="far fa-check-circle hidden-print text-success"></i><span class="visible-print">P</span></td>
								<td><strong>Absent : </strong> <i class="far fa-times-circle hidden-print text-danger"></i><span class="visible-print">A</span></td>
								<td><strong>Holiday : </strong> <i class="fas fa-hospital-symbol hidden-print text-info"></i><span class="visible-print">H</span></td>
								<td><strong>Late : </strong> <i class="far fa-clock hidden-print text-tertiary"></i><span class="visible-print">L</span></td>
								<td><strong>Half Day : </strong> <i class="fas fa-star-half-alt text-tertiary"></i><span class="visible-print">HD</span></td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
			<div class="row">
				<div class="col-md-12">
					<div class="mb-lg">
						<table class="table table-bordered table-hover table-condensed mb-none text-dark table-export">
							<thead>
								<tr>
									<th><?=translate('member_name')?></th>
<?php
$weekends = $this->attendance_model->getWeekendDaysSession($branch_id);
$getHolidays = $this->attendance_model->getHolidays($branch_id);
$getHolidays = explode('","', $getHolidays);
$reportType = $this->input->post('report_type');
for($i = 1; $i <= $days; $i++){
$date = date('Y-m-d', strtotime($year . '-' . $month . '-' . $i));

$startDate = '2024-12-21';
$endDate = '2025-01-12';
?>


<script>
    console.log("Total Late: ", <?= json_encode($reportType); ?>);
</script>

									<th <?php if(in_array($date, $weekends)) { echo "style='background-color: #f99'"; } ?> class="text-center no-sort"><?php echo date('D', strtotime($date)); ?> <br> <?php echo date('d', strtotime($date)); ?></th>
<?php } ?>
<?php if($reportType == 'monthly') {?>
									<th class="text-center" style="padding-right: 15px !important;">(%)</th>
									<th class="text-center" style="padding-right: 15px !important;">W</th>
									<th class="text-center text-success" style="padding-right: 15px !important;">P</th>
									<th class="text-center text-danger" style="padding-right: 15px !important;">A</th>
									<th class="text-center text-tertiary" style="padding-right: 15px !important;">L</th>
									<th class="text-center text-tertiary">HD</th>
								</tr>
							</thead>
						
							<tbody>
							
<?php
foreach ($studentlist as $row):
$total_present = 0;
$total_absent = 0;
$total_late = 0;
$total_half_day = 0;
$total_weekends = 0;
$studentID = $row['enroll_id'];

$startDate = '2024-12-27';
$endDate = '2025-01-21';
$reportType = $this->input->post('report_type');


?>


								<tr>
									<td><?php echo $row['first_name'] . ' ' . $row['last_name']; ?> <div class="visible-print"> / <?php echo translate('register_no') . " " .  $row['register_no'] ?></div></td>
<?php
for ($i = 1; $i <= $days; $i++) { 
$date = date('Y-m-d', strtotime($year . '-' . $month . '-' . $i));

$atten = $this->attendance_model->get_attendance_by_date($studentID, $date);
?>
							<td class="center">
<?php if (!empty($atten)) { ?>
								<span data-toggle="popover" data-trigger="hover" data-placement="top" data-trigger="hover" data-content="<?php echo $atten['remark']; ?>">
<?php if ($atten['status'] == 'A') { $total_absent++; ?>
									<i class="far fa-times-circle text-danger"></i><span class="visible-print">A</span>
<?php } if ($atten['status'] == 'P') { $total_present++; ?>
									<i class="far fa-check-circle text-success"></i><span class="visible-print">P</span>
<?php } if ($atten['status'] == 'L') { $total_late++; ?>
									<i class="far fa-clock text-info"></i><span class="visible-print">L</span>
<?php } if ($atten['status'] == 'H'){ ?>
									<i class="fas fa-hospital-symbol text-tertiary"></i><span class="visible-print">H</span>
<?php } if ($atten['status'] == 'HD'){ $total_half_day++; ?>
									<i class="fas fa-star-half-alt text-tertiary"></i><span class="visible-print">HD</span>
<?php } ?>
								</span>
<?php } else {

	if(in_array($date, $getHolidays)) {
		echo '<i class="fas fa-hospital-symbol text-tertiary"></i><span class="visible-print">H</span>';
	} else {
		if(in_array($date, $weekends)) {
			$total_weekends++;
			echo '<span class="text-success">W</span>';
		}
	}
} ?>
							</td>
<?php } ?>
									<td class="center"><?php 
									$total_working_days = ($total_present + $total_absent + $total_late + $total_half_day);
									if ($total_working_days == 0) {
										echo "-";
									} else {
										$total_present = ($total_present + $total_late + $total_half_day);
										$percentage = ($total_present / $total_working_days) * 100;
										echo round($percentage);
									}

									?></td>
									<td class="center"><?=$total_weekends?></td>
									<td class="center"><?=$total_present?></td>
									<td class="center"><?=$total_absent?></td>
									<td class="center"><?=$total_late?></td>
									<td class="center"><?=$total_half_day?></td>
									<?php endforeach; ?>
								</tr>

								
							</tbody>
							<?php } else if($reportType == 'termly') { ?>


								<?php
// Fetch selected term from the request
$selected_term_id = 1; // Ensure correct term selection handling

// Fetch term start and end dates from the database
$this->db->select('start_date, end_date');
$this->db->where('id', $selected_term_id);
$query = $this->db->get('schoolterm');
$term_data = $query->row_array();

if ($term_data && !empty($term_data['start_date']) && !empty($term_data['end_date'])) {
    $startDate = $term_data['start_date']; // Directly use database values
    $endDate = $term_data['end_date'];
} else {
    $startDate = null;
    $endDate = null;
}

// Calculate total working days (excluding weekends)
$total_working_days = 0;
if ($startDate && $endDate) {
    $start = new DateTime($startDate);
    $end = new DateTime($endDate);

    while ($start <= $end) {
        $dayOfWeek = $start->format('N'); // 6 = Saturday, 7 = Sunday
        if ($dayOfWeek < 6) { // Monday-Friday
            $total_working_days++;
        }
        $start->modify('+1 day'); // Move to next day
    }
}

// Fetch holidays for the selected term
//$getHolidays = $this->attendance_model->getHolidays($branch_id, $startDate, $endDate);
//$getHolidays = explode('","', $getHolidays);

?>
	
	<tr hidden>
    <td class="center">
    <input type="text" class="form-control" id="total_working_days" value="<?= htmlentities($total_working_days) ?>"  >
</td>

</tr>
							<thead>	
<tr>
<th><?=translate('member_name')?></th>
								<th class="text-center" style="padding-right: 15px !important;">(%)</th>
								
									<th class="text-center" style="padding-right: 15px !important;">W</th>
									<th class="text-center text-success" style="padding-right: 15px !important;">P</th>
									<th class="text-center text-danger" style="padding-right: 15px !important;">A</th>
									<th class="text-center text-tertiary" style="padding-right: 15px !important;">L</th>
									<th class="text-center text-tertiary">HD</th>
								</tr>
							</thead>
						
							<tbody>
							

					

							<?php
foreach ($studentlist as $row):
    $total_present = 0;
    $total_absent = 0;
    $total_late = 0;
    $total_half_day = 0;
    $total_weekends = 0;
    $studentID = $row['enroll_id'];

    // Calculate weekends dynamically
    if ($startDate && $endDate) {
        $start = strtotime($startDate);
        $end = strtotime($endDate);

        for ($date = $start; $date <= $end; $date += 86400) { // Loop day by day
            $dayOfWeek = date('N', $date); // 6 = Saturday, 7 = Sunday
            if ($dayOfWeek == 6 || $dayOfWeek == 7) {
                $total_weekends++;
            }
        }
    }
?>

<tr>
    <td><?php echo htmlentities($row['first_name'] . ' ' . $row['last_name']); ?>
        <div class="visible-print"> / <?php echo translate('register_no') . " " . htmlentities($row['register_no']); ?></div>
    </td>

    <?php
    for ($i = 1; $i <= $days; $i++) { 
        $date = date('Y-m-d', strtotime($year . '-' . $month . '-' . $i));

        // Fetch attendance
        $atten1 = $this->attendance_model->get_attendance_by_termdate($studentID, $startDate, $endDate);
    ?>
    <td class="center">
        <?php if (!empty($atten1)) { ?>
            <span data-toggle="popover" data-trigger="hover" data-placement="top" data-content="<?php echo htmlentities($atten1['remark']); ?>">
                <?php 
                if ($atten1['status'] == 'A') { $total_absent++; ?>
                    <i class="far fa-times-circle text-danger"></i><span class="visible-print">A</span>
                <?php } elseif ($atten1['status'] == 'P') { $total_present++; ?>
                    <i class="far fa-check-circle text-success"></i><span class="visible-print">P</span>
                <?php } elseif ($atten1['status'] == 'L') { $total_late++; ?>
                    <i class="far fa-clock text-info"></i><span class="visible-print">L</span>
                <?php } elseif ($atten1['status'] == 'H') { ?>
                    <i class="fas fa-hospital-symbol text-tertiary"></i><span class="visible-print">H</span>
                <?php } elseif ($atten1['status'] == 'HD') { $total_half_day++; ?>
                    <i class="fas fa-star-half-alt text-tertiary"></i><span class="visible-print">HD</span>
                <?php } ?>
            </span>
        <?php } else {
            if (in_array($date, $getHolidays)) {
                echo '<i class="fas fa-hospital-symbol text-tertiary"></i><span class="visible-print">H</span>';
            } else {
                if (date('N', strtotime($date)) == 6 || date('N', strtotime($date)) == 7) {
                    echo '<span class="text-success">W</span>';
                }
            }
        } ?>
    </td>
    <?php } ?>

    <!-- <td class="center"><?php 
        $total_working_days = ($total_present + $total_absent + $total_late + $total_half_day);
        if ($total_working_days == 0) {
            echo "-";
        } else {
            $total_present_calc = ($total_present + $total_late + $total_half_day);
            $percentage = ($total_present_calc / $total_working_days) * 100;
            echo round($percentage);
        }
    ?></td> -->

	
<td class="center" id="attendance_percentage_<?= $studentlist['enroll_id'] ?>">-</td>
<td class="center">
    <input type="text" class="form-control" name="total_weekends" id="total_weekends_<?= $studentlist['enroll_id'] ?>" value="<?= htmlentities($total_weekends) ?>">
</td>
<td class="center">
    <input type="text" class="form-control" name="total_present" id="total_present_<?= $studentlist['enroll_id'] ?>" value="<?= htmlentities($total_present) ?>">
</td>
<td class="center">
    <input type="text" class="form-control" name="total_absent" id="total_absent_<?= $studentlist['enroll_id'] ?>" value="<?= htmlentities($total_absent) ?>" >
</td>
<td class="center">
    <input type="text" class="form-control" name="total_late" id="total_late_<?= $studentlist['enroll_id'] ?>" value="<?= htmlentities($total_late) ?>" >
</td>
<td class="center">
    <input type="text" class="form-control" name="total_half_day" id="total_half_day_<?= $studentlist['enroll_id'] ?>" value="<?= htmlentities($total_half_day) ?>" >
</td>



</tr>

<?php endforeach; ?>

								</tr>

								
							</tbody>
							<?php } ?>
						</table>
					</div>
				</div>
			</div>
		</div>
	</section>
<?php endif; ?>



<script>

$(document).ready(function(e){ 
e.preventDefault();
});
$(document).ready(function(){ 

	
$('#branch_id').on('change', function() {
			var branchID = $(this).val();
			updateBranchRelatedData(branchID);
			//$('#subject_id').html('').append('<option value=""><?=translate("select")?></option>');
		});
});

    function toggleMode(mode) {
        if (mode === 'monthly') {
            document.getElementById('monthlyBox').style.display = 'block';
            document.getElementById('termlyBox').style.display = 'none';
        } else if (mode === 'termly') {
            document.getElementById('monthlyBox').style.display = 'none';
            document.getElementById('termlyBox').style.display = 'block';
        }
    }


	document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll("input").forEach(input => {
        input.addEventListener("input", function () {
            let studentIdMatch = this.id.match(/\d+/);
            let studentId = studentIdMatch ? studentIdMatch[0] : null;
            if (studentId) {
                calculatePercentage(studentId);
            }
        });
    });

    // Run initial calculation
    document.querySelectorAll("[id^='attendance_percentage_']").forEach(cell => {
        let studentIdMatch = cell.id.match(/\d+/);
        let studentId = studentIdMatch ? studentIdMatch[0] : null;
        if (studentId) {
            calculatePercentage(studentId);
        }
    });
});

function calculatePercentage(studentId) {
    console.log(`Calculating percentage for student ID: ${studentId}`);

    let totalPresent = parseInt(document.getElementById(`total_present_${studentId}`)?.value) || 0;
    let totalAbsent = parseInt(document.getElementById(`total_absent_${studentId}`)?.value) || 0;
    let totalLate = parseInt(document.getElementById(`total_late_${studentId}`)?.value) || 0;
    let totalHalfDay = parseInt(document.getElementById(`total_half_day_${studentId}`)?.value) || 0;

    console.log(`Total Present: ${totalPresent}, Total Absent: ${totalAbsent}, Total Late: ${totalLate}, Total Half Day: ${totalHalfDay}`);

    let totalWorkingDays = 29;
    let percentageCell = document.getElementById(`attendance_percentage_${studentId}`);

    if (totalWorkingDays > 0 && percentageCell) {
        let totalPresentCalc = totalPresent + (totalLate * 0.5) + (totalHalfDay * 0.5);
        let percentage = (totalPresentCalc / totalWorkingDays) * 100;

        console.log(`Calculated Percentage: ${percentage}`);

        percentageCell.textContent = Math.round(percentage) + "%";
    }
}







	function updateBranchRelatedData(branchId) {
    if (branchId) {
        

        // Fetch session terms
        $.ajax({
            url: '<?= base_url('ajax/getTermsByBranch') ?>',
            type: 'POST',
            data: { branch_id: branchId },
            success: function (data) {
                $('#session_term').html(data);
            },
            error: function () {
                alert('<?= translate('an_error_occurred') ?>');
            }
        });
    } else {
        // Reset both dropdowns if no branch is selected
        $('#class_id').html('<option value=""><?= translate('select_branch_first') ?></option>');
        $('#session_term').html('<option value=""><?= translate('select_branch_first') ?></option>');
    }
}




// $(document).on('change', '#session_term', function() {
//         const term_id = $(this).val();
//         const branch_id = '<?= $branch_id ?>'; // Pass branch_id dynamically if needed
//         if (term_id) {
//             $.ajax({
//                 url: "<?= base_url('attendance/get_attendance_data') ?>",
//                 type: "POST",
//                 data: { term_id: term_id, branch_id: branch_id },
//                 success: function(response) {
//                     $('#attendanceTable').html(response); // Replace the table content
//                 },
//                 error: function() {
//                     alert("An error occurred while fetching data.");
//                 }
//             });
//         }
//     });

	

</script>