<?php
require_once("../../public/connection.php");
require_once("../../public/functions.php");

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register_subject_btn'])) {
    if (isset($_POST['selected_students'])) {
        $selected_students = $_POST['selected_students'];
        $class = mysqli_real_escape_string($connection, $_POST['class']);
        $subject = mysqli_real_escape_string($connection, $_POST['subject']);
        $term = mysqli_real_escape_string($connection, $_POST['term']);
        $session = mysqli_real_escape_string($connection, $_POST['session']);

        $success_count = 0;
        $duplicate_count = 0;

        foreach ($selected_students as $reg_number) {
            $reg_number = mysqli_real_escape_string($connection, $reg_number);
            $name_query = "SELECT firstname, othername, lastname FROM students WHERE reg_number = '$reg_number'";
            $name_result = mysqli_query($connection, $name_query);

            if ($name_row = mysqli_fetch_assoc($name_result)) {
                $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 entry
                $check_query = "SELECT id FROM `subjects` WHERE `reg_number` = '$reg_number' AND `class` = '$class' AND `subjects` = '$subject' AND `term` = '$term' AND `session` = '$session'";
                $check_result = mysqli_query($connection, $check_query);

                if (mysqli_num_rows($check_result) == 0) {
                    // Insert new record
                    $insert_query = "INSERT INTO `subjects` (`name`, `reg_number`, `class`, `subjects`, `term`, `session`, `registration_date`, `registration_time`) 
                                     VALUES ('$full_name', '$reg_number', '$class', '$subject', '$term', '$session', '$registration_date', '$registration_time')";
                    
                    if (mysqli_query($connection, $insert_query)) {
                        $success_count++;
                    }
                } else {
                    $duplicate_count++;
                }
            }
        }

        // Store message in session before redirect
        $_SESSION['msg'] = "✅ $success_count students registered successfully. ❌ $duplicate_count duplicates skipped.";
        header("Location: teacher_dashboard.php?vp_register_students_subjects");
        exit();
    } else {
        $_SESSION['msg'] = "⚠️ No students selected!";
        header("Location: teacher_dashboard.php?vp_register_students_subjects");
        exit();
    }
}
?>


<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Subject Management</h1>
    <p>Register Student Subject</p>
  </div>
  <div>
    <ul class='breadcrumb'>
      <li><a href='#'><i class='fa fa-home fa-lg'></i></a></li>
      <li><a href='#'>Subject Management</a></li>
      <li><a href='#'>Register Student Subject</a></li>
    </ul>
  </div>
</div>
<div class='card'>
	<?php
		session_start();
		if (isset($_SESSION['msg'])) {
			echo "<div class='alert alert-info'>" . $_SESSION['msg'] . "</div>";
			unset($_SESSION['msg']); // Clear message after displaying it
		}
	?>

   <?php
        if(isset($msg)){
            echo $msg;
        }
    ?>
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>Student Subject Registration Sheet</h4>
        </div>
        <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'>
								<thead>
									<tr>
										<th><input type='checkbox' id='select-all' /></br>Select All</th>
										<th>Reg Number</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 {
						echo "<p class='text-danger'>No students found in the selected class.</p>";
					}
				}
				?>
        </div>
    </div>
</div>


<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>