// Subject teacher
								<?php
								$selected_class = $_POST['class'] ?? '';
								$selected_subject = $_POST['subject'] ?? '';
								$subjects = [];

								if (!empty($selected_class)) {
									$stmt = $connection->prepare("SELECT DISTINCT subject FROM subject_teacher WHERE staff_id = ? AND class = ?");
									$stmt->bind_param("is", $staff_id, $selected_class);
									$stmt->execute();
									$result = $stmt->get_result();
									
									while ($row = $result->fetch_assoc()) {
										$subjects[] = $row['subject'];
									}
									$stmt->close();
								}
								?>
<?php
if (isset($_POST['result_upload_btn'])) {
    if (!isset($_POST["total_num"]) || empty($_POST["total_num"])) {
        $_SESSION['msg'] = "Total Score is missing or empty";
        $_SESSION['type'] = "error";
        exit();
    }

    $total_num = (int)$_POST["total_num"];
    $student_class = inject_checker($connection, $_POST['student_class'][0]);
    $result_term = inject_checker($connection, $_POST['result_term'][0]);
    $result_session = inject_checker($connection, $_POST['result_session'][0]);
    $result_subject = inject_checker($connection, $_POST['result_subject'][0]);

    // Check if result already exists
    $check_query = "SELECT 1 FROM `results1` WHERE `class` = ? AND `term` = ? AND `session` = ? AND `subjects` = ? LIMIT 1";
    $stmt = mysqli_prepare($connection, $check_query);
    mysqli_stmt_bind_param($stmt, "ssss", $student_class, $result_term, $result_session, $result_subject);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);

    if (mysqli_stmt_num_rows($stmt) > 0) {
        $_SESSION['msg'] = "This Result Has Already Been Uploaded";
        $_SESSION['type'] = "warning";
        header("Location: subject_teacher_upload_ca");
        exit();
    }
    mysqli_stmt_close($stmt);

    // Prepare insert statement
    $insert_query = "INSERT INTO `results1`(`class`, `term`, `session`, `reg_number`, `name`, `subjects`, `ca1`, `ca2`, `subject_total`, `date_of_upload`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = mysqli_prepare($connection, $insert_query);

    if (!$stmt) {
        $_SESSION['msg'] = "Statement preparation failed: " . mysqli_error($connection);
        $_SESSION['type'] = "danger";
        header("Location: subject_teacher_upload_ca");
        exit();
    }

    for ($j = 0; $j < $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_ca = (int)inject_checker($connection, $_POST['student_ca'][$j]);
        $student_project = (int)inject_checker($connection, $_POST['student_project'][$j]);
        $student_total = $student_ca + $student_project;
        $date = date('d/M/Y');

        mysqli_stmt_bind_param($stmt, "sssssssdds", $student_class, $result_term, $result_session, $student_id, $student_name, $result_subject, $student_ca, $student_project, $student_total, $date);

        if (!mysqli_stmt_execute($stmt)) {
            $_SESSION['msg'] = "Failed to insert record for student {$student_name}: " . mysqli_stmt_error($stmt);
            $_SESSION['type'] = "error";
            header("Location: subject_teacher_upload_ca");
            exit();
        }
    }

    mysqli_stmt_close($stmt);
    $_SESSION['msg'] = "C.A Uploaded Successfully";
    $_SESSION['type'] = "success";
    header("Location: subject_teacher_upload_ca");
    exit();
}
?>



<div class='page-title hidden-print'>
  <div>
    <h1><i class='fa fa-laptop'></i> Result Management</h1>
    <p>Upload C.A Scores</p>
  </div>
</div>
<div class='card'>
    <div class='panel panel-primary print_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' onchange='this.form.submit()' required>
								<option disabled <?= $selected_class == '' ? 'selected' : '' ?>>Select Class</option>
								<?php
								$stmt = $connection->prepare("SELECT DISTINCT class FROM subject_teacher WHERE staff_id = ?");
								$stmt->bind_param("i", $staff_id);
								$stmt->execute();
								$result = $stmt->get_result();

								while ($row = $result->fetch_assoc()) {
								    $class = htmlspecialchars($row['class']);
								    $selected = ($selected_class == $class) ? 'selected' : '';
								    echo "<option value='{$class}' $selected>{$class}</option>";
								}
								$stmt->close();
								?>
							</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'>                                
                              <?php
								if (!empty($subjects)) {
								    echo "<option disabled>Select Subject</option>";
								    foreach ($subjects as $subj) {
								        $subj = htmlspecialchars($subj);
								        $selected = ($selected_subject == $subj) ? 'selected' : '';
								        echo "<option value='{$subj}' {$selected}>{$subj}</option>";
								    }
								} else {
								    echo "<option>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>
                        <br />
                    </div>

                    <div class='col-md-4'>
                        <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']);

					if ($result_upload_class === $select) {
						$_SESSION['msg'] = "Please select the class for result upload";
						$_SESSION['type'] = "danger";
					} elseif ($result_upload_subject === $select) {
						$_SESSION['msg'] = "Please select the subject for result upload";
						$_SESSION['type'] = "danger";
					} elseif ($result_upload_term === $select) {
						$_SESSION['msg'] = "Please select the term for result upload";
						$_SESSION['type'] = "danger";
					} else {
						$query = "SELECT * FROM `subjects` WHERE `class` = '{$result_upload_class}' AND `subjects` = '{$result_upload_subject}' AND `term` = '{$result_upload_term}' AND `session` = '{$result_upload_session}' ORDER BY `name` ASC";
						$run_query = mysqli_query($connection, $query);

						if (mysqli_num_rows($run_query) > 0) {
							$_SESSION['msg'] = "Student records loaded successfully. <br />You may now enter scores.";
							$_SESSION['type'] = "success";

							echo "
							<div class='row text-center'>
								<div class='col-md-12 col-xs-12'>
									<h4>{$school_name}</h4>                                     
								    <h4>CONTINOUS ASSESSMENT 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'>
							<form method='POST' action=''>
								<table class='table table-hover table-bordered' id='myTable'>
								    <thead>
								        <tr>
								            <th>S/N</th>
								            <th>NAMES</th>
								            <th>REG NO</th>
								            <th>1st CA (20)</th>
								            <th>2nd CA (20)</th>
								        </tr>
								    </thead>
								    <tbody>
							";

							$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'];
								$result_term = $result['term'];
								$result_subject = $result['subjects'];
								$result_session = $result['session'];

								echo "
								<tr>
								    <td>{$k}</td>
								    <td>
								        {$student_names}
								        <input type='hidden' name='student_name[]' value='{$student_names}' />
								    </td>
								    <td>
								        {$students_reg_no}
								        <input type='hidden' name='student_id[]' value='{$students_reg_no}' />
								    </td>
								    <input type='hidden' name='student_class[]' value='{$student_class}' />
								    <input type='hidden' name='result_term[]' value='{$result_term}' />
								    <input type='hidden' name='result_session[]' value='{$result_session}' />
								    <input type='hidden' name='result_subject[]' value='{$result_subject}' />
								    <td><input type='text' name='student_ca[]' required /></td>
								    <td><input type='text' name='student_project[]' required /></td>
								</tr>
								";
								$i++;
								$k++;
							}

							echo "
								    </tbody>
								</table>
								<br />
								<div class='row'>
								    <div'>
								        <input type='hidden' name='total_num' value='{$i}' />
								    </div>
								    <div class='col-md-4'>
								        <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()'><span class='glyphicon glyphicon-print'></span> Print </button>
								    </div>
								</div>
							</form>
							</div>
							";
						} else {
							$_SESSION['msg'] = "No records found!";
							$_SESSION['type'] = "error";
						}
					}
				}
				?>

        </div>
    </div>
</div>
