<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register_subject_btn'])) {
    if (isset($_POST['selected_students'])) {
        $selected_students = $_POST['selected_students'];
        $class = trim($_POST['class']);
        $subject = trim($_POST['subject']);
        $term = trim($_POST['term']);
        $session = trim($_POST['session']);

        $success_count = 0;
        $duplicate_count = 0;

        // Prepare name fetch query
        $name_stmt = $connection->prepare("SELECT firstname, othername, lastname FROM students WHERE reg_number = ?");
        // Prepare duplicate check query
        $check_stmt = $connection->prepare("SELECT id FROM subjects WHERE reg_number = ? AND class = ? AND subjects = ? AND term = ? AND session = ?");
        // Prepare insert query
        $insert_stmt = $connection->prepare("INSERT INTO subjects (name, reg_number, class, subjects, term, session, registration_date, registration_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

        foreach ($selected_students as $reg_number) {
            // Get student name
            $name_stmt->bind_param("s", $reg_number);
            $name_stmt->execute();
            $name_result = $name_stmt->get_result();

            if ($name_row = $name_result->fetch_assoc()) {
                $full_name = trim($name_row['firstname'] . " " . $name_row['othername'] . " " . $name_row['lastname']);
                $registration_date = date("Y-m-d");
                $registration_time = date("H:i:s");

                // Check for duplicate
                $check_stmt->bind_param("sssss", $reg_number, $class, $subject, $term, $session);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();

                if ($check_result->num_rows === 0) {
                    // Insert if not duplicate
                    $insert_stmt->bind_param("ssssssss", $full_name, $reg_number, $class, $subject, $term, $session, $registration_date, $registration_time);
                    if ($insert_stmt->execute()) {
                        $success_count++;
                    }
                } else {
                    $duplicate_count++;
                }
            }
        }

        // Close statements
        $name_stmt->close();
        $check_stmt->close();
        $insert_stmt->close();

        // Set session feedback
        $_SESSION['msg'] = "$success_count students registered successfully.<br />$duplicate_count duplicates skipped.";
        $_SESSION['type'] = ($success_count > 0) ? "success" : "warning";

        header("Location: register_student_subject");
        exit();
    } else {
        $_SESSION['msg'] = "No students selected!";
        $_SESSION['type'] = "warning";
        header("Location: register_student_subject");
        exit();
    }
}
?>




<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Subject Management</h1>
    <p>Register Student Subject</p>
  </div>  
</div>
<div class='card'>	
    <div class='panel panel-primary'>
        <div class='panel-body'>
            <p class="text-danger">Select the Class and Subject</p>
            <form method='POST' action=''>
                <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='class' id='class-select' required>
								<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>
						<br />
					</div>

					<div class='col-md-3'>
						<div class='input-group'>
							<span class='input-group-addon' id='basic-addon2'>Subject:</span>
							<select class='form-control' name='subject' id='subject-select' required>
								<option selected>Select a Class First</option>
							</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='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-3'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Session:</span>
                            <select class='form-control' name='session' 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_session = $result['current_session'];
                                            echo "<option>{$show_current_session}</option>";
                                        }
                                    }
                                ?>
                            </select>
                        </div>
                        <br />
                    </div>
                    
                    <div class='col-md-3'>
                        <input type='submit' name='get_student_btn' value='GET' class='btn btn-primary' />
                    </div>
                </div>
            </form>
            <br />

			<?php
				if(isset($_POST['get_student_btn'])){
					// Capture Form Data
					$selected_class = mysqli_real_escape_string($connection, $_POST['class']);
					$selected_subject = mysqli_real_escape_string($connection, $_POST['subject']);
					$selected_term = mysqli_real_escape_string($connection, $_POST['term']);
					$selected_session = mysqli_real_escape_string($connection, $_POST['session']);

					// Fetch Students
					$query = "SELECT * FROM `students` WHERE `class` = '$selected_class' ORDER BY `firstname` ASC";
					$run_query = mysqli_query($connection, $query);

					if(mysqli_num_rows($run_query) > 0){
						echo "<form method='POST' action=''>";
						
						// Hidden Inputs to Pass Form Data
						echo "<input type='hidden' name='class' value='$selected_class'>";
						echo "<input type='hidden' name='subject' value='$selected_subject'>";
						echo "<input type='hidden' name='term' value='$selected_term'>";
						echo "<input type='hidden' name='session' value='$selected_session'>";

						echo "<div class='table-responsive'>";
						echo "<table class='table table-bordered' id ='myTable'>
								<thead>
									<tr>
										<th><input type='checkbox' id='select-all' /></br>Select All</th>
										<th>Adm No</th>
										<th>Name</th>
										<th>Subject</th>
										<th>Term</th>
										<th>Session</th>
									</tr>
								</thead>
								<tbody>";

						while($row = mysqli_fetch_assoc($run_query)){
							$full_name = $row['firstname']." ".$row['othername']." ".$row['lastname'];
							echo "<tr>
									<td><input type='checkbox' class='select-student' name='selected_students[]' value='{$row['reg_number']}' /></td>
									<td>{$row['reg_number']}</td>
									<td>{$full_name}</td>
									<td>{$selected_subject}</td>
									<td>{$selected_term}</td>
									<td>{$selected_session}</td>
								  </tr>";
						}

						echo "</tbody></table></div>";
						echo "<input type='submit' name='register_subject_btn' value='SUBMIT SELECTION' class='btn btn-primary' />";
						echo "</form>";
					} else {					
						$_SESSION['msg'] = "No students found in the selected class.";
				        $_SESSION['type'] = "error";
						header("Location: register_student_subject");
        exit();
					}
				}
				?>
        </div>
    </div>
</div>
