<?php
if (isset($_POST['result_upload_btn'])) {
    // Check if total_num is provided
    if (!isset($_POST["total_num"]) || empty($_POST["total_num"])) {
        echo "<p class='text-danger'><b>Error: total_num is missing or empty</b></p>";
        exit();
    }

    for ($j = 0; $j < (int)$_POST["total_num"]; $j++) {
        $student_id = inject_checker($connection, $_POST['student_id'][$j]);
        $student_name = inject_checker($connection, $_POST['student_name'][$j]);
        $student_class = inject_checker($connection, $_POST['student_class'][$j]);
        $result_term = inject_checker($connection, $_POST['result_term'][$j]);
        $result_session = inject_checker($connection, $_POST['result_session'][$j]);
        $result_subject = inject_checker($connection, $_POST['result_subject'][$j]);
        $student_exam = inject_checker($connection, $_POST['student_exam'][$j]);
        $date = date('d/M/Y');
        
        // Check if the CA and Project results are already available
        $query = "SELECT * FROM `results1` WHERE `class` = '{$student_class}' AND `term` = '{$result_term}' AND `session` = '{$result_session}' AND `subjects` = '{$result_subject}' AND `reg_number` = '{$student_id}'";
        $run_query = mysqli_query($connection, $query);
        
        // If record already exists, display CA and Project and update exam only
        if (mysqli_num_rows($run_query) > 0) {
            // Fetch existing CA and Project scores
            $existing_result = mysqli_fetch_assoc($run_query);
            $student_ca = $existing_result['ca1'];
            $student_project = $existing_result['ca2'];
            $student_total = $student_ca + $student_project + $student_exam;

            // Update the existing record with the exam score and total
            $update_query = "UPDATE `results1` SET `exam` = '{$student_exam}', `subject_total` = '{$student_total}', `date_of_upload` = '{$date}' WHERE `class` = '{$student_class}' AND `term` = '{$result_term}' AND `session` = '{$result_session}' AND `subjects` = '{$result_subject}' AND `reg_number` = '{$student_id}'";
            $run_update = mysqli_query($connection, $update_query);
            
            if ($run_update) {
                $msg = "<p class='text-success'><b><span class='glyphicon glyphicon-ok'></span> Exam Score Uploaded Successfully</b></p>";
            } else {
                $msg = "<p class='text-danger'><b><span class='glyphicon glyphicon-remove'></span> Failed to Upload Exam Score! Try Again</b></p>";
            }
        } else {
            // If record does not exist, CA and Project must be missing, notify the user
            $msg = "<p class='text-danger'><b><span class='glyphicon glyphicon-remove'></span> CA and Project scores are missing. Please upload them first.</b></p>";
        }
    }

    // Fetch students' scores for a specific subject, class, term, and session
    $query1 = "
        SELECT * 
        FROM `results1` 
        WHERE `subjects` = '{$result_subject}' 
        AND `class` = '{$student_class}' 
        AND `term` = '{$result_term}' 
        AND `session` = '{$result_session}' 
        ORDER BY `subject_total` DESC
    ";
    $run_query1 = mysqli_query($connection, $query1);

    if ($run_query1) {
        $i = 1; // Rank counter
        $previous_subject_total = null; // Tracks the last `subject_total`
        $rank = 1; // Current rank
        
        // Iterate through the results and calculate ranks
        while ($outputs = mysqli_fetch_assoc($run_query1)) {
            $rec_id = (int)$outputs['id'];
            $subject_t = $outputs['subject_total'];
            $reg_no = $outputs['reg_number'];
            
            // Update rank only if the current total is different from the previous one
            if ($previous_subject_total !== null && $subject_t == $previous_subject_total) {
                // Keep same rank for tie
            } else {
                $rank = $i; // Assign current rank to this score group
            }

            // Update the rank in the database
            $sql = "UPDATE results1 SET subject_rank = '{$rank}' WHERE id = '{$rec_id}'";
            $run_query2 = mysqli_query($connection, $sql);

            // Increment the rank counter
            $i++;

            // Update the previous subject total for the next iteration
            $previous_subject_total = $subject_t;
		}
    }
}
?>


<div class='card'>
    <?php
        if(isset($msg)){
            echo $msg;
        }
    ?>
    <div class='panel panel-primary print_div'>
        <div class='panel-heading noprint clearfix'>
            <div class='pull-right'>
                <a href='teacher_dashboard.php?teacher_excel_result_upload' class='btn btn-success btn-xs' style='color:#fff;'><i class='fa fa-file-excel-o'></i> Excel / CSV Result Upload & Export</a>
            </div>
            <h4 class='text-center'>Upload Student Exam Score</h4>
        </div>
        <div class='panel-body'>
            <form class='noprint' method='POST' action='' id='result_upload'>
                <div class='row'>
					<div class='col-md-4'>
						<div class='input-group'>
							<span class='input-group-addon' id='basic-addon2'>Class:</span>
							<select class='form-control' name='result_upload_class' id='class-select'>
                                <option selected disabled>Select Class</option>
								<?php
								$query = "SELECT * FROM `classes`";
								$run_query = mysqli_query($connection, $query);
								if (mysqli_num_rows($run_query) > 0) {
									while ($result = mysqli_fetch_assoc($run_query)) {
										$attendance = $result['classes'];
										echo "<option value='{$attendance}'>{$attendance}</option>";
									}
								}
								?>
                            </select>
                        </div>
                    </div>

                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Subject:</span>
                            <select class='form-control' name='result_upload_subject' id='subject-select'>                                
                               <option selected>Select a Class First</option>
							</select>
						</div>
					</div>

					<div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Term:</span>
                            <select class='form-control' name='result_upload_term' required>
                                <?php
                                    $query = " SELECT * FROM `current_season` ";
                                    $run_query = mysqli_query($connection, $query);
                                    if(mysqli_num_rows($run_query) == 1){
                                        while($result = mysqli_fetch_assoc($run_query)){
                                            $show_current_term = $result['current_term'];
                                            echo "<option>{$show_current_term}</option>";
                                        }
                                    }
                                ?>
                            </select>
                        </div>
                        <br />
                    </div>

                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Session:</span>
                            <select class='form-control' name='result_upload_session'>
                                <?php
                                    ///////////// POST ACTION TO DISPLAY CURRENT SESSION //////////////
                                    $query = " SELECT * FROM `current_season` ";
                                    $run_query = mysqli_query($connection, $query);
                                    if(mysqli_num_rows($run_query) == 1){
                                        while($result = mysqli_fetch_assoc($run_query)){
                                            $show_current_session = $result['current_session'];
                                            echo"
                                                <option>{$show_current_session}</option>
                                            ";
                                        }
                                    }
                                ?>
                            </select>
                        </div>
                    </div>

                    <div>
                        <input type='submit' name='go_upload' value='GET' class='btn btn-md btn-primary' />
                    </div>

                </div>
            </form>
            <br />
			<?php
			if(isset($_POST['go_upload'])){
				$result_upload_class = inject_checker($connection, $_POST['result_upload_class']);
				$result_upload_subject = inject_checker($connection, $_POST['result_upload_subject']);
				$result_upload_term = inject_checker($connection, $_POST['result_upload_term']);
				$result_upload_session = inject_checker($connection, $_POST['result_upload_session']);

				// Error checking for empty fields
				if($result_upload_class === $select){
					$error[] = "Error: Please Select the Class for result upload";
				}
				if($result_upload_subject === $select){
					$error[] = "Error: Please Select the Subject for result upload";
				}
				if($result_upload_term === $select){
					$error[] = "Error: Please Select the Term for result upload";
				}

				if(empty($error)){
					$query = "
						SELECT s.name, s.reg_number, s.class, r.ca1, r.ca2
						FROM subjects s
						LEFT JOIN results1 r ON 
							s.reg_number = r.reg_number 
							AND s.class = r.class 
							AND s.subjects = r.subjects 
							AND s.term = r.term 
							AND s.session = r.session
						WHERE s.class = '{$result_upload_class}' 
							AND s.subjects = '{$result_upload_subject}' 
							AND s.term = '{$result_upload_term}' 
							AND s.session = '{$result_upload_session}' 
						ORDER BY s.name ASC
					";
					
					$run_query = mysqli_query($connection, $query);

					if(mysqli_num_rows($run_query) > 0){
						echo "
							<div class='row text-center'>
								<div class='col-md-12 col-xs-12'>
									<h3 style='margin-top: 0;'>{$teacher_name}</h3>
									<h4>SCORE SHEET</h4>
								</div>
								
								<div class='col-md-3 col-xs-3'>
									<p><b>CLASS: </b><br>{$result_upload_class}</p>
								</div>
								
								<div class='col-md-3 col-xs-3'>
									<p><b>SESSION: </b><br>{$result_upload_session}</p>
								</div>
								
								<div class='col-md-3 col-xs-3'>
									<p><b>TERM: </b><br>{$result_upload_term}</p>
								</div>
								
								<div class='col-md-3 col-xs-3'>
									<p><b>SUBJECT: </b><br>{$result_upload_subject}</p>
								</div>
							</div>
							<div class='table-responsive'>
								<table class='table table-bordered'>
									<thead>
										<tr>
											<th>S/N</th>
											<th>NAMES</th>
											<th>REG NO</th>
											<th>1st CA (20)</th>
											<th>2nd CA (20)</th>
											<th>EXAM (60)</th>
										</tr>
									</thead>
									<tbody>
									<form method='POST' action'upload_exam.php?go_upload'>
						";
						
						$i = 0; $k = 1;
						while($result = mysqli_fetch_assoc($run_query)){
							$students_reg_no = $result['reg_number'];
							$student_names = $result['name'];
							$student_class = $result['class'];
							$student_ca = isset($result['ca1']) ? $result['ca1'] : '0';
							$student_project = isset($result['ca2']) ? $result['ca2'] : '0';

							echo "
								<tr>
									<td>{$k}</td>
									<td style='padding: 0; margin: 0; width: 30%;'>
										<input type='text' style='border: 0; font-size: 14px; width: 100%; height: 37px; padding-left: 2%;' name='student_name[]' value='{$student_names}' readonly />
									</td>
									<td style='padding: 0; margin: 0; width: 30%;'>
										<input type='text' style='border: 0; font-size: 14px; width: 100%; height: 37px; padding-left: 2%;' name='student_id[]' value='{$students_reg_no}' readonly /> 
									</td>

									<input type='hidden' name='student_class[]' value='{$student_class}' />
									<input type='hidden' name='result_term[]' value='{$result_upload_term}' />
									<input type='hidden' name='result_session[]' value='{$result_upload_session}' />
									<input type='hidden' name='result_subject[]' value='{$result_upload_subject}' />

									<td style='padding: 0; margin: 0;'>
										<input id='hidden' type='text' style='width: 100%; font-size: 14px; height: 37px;' name='student_ca[]' value='{$student_ca}' readonly />
									</td>
									<td style='padding: 0; margin: 0;'>
										<input id='hidden' type='text' style='width: 100%; font-size: 14px; height: 37px;' name='student_project[]' value='{$student_project}' readonly />
									</td>
									<td style='padding: 0; margin: 0;'>
										<input type='text' style='width: 100%; font-size: 14px; height: 37px;' name='student_exam[]' required placeholder='Enter Exam Score' />
									</td>
								</tr>
							";
							$i++; $k++;
						}
						echo "
									</tbody>
								</table>
							</div>
							<br />
							<div class='row'>
								<div class='col-md-1'>
									<input type='hidden' name='total_num' value='{$i}' />
								</div>
								<div class='col-md-3'>
									<input type='submit' name='result_upload_btn' id='submit' value='Upload' class='btn btn-large btn-primary login_btn text-center noprint' />
									<button type='button' class='btn btn-default noprint' onclick='window.print()' value='print a div!'><span class='glyphicon glyphicon-print'></span> Print </button>
								</div>
							</div>
						</form>
						";
					} else {
						echo "<p class='text-danger'><b>No records found !!!</b></p>";
					}
				}
			}
			?>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
	$(document).ready(function () {
        $("#select-all").click(function () {
            $(".select-student").prop('checked', this.checked);
        });
    });
	
    $(document).ready(function () {
        $("#class-select").change(function () {
            var selectedClass = $(this).val();

            $.ajax({
                url: "fetch_subjects.php", // PHP file to fetch subjects
                method: "POST",
                data: { class: selectedClass },
                success: function (data) {
                    $("#subject-select").html(data);
                }
            });
        });
    });
	
</script>