<div class='page-title'>
    <div>
        <h1><i class='icon-graduation icons'></i> Student Management</h1>
        <p>Add and View Students/Pupils</p>
    </div>
</div>

<div class="card">
    <div class="row">
        <div class="col-12">
            <div class="panel panel-primary ch">
                <div class="panel-body">

                    <div class="mb-3 text-right">
                        <button class="btn btn-sm btn-success" data-toggle="modal" data-target="#studentRegModal">➕ Register Student</button>
                    </div>             

                    <form method="POST" action="">
                        <div class="row align-items-end">
                            <div class="col-md-4">
                                <div class="input-group">
                                    <span class="input-group-addon">CLASS</span>
                                    <select name="reg_no_class" class="form-control" required>
                                        <option value="">Select Class</option>
                                        <?php
                                        $query = "SELECT * FROM `classes`";
                                        $run_query = mysqli_query($connection, $query);
                                        while ($result = mysqli_fetch_assoc($run_query)) {
                                            $class_option = htmlspecialchars($result['classes']);
                                            echo "<option value='{$class_option}'>{$class_option}</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <button type="submit" name="get_reg_no_btn" class="btn btn-primary btn-md">VIEW</button>
                            </div>
                        </div>
                    </form>

                    <br />

<?php
if (isset($_POST['get_reg_no_btn'])) {
    $reg_no_class = inject_checker($connection, $_POST['reg_no_class']);

    if (empty($reg_no_class)) {
    	    $_SESSION['msg'] = "Please select a class.";
		    $_SESSION['type'] = "warning"; 
    } else {
        $stmt = $connection->prepare("
    SELECT * 
    FROM students 
    WHERE class = ? 
      AND status = 'active' 
    ORDER BY firstname ASC
");
$stmt->bind_param("s", $reg_no_class);
$stmt->execute();
$result = $stmt->get_result();

        if ($result->num_rows > 0) {
            echo "<div class='table-responsive'>
            		<table class='table table-hover table-sm table-bordered ' id = 'myTable'>
            			<thead>
		        			<tr>
		        				<th>S/N</th>
		        				<th>IMAGE</th>
		        				<th>NAME</th>
		        				<th>SEX</th>
		        				<th>CLASS</th>
		        				<th>ADM NUMBER</th>
		        				<th>ACTION</th>
		        			</tr>
		       			</thead>
		    			<tbody>";
            $i = 0;
            while ($row = $result->fetch_assoc()) {
                $i++;
                $edit_student_id = $row['id'];
                $firstname = htmlspecialchars($row['firstname']);
                $lastname = htmlspecialchars($row['lastname']);
                $othername = htmlspecialchars($row['othername']);
                $fullname = ucwords("$firstname $othername $lastname");
                $sex = ucfirst($row['gender']);
                $height = htmlspecialchars($row['height']);
                $weight = htmlspecialchars($row['weight']);
                $club = htmlspecialchars($row['club']);
                $class = htmlspecialchars($row['class']);
                $level = htmlspecialchars($row['level']);
                $reg_number = htmlspecialchars($row['reg_number']);
                $health_conditions = htmlspecialchars($row['health_conditions']);
                $nationality = htmlspecialchars($row['nationality']);                
                $passport = !empty($row['passport']) ? "../" . $row['passport'] : "../uploads/students/none.jpg";
                $dob = htmlspecialchars($row['dob']);
                $state = htmlspecialchars($row['state']);
                $lga = htmlspecialchars($row['lga']);
                $address = htmlspecialchars($row['address']);
                $guardian_name = htmlspecialchars($row['guardian_name']);
                $guardian_occupation = htmlspecialchars($row['guardian_occupation']);
                $guardian_phone = htmlspecialchars($row['guardian_phone']);

                echo "<tr>
    <td>{$i}</td>
    <td class='text-center'><img src='{$passport}' alt='Passport' width='40' height='40' class='img-thumbnail'></td>
    <td>{$fullname}</td>
    <td class='text-center'>{$sex}</td>
    <td class='text-center'>{$class}</td>
    <td class='text-center'>{$reg_number}</td>
<td class='text-center'>
    <form method='POST' style='display:inline-block;'>
        <input type='hidden' name='student_hidden_id' value='{$edit_student_id}'>

        <div class='btn-group btn-group-sm' role='group'>
        	<!-- View Button triggers modal -->
            <button type='button' class='btn btn-secondary' title='View Student'
                data-toggle='modal' data-target='#viewStudentModal{$edit_student_id}'>
                <i class='fa fa-eye'></i>
            </button>
            <!-- View Student Modal -->
<div class='modal fade' id='viewStudentModal{$edit_student_id}' tabindex='-1' role='dialog' aria-labelledby='viewStudentModalLabel{$edit_student_id}' aria-hidden='true'>
  <div class='modal-dialog modal-lg' role='document'>
    <div class='modal-content'>
      <div class='modal-header'>
        <h2 class='modal-title'>Student Details - {$fullname}</h2>
        <button type='button' class='close' data-dismiss='modal' aria-label='Close'>
          <span aria-hidden='true'>&times;</span>
        </button>
      </div>

      <div class='modal-body'>
        <div class='row'>
          <!-- Passport Section -->
          <div class='col-md-4 text-center mb-3'>
            <img src='{$passport}' class='img-thumbnail' alt='Passport' style='width: 150px; height: 150px;'>
          </div>

          <!-- Details Section -->
          <div class='col-md-8'>
            <table class='table table-bordered table-sm'>
              <tr>
                <th>Full Name</th>
                <td>{$fullname}</td>
              </tr>
              <tr>
                <th>Reg Number</th>
                <td>{$reg_number}</td>
              </tr>
              <tr>
                <th>Class</th>
                <td>{$class}</td>
              </tr>
              <tr>
                <th>Level</th>
                <td>{$level}</td>
              </tr>
              <tr>
                <th>Gender</th>
                <td>{$sex}</td>
              </tr>
              <tr>
                <th>Date of Birth</th>
                <td>{$dob}</td>
              </tr>
              <tr>
                <th>Height</th>
                <td>{$height}ft</td>
              </tr>
              <tr>
                <th>Weight</th>
                <td>{$weight}kg</td>
              </tr>
              <tr>
                <th>Health Conditions</th>
                <td>{$health_conditions}</td>
              </tr>
              <tr>
                <th>LGA</th>
                <td>{$lga}</td>
              </tr>
              <tr>
                <th>State</th>
                <td>{$state}</td>
              </tr>
              <tr>
                <th>Nationality</th>
                <td>{$nationality}</td>
              </tr>
              <tr>
                <th>Address</th>
                <td>{$address}</td>
              </tr>
              <tr>
                <th>Club</th>
                <td>{$club}</td>
              </tr>              
              <tr>
                <th>Guardian Name</th>
                <td>{$guardian_name}</td>
              </tr>
              <tr>
                <th>Guardian Occupation</th>
                <td>{$guardian_occupation}</td>
              </tr>
              <tr>
                <th>Guardian Phone</th>
                <td>{$guardian_phone}</td>
              </tr>
            </table>
          </div>
        </div>
      </div>

      <div class='modal-footer'>
        <button type='button' class='btn btn-secondary' data-dismiss='modal'>Close</button>
      </div>
    </div>
  </div>
</div>

     <a href='slip.php?id=$edit_student_id' class='btn btn-info' title='Print Slip' target='_blank'>
    <i class='fa fa-print'></i>
</a>

            <button type='submit' name='student_delete_btn' class='btn btn-danger' title='Delete Student'>
                <i class='fa fa-trash'></i>
            </button>
            <button type='button' class='btn btn-primary' data-toggle='modal' data-target='#editStudentModal{$edit_student_id}' title='Edit Student'>
                <i class='fa fa-edit'></i>
            </button>
        </div>
    </form>
</td>

</tr>";


                // Modal for Editing Student
                echo "
<div class='modal fade' id='editStudentModal{$edit_student_id}' tabindex='-1' role='dialog'>
  <div class='modal-dialog modal-xl'>
    <div class='modal-content'>
      <form method='POST' enctype='multipart/form-data'>
        <div class='modal-header bg-primary text-white'>
          <h5 class='modal-title'>Edit Student - {$fullname}</h5>
          <button type='button' class='close text-white' data-dismiss='modal'>&times;</button>
        </div>
        <div class='modal-body'>
          <input type='hidden' name='edit_student_id' value='{$edit_student_id}'>

          <div class='form-group text-center'>
            <label>Current Passport</label><br>
            <img id='preview{$edit_student_id}' src='{$passport}' width='150' height='150' class='img-thumbnail mb-2'>
            <input type='file' name='edit_student_passport' class='form-control-file' onchange=\"previewImage(event, 'preview{$edit_student_id}')\">
          </div>
		<div class='form-group'>
            <label>Class</label>
            <select name='edit_student_class' class='form-control' required>";
                $class_query = mysqli_query($connection, "SELECT * FROM classes");
                while ($c = mysqli_fetch_assoc($class_query)) {
                    $selected = $class === $c['classes'] ? 'selected' : '';
                    echo "<option value='{$c['classes']}' {$selected}>{$c['classes']}</option>";
                }
          echo "</select>
          </div>
          <div class='form-group'>
            <label>Level</label>
            <select name='edit_student_class_level' class='form-control' required>";
                $level_query = mysqli_query($connection, "SELECT * FROM class_level");
                while ($cl = mysqli_fetch_assoc($level_query)) {
                    $selected = $level === $cl['level'] ? 'selected' : '';
                    echo "<option value='{$cl['level']}' {$selected}>{$cl['level']}</option>";
                }
          echo "</select>
          </div>          
          <div class='form-group'><label>First Name</label><input type='text' name='edit_student_firstname' value='{$firstname}' class='form-control' required></div>
          <div class='form-group'><label>Middle Name</label><input type='text' name='edit_student_othername' value='{$othername}' class='form-control'></div>
          <div class='form-group'><label>Last Name</label><input type='text' name='edit_student_lastname' value='{$lastname}' class='form-control' required></div>
          <div class='form-group'><label>Date of Birth</label><input type='text' name='edit_student_dob' value='{$dob}' class='form-control datepicker'></div>		
          <div class='form-group'>
            <label>Gender</label>
            <select name='edit_student_gender' class='form-control'>
              <option value='Male' " . ($sex === 'Male' ? 'selected' : '') . ">Male</option>
              <option value='Female' " . ($sex === 'Female' ? 'selected' : '') . ">Female</option>
            </select>
          </div>
		<div class='form-group'><label>Height</label><input type='text' name='edit_height' value='{$height}' class='form-control '></div>
		<div class='form-group'><label>Weight</label><input type='text' name='edit_weight' value='{$weight}' class='form-control '></div>
		<div class='form-group'><label>Health Conditions</label><input type='text' name='edit_health_conditions' value='{$health_conditions}' class='form-control '></div>
		<div class='form-group'><label>Club</label><input type='text' name='edit_club' value='{$club}' class='form-control '></div>
		<div class='form-group'><label>Country</label><input type='text' name='edit_student_nationality' value='{$nationality}' class='form-control '></div>
          <div class='form-group'>
            <label>State</label>
            <select name='edit_student_state' id='state{$edit_student_id}' class='form-control' onchange='toggleLGA(this, {$edit_student_id});' required>
              <option selected>" . htmlspecialchars($state) . "</option>";
                $states = ["Abia", "Adamawa", "AkwaIbom", "Anambra", "Bauchi", "Bayelsa", "Benue", "Borno",
                  "Cross River", "Delta", "Ebonyi", "Edo", "Ekiti", "Enugu", "FCT", "Gombe", "Imo",
                  "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi", "Kwara", "Lagos", "Nasarawa",
                  "Niger", "Ogun", "Ondo", "Osun", "Oyo", "Plateau", "Rivers", "Sokoto", "Taraba",
                  "Yobe", "Zamfara"];
                foreach ($states as $st) {
                    $selected = ($state === $st) ? "selected" : "";
                    echo "<option value='{$st}' {$selected}>{$st}</option>";
                }
          echo "</select>
          </div>

          <div class='form-group'>
            <label>LGA</label>
            <select name='edit_student_lga' id='lga{$edit_student_id}' class='form-control select-lga' required>
              <option selected>" . htmlspecialchars($lga) . "</option>
              <!-- Populate dynamically via JS -->
            </select>
          </div>

          <div class='form-group'><label>Address</label><input type='text' name='edit_student_address' value='{$address}' class='form-control'></div>
          <div class='form-group'><label>Guardian Name</label><input type='text' name='edit_guardian_name' value='{$guardian_name}' class='form-control'></div>
          <div class='form-group'><label>Guardian Occupation</label><input type='text' name='edit_guardian_occupation' value='{$guardian_occupation}' class='form-control'></div>
          <div class='form-group'><label>Guardian Phone</label><input type='text' name='edit_guardian_phone' value='{$guardian_phone}' class='form-control'></div>
        </div>

        <div class='modal-footer'>
          <button type='submit' name='student_edit_btn' class='btn btn-success'>Save Changes</button>
          <button type='button' class='btn btn-secondary' data-dismiss='modal'>Cancel</button>
        </div>
      </form>
    </div>
  </div>
</div>";
            }

            echo "</tbody></table></div>";
        } else {
		    $_SESSION['msg'] = "No student found in {$reg_no_class}.";
		    $_SESSION['type'] = "warning";          
        }

        $stmt->close();
    }
}
?>


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

<!-- Modal -->
<div class="modal fade" id="studentRegModal" tabindex="-1" role="dialog" aria-labelledby="studentRegModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable modal-xl" role="document">
        <div class="modal-content">
            <form action="" method="POST" enctype="multipart/form-data">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="studentRegModalLabel">Student Online Registration</h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>

                <div class="modal-body">
                    <!-- Profile Upload -->
                    <div class='form-group text-center'>
                        <label for='uploadImage'><b>Student Upload Image</b></label><br>
                        <img id='preview' src='../uploads/students/none.jpg' class='img-thumbnail rounded-circle mb-2' width='150' height='150' alt='Profile Preview'>
                        <input type='file' name='file' id='uploadImage' class='form-control-file d-block mx-auto' onchange="previewImage(event, preview)" required>
                    </div>

                    <!-- Registration Table -->
                    <div class="table-responsive">
                        <table class='table table-striped'>

                            <!-- CLASS -->
                            <tr>
                                <td><b>Class</b></td>
                                <td>
                                    <select name='reg_student_tc' class='form-control' required>
                                        <option>Select Class</option>
                                        <?php
                                        $query = "SELECT * FROM `classes`";
                                        $run_query = mysqli_query($connection, $query);
                                        while ($result = mysqli_fetch_assoc($run_query)) {
                                            echo "<option>{$result['classes']}</option>";
                                        }
                                        ?>
                                    </select>
                                </td>
                            </tr>
                             <!-- Role -->
                            <tr>
                                <td><b>Role</b></td>
                                <td>
                                    <select name="role" class="form-control" required>
										<option value="">-- Select Role --</option>
										<?php
										$role_query = mysqli_query($connection, "SELECT id, role_name FROM role WHERE role_name = 'student'");
										while ($role = mysqli_fetch_assoc($role_query)) {
											echo "<option value='{$role['id']}' selected>" . htmlspecialchars($role['role_name']) . "</option>";
										}
										?>
									</select>
                                </td>
                            </tr>
                            <tr>
                                <td><b>Level</b></td>
                                <td>
                                    <select class="form-control" name="class_level" required>
												<option value="">--Select Level--</option>
												<?php
												$level_query = 'SELECT * FROM `class_level`';
												$run_level_query = mysqli_query($connection, $level_query);
												if (mysqli_num_rows($run_level_query) > 0) {
													while ($level_result = mysqli_fetch_assoc($run_level_query)) {
														$level = $level_result['level'];
														$selected = (isset($all_level) && $level == $all_level) ? 'selected' : '';
														echo "<option value='" . htmlspecialchars($level ?? '') . "' $selected>" . htmlspecialchars($level ?? '') . "</option>";
													}
												}
												?>
											</select>
                                </td>
                            </tr>

                            <tr><td><b>Admission Number</b></td><td><input type='text' name='reg_number' class='form-control' value='<?= $school_initial ?>' required></td></tr>
                            <tr><td><b>First Name</b></td><td><input type='text' name='reg_student_firstname' class='form-control' required></td></tr>
                            <tr><td><b>Middle Name</b></td><td><input type='text' name='reg_student_othername' class='form-control'></td></tr>
                            <tr><td><b>Last Name</b></td><td><input type='text' name='reg_student_lastname' class='form-control' required></td></tr>
                            <tr><td><b>Gender</b></td><td>
                                <select name='reg_student_gender' class='form-control' required>
                                	<option value="">-- Select Gender --</option>
                                    <option>Male</option>
                                    <option>Female</option>
                                </select></td>
                            </tr>
                            <tr><td><b>Height</b></td><td><input type='text' name='height' class='form-control' required></td></tr>
                            <tr><td><b>Weight</b></td><td><input type='text' name='weight' class='form-control' required></td></tr>
                            <tr><td><b>Date of Birth</b></td><td><input type='text' name='reg_student_dob' class='form-control datepicker' required></td></tr>
                            <tr><td><b>Health Conditions</b></td><td><input type='text' name='health_conditions' class='form-control' required></td></tr>
                            <tr><td><b>Club</b></td><td><input type='text' name='club' class='form-control' required></td></tr>

                            <!-- Nationality -->
                            <tr>
                                <td><b>Nationality</b></td>
                                <td>
                                    <select name='reg_student_nationality' class='form-control'>
                                        <option>Country</option>
                                        <?php foreach (["Nigerian", "Ghananian"] as $country) echo "<option>$country</option>"; ?>
                                    </select>
                                </td>
                            </tr>

                            <!-- State -->
                            <tr>
                                <td><b>State</b></td>
                                <td>
                                    <select name="reg_student_state" id="state" class="form-control" onchange="toggleLGA(this);">
                                        <option value="">- Select -</option>
                                        <?php
                                        $states = ["Abia", "Adamawa", "AkwaIbom", "Anambra", "Bauchi", "Bayelsa", "Benue", "Borno", "Cross River", "Delta", "Ebonyi", "Edo", "Ekiti", "Enugu", "FCT", "Gombe", "Imo", "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi", "Kwara", "Lagos", "Nasarawa", "Niger", "Ogun", "Ondo", "Osun", "Oyo", "Plateau", "Rivers", "Sokoto", "Taraba", "Yobe", "Zamfara"];
                                        foreach ($states as $state) echo "<option value='$state'>$state</option>";
                                        ?>
                                    </select>
                                </td>
                            </tr>

                            <!-- LGA -->
                            <tr>
                                <td><b>LGA</b></td>
                                <td><select name="reg_student_lga" id="lga" class="form-control select-lga" required></select></td>
                            </tr>

                            <tr><td><b>Student Address</b></td><td><input type='text' name='reg_student_address' class='form-control' required></td></tr>

                            <!-- Guardian -->
                            <tr>
                                <td><b>Guardian's Details</b></td>
                                <td>
                                    <div class='form-row'>
                                        <div class='col'><input type='text' name='guardian_name' class='form-control' placeholder='Guardian Name'></div>
                                        <div class='col'><input type='text' name='guardian_occupation' class='form-control' placeholder='Occupation'></div>
                                        <div class='col'><input type='text' name='guardian_phone' pattern='[0-9]+' class='form-control' placeholder='Phone Number'></div>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

                <!-- Modal Footer -->
                <div class="modal-footer">
                    <button type="submit" name="student_reg_btn" class="btn btn-success">Submit Registration</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

