<?php $widget = (is_superadmin_loggedin() ? 2 : 3); ?>
<div class="row">
	<div class="col-md-12">
		<section class="panel">
		<?php echo form_open($this->uri->uri_string(), array('class' => 'validate'));?>
			<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-2 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' id='branch_id'
								data-plugin-selectTwo data-width='100%' data-minimum-results-for-search='Infinity'");
							?>
						</div>
					</div>
					<?php endif; ?>







					<div class="col-md-<?php echo $widget; ?> mb-sm">
						<div class="form-group">
   
   <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%' required"
   );
   
   
   ?>
</div>
</div>




					<div class="col-md-<?php echo $widget; ?> mb-sm">
						<div class="form-group">
							<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>
					<div class="col-md-3 mb-sm">
						<div class="form-group">
							<label class="control-label"><?=translate('group_type')?> <span class="required">*</span></label>
							<?php
								$arrayClass = $this->app_lib->getClass($branch_id);
								echo form_dropdown("class_id", $arrayClass, set_value('class_id'), "class='form-control' id='class_id' onchange='getSectionByClass(this.value,0)'
								required data-plugin-selectTwo data-width='100%' data-minimum-results-for-search='Infinity' ");
							?>
						</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'), true); // Enable 'all' option
            echo form_dropdown(
                "section_id", 
                $arraySection, 
                set_value('section_id'), 
                "class='form-control' id='section_id' required
                 data-plugin-selectTwo data-width='100%' data-minimum-results-for-search='Infinity'"
            );
        ?>
    </div>
</div>





					



					<div class="col-md-3">
						<div class="form-group">
							<label class="control-label"><?=translate('subject')?> <span class="required">*</span></label>
							<?php
								if(!empty(set_value('class_id'))) {
									$arraySubject = array("" => translate('select'));
									$query = $this->subject_model->getSubjectByClassSection(set_value('class_id'), set_value('section_id'));
									$subjects = $query->result_array();
									foreach ($subjects as $row){
										$subjectID = $row['subject_id'];
										$arraySubject[$subjectID] = $row['subjectname'];
									}
								} else {
									$arraySubject = array("" => translate('select_class_first'));
								}
								echo form_dropdown("subject_id", $arraySubject, set_value('subject_id'), "class='form-control' id='subject_id' required
								data-plugin-selectTwo data-width='100%' data-minimum-results-for-search='Infinity' ");
							?>
						</div>
					</div>
				</div>
			</div>
			<footer class="panel-footer">
				<div class="row">
					<div class="col-md-offset-10 col-md-2">
						<button type="submit" name="search" value="1" 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($student)): ?>
		<section class="panel appear-animation" data-appear-animation="<?php echo $global_config['animations'];?>" data-appear-animation-delay="100">
			<?php echo form_open('exam/mark_save', array('class' => 'frm-submit-msg'));
				$data = array(
					'class_id' => $class_id,
					'section_id' => $section_id,
					'exam_id' => $exam_id,
					'subject_id' => $subject_id,
					'session_id' => get_session_id(),
					'branch_id' => $branch_id
				);
				echo form_hidden($data);
			?>
			<header class="panel-heading">
				<h4 class="panel-title"><i class="fas fa-users"></i> <?=translate('mark_entries')?></h4>
				
						<a class="btn btn-default pull-right" href="<?=base_url('exam/csv_Sampledownloader')?>">
							<i class='fas fa-file-download'></i> Download Sample Import File
						</a>
					
			</header>
			<div class="panel-body">

			
				<?php if (!empty($student) && !empty($timetable_detail)) { ?>

					
				<div class="table-responsive mt-md mb-lg">
				<table class="table table-bordered table-condensed mb-none" id="comments_table">
    <thead>
        <tr>
            <th><?=translate('sl')?></th>
            <th><?=translate('member_name')?></th>
            <th><?=translate('category')?></th>
            <th><?=translate('register_no')?></th>
            <th><?=translate('roll')?></th>
            <th>IsAbsent</th>
            <?php
            $distributions = json_decode($timetable_detail['mark_distribution'], true);
            foreach ($distributions as $i => $value) {
                ?>
                <th>
                    <?php 
                        $data = array(
                            'max_mark_' .  $i => $value['full_mark'],
                        );
                        echo form_hidden($data);
                        echo get_type_name_by_id('exam_mark_distribution', $i) . " (" . $value['full_mark'] . ")" 
                    ?>
                </th>
                <th><?=translate('percentage')?></th>
				
            <?php } ?>
			<th><?=translate('remarks')?></th>
        </tr>
    </thead>
    <tbody>
        <?php 
        $count = 1;
        foreach ($student as $key => $row):
            ?>
        <tr>
            

            <td><?php echo $count++; ?></td>
            <td><?php echo $row['first_name'] . ' ' . $row['last_name']; ?></td>
            <td><?php echo get_type_name_by_id('student_category', $row['category_id']); ?></td>
            <td><?php echo $row['register_no']; ?></td>
            <td><?php echo $row['roll']; ?></td>
            <td>
                <div class="checkbox-replace"> 
                    <label class="i-checks"><input type="checkbox" name="mark[<?=$key?>][absent]" <?=($row['get_abs'] == 'on' ? 'checked' : ''); ?>><i></i></label>
                </div>
            </td>
            <?php
            $termID = $this->input->post('term_id');
            $subjectID = $this->input->post('subject_id');
            $evaluations = $this->exam_model->getEvaluate($termID, $subjectID); // Call the getEvaluate function

            // Map the results by student_id for easy access
            $evaluation_data = [];
            foreach ($evaluations as $evaluation) {
                $evaluation_data[$evaluation['student_id']] = $evaluation['total_marks']; // Store total marks by student_id
            }

            $getDetails = json_decode($row['get_mark'], true);
            foreach ($distributions as $id => $ass) {
                $existMark = isset($getDetails[$id]) ? $getDetails[$id] : '0.00';
                $assessment_name = get_type_name_by_id('exam_mark_distribution', $id); // Get the assessment name based on ID
                
                // Check if the assessment name is 'Assignments'
                if ($assessment_name == 'Assignments') {
                    $student_id = $row['student_id']; // Get the student_id from the row
                    $existMark = isset($evaluation_data[$student_id]) ? $evaluation_data[$student_id] : '0.00'; // Assign total_marks or 78 if not found
                }
            ?>
                <td class="min-w-sm">
                    <div class="form-group">
                        <input type="text" class="form-control mark-input" autocomplete="off" 
                            name="mark[<?=$key?>][assessment][<?=$id?>]" 
                            value="<?=$existMark?>" 
                            data-full-mark="<?=$ass['full_mark']?>"
                            data-student="<?=$key?>"
                            data-distribution="<?=$id?>">
                        <span class="error"></span>
                    </div>
                </td>
                <td>
                    <span id="percentage_<?=$key?>_<?=$id?>">
                        <?= !empty($existMark) ? round(($existMark / 100 ) * $ass['full_mark'], 2) : '0.00' ?>%
                    </span>
                </td>
				
			

				

            <?php } ?>

			

            <!-- Add extra row with comments if comments are enabled -->
			<?php if ($comments_enabled): ?>
    <tr class="comments_row">
        <td colspan="<?= count($distributions) * 2 ?>">
            <input type="text" class="form-control" id="comments_load" 
                name="comment[<?=$key?>][comment_1]" 
                placeholder="Enter Comment" 
                list="comments_suggestions"
                value="<?= isset($row['id']) ? $row['id'] : ''; ?>"> <!-- Set the comment value dynamically -->
            <datalist id="comments_suggestions"></datalist>
        </td>
        <td colspan="6">
            <!-- Add More Button -->
            <button type="button" id="add_more_btn" class="btn btn-primary add_more_btn">Add More</button>
        </td>
        <td colspan="<?= count($distributions) * 1 ?>">
            <select class="form-control" name="comment[<?=$key?>][comment_2]">
                <option value="">Select Comment</option>
                <option value="Excellent" <?= (isset($row['comment_2']) && $row['comment_2'] == 'Excellent') ? 'selected' : ''; ?>>Excellent</option>
                <option value="Very Good" <?= (isset($row['comment_2']) && $row['comment_2'] == 'Very Good') ? 'selected' : ''; ?>>Very Good</option>
                <option value="Pass" <?= (isset($row['comment_2']) && $row['comment_2'] == 'Pass') ? 'selected' : ''; ?>>Pass</option>
                <option value="Fail" <?= (isset($row['comment_2']) && $row['comment_2'] == 'Fail') ? 'selected' : ''; ?>>Fail</option>
            </select>
        </td>


		
    </tr>
<?php endif; ?>


        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

				</div>
				<?php } else { echo '<div class="alert alert-subl mt-md text-center">' . translate('no_information_available') . '</div>'; } ?>
			</div>
			<div class="panel-footer">
				<div class="row">
					<div class="col-md-offset-10 col-md-2">
						<button type="submit" class="btn btn-default btn-block" data-loading-text="<i class='fas fa-spinner fa-spin'></i> Processing">
							<i class="fas fa-plus-circle"></i> <?=translate('save')?>
						</button>
					</div>
				</div>
			</div>
			<?php echo form_close(); ?>
		</section>
		<?php endif; ?>
	</div>
</div>
	
<script type="text/javascript">
	$(document).ready(function () {
		$('#branch_id').on('change', function() {
			var branchID = $(this).val();
			getClassByBranch(branchID);
			getExamByBranch(branchID);
			updateBranchRelatedData(branchID);

			$('#subject_id').html('').append('<option value=""><?=translate("select")?></option>');
		});

		$('#section_id').on('change', function() {
			var classID = $('#class_id').val();
			var sectionID =$(this).val();
			$.ajax({
				url: base_url + 'subject/getByClassSection',
				type: 'POST',
				data: {
					classID: classID,
					sectionID: sectionID
				},
				success: function (data) {
					$('#subject_id').html(data);
				}
			});
		});
	});





	$(document).ready(function () {
    // Function to fetch and populate the datalist
    function fetchSuggestions(query = '') {

		var branchID = $('#branch_id').val();
		console.log(branchID);
        $.ajax({
            url: '<?= base_url("exam/fetch_comments") ?>', // Replace with your controller/method
            type: 'GET',
            data: { query: query, branchID:branchID },
            dataType: 'json',
            success: function (data) {
                let suggestions = '';
                if (data.length > 0) {
                    data.forEach(function (comment) {
                        suggestions += `<option value="${comment.id}">${comment.comment}</option>`;
                    });
                }
                $('#comments_suggestions').html(suggestions); // Populate the datalist
            },
            error: function (xhr, status, error) {
                console.error('Error fetching comments:', error); // Log any errors
            }
        });
    }

    // Fetch suggestions when the input box is clicked or focused
    $('#comments_load').on('focus', function () {
        fetchSuggestions(); // Fetch all suggestions on focus
    });

    // Optionally, fetch suggestions based on input value
    $('#comments_load').on('input', function () {
        const query = $(this).val();
        if (query.length >= 2) {
            fetchSuggestions(query); // Fetch suggestions matching the query
        }
    });
});






// $(document).ready(function () {
//     // Add More button functionality
//     $('.add_more_btn').on('click', function () {
//         // Find the closest table row (tr) where the button was clicked
//         let currentRow = $(this).closest('tr');

//         // Clone the row
//         let newRow = currentRow.clone();


// 		newRow.find('.add_more_btn').remove();
//         // Clear the input fields and dropdown values in the cloned row
//         newRow.find('input').val('');
//         newRow.find('select').val('');
//         currentRow.after(newRow);
//     });
// });



$(document).ready(function () {
    // Add More button functionality
    $('.add_more_btn').on('click', function () {
        // Find the closest table row (tr) where the button was clicked
        let currentRow = $(this).closest('tr');

        // Clone the row
        let newRow = currentRow.clone();

        // Remove the Add More button from the cloned row
        newRow.find('.add_more_btn').remove();

        // Clear the input fields and dropdown values in the cloned row
        newRow.find('input').val('');
        newRow.find('select').val('');

        // Append the cloned row to the table
        currentRow.after(newRow);
    });
});





	$(document).on('input', '.mark-input', function () {
        let mark = parseFloat($(this).val());
        let fullMark = parseFloat($(this).data('full-mark'));
        let studentId = $(this).data('student');
        let distributionId = $(this).data('distribution');

        // Calculate percentage
        let percentage = 0;
        if (!isNaN(mark) && !isNaN(fullMark) && fullMark > 0) {
            percentage = (mark /100 ) *  fullMark;
        }

        // Update the percentage display
        $('#percentage_' + studentId + '_' + distributionId).text(percentage.toFixed(2) + '%');
    });



	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>');
    }
}


</script>	