<?php
if (isset($_POST['subject_register_btn'])) {
    $student_id = inject_checker($connection, $_POST['student_id']);
    $student_name = inject_checker($connection, $_POST['student_name']);
    $student_class = inject_checker($connection, $_POST['student_class']);
    $student_subject = inject_checker($connection, $_POST['student_subject']);
    $current_term = inject_checker($connection, $_POST['current_term']);
    $current_session = inject_checker($connection, $_POST['current_session']);
    $date = date("Y-m-d");

    // Validation
    if (empty($student_id) || empty($student_name)) {
        $_SESSION['msg'] = "Your Registration Number and Name are required.";
        $_SESSION['type'] = "error";
    } elseif ($student_class == "--select--") {
        $_SESSION['msg'] = "Please select your class.";
        $_SESSION['type'] = "error";
    } elseif ($student_subject == "--select--") {
        $_SESSION['msg'] = "Please select a subject.";
        $_SESSION['type'] = "error";
    } elseif ($current_term == "--select--") {
        $_SESSION['msg'] = "Please select the current term.";
        $_SESSION['type'] = "error";
    } else {
        // Check for duplicate subject registration
        $check_stmt = $connection->prepare("SELECT 1 FROM subjects WHERE reg_number = ? AND class = ? AND subjects = ? AND term = ? AND session = ?");
        $check_stmt->bind_param("sssss", $student_id, $student_class, $student_subject, $current_term, $current_session);
        $check_stmt->execute();
        $check_stmt->store_result();

        if ($check_stmt->num_rows > 0) {
            $_SESSION['msg'] = "You cannot register the same subject twice for the same term.";
            $_SESSION['type'] = "error";
        } else {
            $insert_stmt = $connection->prepare("INSERT INTO subjects (reg_number, name, class, subjects, term, session, registration_date) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $insert_stmt->bind_param("sssssss", $student_id, $student_name, $student_class, $student_subject, $current_term, $current_session, $date);
            if ($insert_stmt->execute()) {
                $_SESSION['msg'] = "Registration successful.";
                $_SESSION['type'] = "success";
            } else {
                $_SESSION['msg'] = "Registration failed. Please try again.";
                $_SESSION['type'] = "error";
            }
            $insert_stmt->close();
        }
        $check_stmt->close();
    }

    header("Location: student_register_subject");
    exit();
}
?>

<?php
if (isset($_POST['del_btn'])) {
    $hidden_id = $_POST['hidden_id'];

    $stmt = $connection->prepare("DELETE FROM subjects WHERE id = ? AND class = ?");
    $stmt->bind_param("is", $hidden_id, $student_class);

    if ($stmt->execute()) {
        $_SESSION['msg'] = "Subject deleted successfully.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Error! Could not delete record.";
        $_SESSION['type'] = "error";
    }
    $stmt->close();

    header("Location: student_register_subject");
    exit();
}
?>

<?php
$current_term_checking = "";
$current_session_checking = "";

$stmt = $connection->prepare("SELECT current_term, current_session FROM current_season LIMIT 1");
$stmt->execute();
$stmt->bind_result($current_term_checking, $current_session_checking);
$stmt->fetch();
$stmt->close();
?>


<div class="page-title">
  <div>
    <h1><i class="fa fa-calendar"></i> Subjects you are to offer</h1>
    <p>The following subjects are the specified subjects for your class</p>
  </div>
</div>

<div class="card">
    <div class='row'>
        <div class='col-xs-12 col-sm-12 col-md-12'>
			<div class='panel-primary'>
                <div class='panel-heading'>
                    <h2>Register Subjects</h2>
                </div>

                <div class='panel-body'>
                    <form method='POST' action=''>
                        <div class='row'>
                            <div class='col-md-5'>
                                <div class='input-group'>
                                    <span class='input-group-addon' id='basic-addon2'>Reg Number:</span>
                                    <input type='text' value='<?php echo $student_reg_number; ?>' name='student_id' placeholder='Type Your Registration Number' class='form-control' />
                                </div>
                                <br />
                            </div>

                            <div class='col-md-5'>
                                <div class='input-group'>
                                    <span class='input-group-addon' id='basic-addon2'>Name:</span>
                                    <input type='text' value='<?php echo $surname ." " .$othername ." " .$lastname; ?>' name='student_name' placeholder='Type Your Name' class='form-control' />
                                </div>
                            </div>
                        </div>
                        <br />
                        
                        <div class='row'>
							<div class='col-md-3'>
								<div class='input-group'>
									<span class='input-group-addon' id='basic-addon2'>Class:</span>
									<select class='form-control' name='student_class' id='class-select' required>
										<option selected value="<?= htmlspecialchars($student_class) ?>">
											<?= htmlspecialchars($student_class) ?>
										</option>
									</select>
								</div>
								<br />
							</div>

							<div class='col-md-3'>
								<div class='input-group'>
									<span class='input-group-addon' id='basic-addon2'>Subject:</span>
									<?php
									$subjects = getSubjectsByStudentClass($connection, $student_class);
									?>

									<select class='form-control' name='student_subject' required>
										<?php if (!empty($subjects)) : ?>
											<option selected>Select a Subject</option>
											<?php foreach ($subjects as $subject): ?>
												<option value="<?= htmlspecialchars($subject) ?>"><?= htmlspecialchars($subject) ?></option>
											<?php endforeach; ?>
										<?php else: ?>
											<option>No subjects available</option>
										<?php endif; ?>
									</select>
								</div>
								<br />
							</div>


                            <div class='col-md-3'>
                                <div class='input-group'>
                                    <span class='input-group-addon' id='basic-addon2'>Term:</span>
                                    <select class='form-control' name='current_term'>
                                        <?php
                                            ///// POST ACTION TO DISPLAY CURRRENT TERM /////////////
                                            $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-3'>
                                <div class='input-group'>
                                    <span class='input-group-addon' id='basic-addon2'>Session:</span>
                                    <select class='form-control' name='current_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-3'>
                                <p id='btnsubmit'><input type='submit' name='subject_register_btn' id='submit' value='REGISTER' class='btn btn-large btn-primary login_btn text-center' /></p>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div class='table-responsive'>
                <table class='table table-striped'>
                    <caption class='text-warning'><b>THE TABLE BELOW SHOWS THE SUBJECTS YOU HAVE REGISTERED (!!! PLEASE REGISTER SUBJECTS ONLY WHEN INSTRUCTED TO DO SO !!!)</b></caption>
                    <thead>
                        <tr class='info'>
                            <th>S/N</th>
                            <th>SUBJECTS</th>
                            <th>REG NO</th>
                            <th>CLASS</th>
                            <th>TERM</th>
                            <th>ACTION</th>
                        </tr>
                    <thead>
                    <tbody>
                        <?php
                            if($show_current_term === $current_term_checking && $show_current_session === $current_session_checking){
                                ///// QUERY TO DISPLAY ALREADY REGISTERED SUBJECTS OF A PARTICULAR STUDENT IN THE REGISTER SUBJECTS PAGE //////////////
                                $query = " SELECT * FROM `subjects` WHERE `reg_number` ='{$student_reg_number}' AND `class` = '{$student_class}' AND term = '{$current_term_checking}' AND session = '{$current_session_checking}' ";
                                $run_query = mysqli_query($connection, $query);

                                if($run_query == true){
                                    if(mysqli_num_rows($run_query) > 0){

                                        $i = 0;
                                        while($result = mysqli_fetch_assoc($run_query)){
                                            $i++;
                                            $subject_id = $result['id'];
                                            $subject_reg_no = $result['reg_number'];
                                            $subject_name = $result['subjects'];
                                            $subject_class = $result['class'];
                                            $subject_term = $result['term'];

                                            echo"
                                                <tr>
                                                    <td>{$i}</td>
                                                    <td>{$subject_name}</td>
                                                    <td>{$subject_reg_no}</td>
                                                    <td>{$subject_class}</td>
                                                    <td>{$subject_term}</td>
                                                    <td>
                                                        <form method='POST' action>
                                                            <input type='hidden' name='hidden_id' value='$subject_id' />
                                                            <input type='submit' name='del_btn' value='Delete' class='btn btn-danger btn-xs' />
                                                        </form>
                                                    </td>
                                                </tr>
                                            ";
                                        }
                                    }else{
                                        echo "<p class='text-danger'><b>No Subject Registered Yet</b></p>";
                                    }
                                }else{
                                    echo "<p class='text-danger'><b>No Records Found</b></p>";
                                }
                            }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
