<?php

session_name('super_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');

session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);

session_start();

error_reporting(0);

include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];

include('includes/flash.php');



require_once 'vendor/autoload.php'; // PhpSpreadsheet Library



use PhpOffice\PhpSpreadsheet\IOFactory;



if (isset($_POST['upload'])) {

  $fileName = $_FILES['file']['name'];

  $fileTmpName = $_FILES['file']['tmp_name'];

  $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);



  // Validate file type

  if ($fileExtension != "xls" && $fileExtension != "xlsx") {

    flash_alert('Invalid file format. Please upload an Excel file.');

    exit();

  }



  // Load the spreadsheet

  $spreadsheet = IOFactory::load($fileTmpName);

  $worksheet = $spreadsheet->getActiveSheet();

  $rows = $worksheet->toArray();



  $skipped = 0;

  $inserted = 0;



  // Skip the header row

  $firstRowSkipped = false;

  foreach ($rows as $row) {

    if (!$firstRowSkipped) {

      $firstRowSkipped = true;

      continue;

    }



    // Extract values from Excel (Modify index if necessary)

    $studentno = trim($row[0]);

    $studentName = trim($row[1]);

    $class = trim($row[2]);

    $section = trim($row[3]);

    $stream = trim($row[4]);

    $age = trim($row[5]);

    $gender = trim($row[6]);

    $academic_session = trim($row[7]);

    $scholarship = trim($row[8]);

    $parentName = trim($row[9]);

    $relation = trim($row[10]);

    $occupation = trim($row[11]);

    $email = trim($row[12]);

    $contactno = trim($row[13]);

    $nextphone = trim($row[14]);

    $country = trim($row[15]);

    $district = trim($row[16]);

    $state = trim($row[17]);

    $village = trim($row[18]);



    // Convert Excel date format to YYYY-MM-DD

    if (is_numeric($age)) {

      $age = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($age)->format('Y-m-d');

    } else {

      $age = date('Y-m-d', strtotime($age));

    }



    // Default values

    $password = $studentno;

    $hashedPassword = password_hash($password, PASSWORD_BCRYPT);

    $studentImage = 'but.jpg';

    $spcase = 'No';



    // Check if student number already exists

    $checkQuery = "SELECT studentno FROM students WHERE studentno = '$studentno'";

    $checkResult = mysqli_query($con, $checkQuery);



    if (mysqli_num_rows($checkResult) > 0) {

      $skipped++;

      continue; // Skip existing student

    }



    // Insert into database

    $query = "INSERT INTO students (studentno, studentName, class, section, stream, age, gender, email, 

                  contactno, nextphone, country, district, state, village, studentImage, parentName, relation, 

                  occupation, academic_session, password, spcase, scholarship, adclass) 

                  VALUES ('$studentno', '$studentName', '$class', '$section', '$stream', '$age', '$gender', '$email', 

                  '$contactno', '$nextphone', '$country', '$district', '$state', '$village', '$studentImage', 

                  '$parentName', '$relation', '$occupation', '$academic_session', '$hashedPassword', '$spcase', 

                  '$scholarship', '$class')";



    $result = mysqli_query($con, $query);



    if ($result) {

      $inserted++;

    } else {

      flash_alert('Error inserting student: ' . mysqli_error($con));

    }

  }



  flash_alert('Upload complete. ' . $inserted . ' student(s) added. ' . $skipped . ' duplicate(s) skipped.');

  header('Location: add_student1.php'); exit;

} elseif (isset($_POST['submit'])) {

  // Collect form data

  $names = $_POST['names'];

  $age = $_POST['age'] ?? date('Y-m-d'); // Default to current date if not set

  $sex = $_POST['sex'];

  $class = $_POST['class'];

  $stream = $_POST['stream'];

  $parentname = $_POST['parentname'];

  $relation = $_POST['relation'];

  $occupation = $_POST['ocupation'];

  $email = $_POST['email'];

  $phone = $_POST['phone'];

  $nextphone = $_POST['nextphone'];

  $country = $_POST['country'];

  $district = $_POST['district'];

  $state = $_POST['state'];

  $village = $_POST['village'];

  $acsession = $_POST['session_id'];

  $term = $_POST['term_id'];

  $religion = $_POST['religion'];

  $studentno = $_POST['regno'];

  $medical_history = $_POST['medical_history'];

  $doctor_address = $_POST['doctor_address'];

  $doctor_phone = $_POST['doctor_phone'];

  $hospital_name = $_POST['hospital_name'];

  $hospital_phone = $_POST['hospital_phone'];

  $boarding_experience = $_POST['boarding_experience'];

  $ifyes = $_POST['ifyes'];

  $nationality = $_POST['nationality'];

  $work_address = $_POST['office_address'];

  $additional = $_POST['additional'] ?? ''; // Default to empty string if not set

  $state2 = $_POST['state2'] ?? ''; // Default to empty string if not set

  $hospital_address = $_POST['hospital_address'];





  $studentimage = 'but.jpg'; // default image



  // Convert arrays to comma-separated strings

  $physical_peculiarity = !empty($_POST['physical_peculiarity']) && is_array($_POST['physical_peculiarity'])

    ? implode(',', array_map([$con, 'real_escape_string'], $_POST['physical_peculiarity'])) : '';



  $language = !empty($_POST['language']) && is_array($_POST['language'])

    ? implode(',', array_map([$con, 'real_escape_string'], $_POST['language'])) : '';



  $password = '12345678';

  $hashedPassword = password_hash($password, PASSWORD_BCRYPT);

  $status = 4;



  // 🔍 Check for duplicate studentRegNo

  $checkQuery = "SELECT id FROM students WHERE studentRegNo = '$studentno' LIMIT 1";

  $checkResult = mysqli_query($con, $checkQuery);



  if ($checkResult && mysqli_num_rows($checkResult) > 0) {

    flash_alert('A student with this registration number already exists.');
        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;

    exit();

  }



  // ✅ Insert new student

  $insertQuery = "INSERT INTO students (

      studentRegNo, StudentName, class, stream, age, gender, email, parentName, relation, 

      occupation, country, district, state, village, contactno, nextphone, 

      academic_session, admission_term, password, status, physical_peculiarity, 

      medical_history, doctor_address, doctor_phone, religion, language, studentImage, 

      hospital_name, hospital_phone, boarding_experience, ifyes, nationality, work_address,

      additional_info, state2

    ) VALUES (

      '$studentno', '$names', '$class', '$stream', '$age', '$sex', '$email', '$parentname', '$relation', 

      '$occupation', '$country', '$district', '$state', '$village', '$phone', '$nextphone', 

      '$acsession', '$term', '$hashedPassword', '$status', '$physical_peculiarity', 

      '$medical_history', '$doctor_address', '$doctor_phone', '$religion', '$language', '$studentimage', 

      '$hospital_name', '$hospital_phone', '$boarding_experience', '$ifyes', '$nationality', '$work_address',

      '$additional', '$state2', '$hospital_address'

    )";



  $result = mysqli_query($con, $insertQuery);



  if ($result) {

    $student_id = mysqli_insert_id($con);



    // Insert school history

    if (!empty($_POST['school_name']) && is_array($_POST['school_name'])) {

      $stmtSchools = $con->prepare("INSERT INTO schools_attended (student_id, school_name, start_date, end_date) VALUES (?, ?, ?, ?)");



      $school_names = $_POST['school_name'] ?? ['Nill'];

      $start_dates = $_POST['school_start_date'] ?? [date('Y-m-d')];

      $end_dates = $_POST['school_end_date'] ?? [date('Y-m-d')];



      for ($i = 0; $i < count($school_names); $i++) {

        $schoolname = $con->real_escape_string(trim($school_names[$i]));

        $start_date = $con->real_escape_string(trim($start_dates[$i]));

        $end_date = $con->real_escape_string(trim($end_dates[$i]));



        $stmtSchools->bind_param("isss", $student_id, $schoolname, $start_date, $end_date);

        $stmtSchools->execute();

      }



      $stmtSchools->close();

    }



    flash_alert('Student registration successful.', 'add_student1.php');
        header('Location: add_student1.php'); exit;

  } else {

    flash_alert('Insertion failed: ' . mysqli_error($con));

  }

}

?>







<!DOCTYPE html>

<html>

<?php @include("includes/head.php"); ?>



<body class="hold-transition sidebar-mini layout-fixed">

  <div class="wrapper">

    <!-- Navbar -->

    <?php @include("includes/header2.php"); ?>

    <!-- /.navbar -->



    <!-- Main Sidebar Container -->

    <?php @include("includes/sidebar2.php"); ?>



    <!-- Content Wrapper. Contains page content -->

    <div class="content-wrapper">

      <!-- Content Header (Page header) -->

<section class="content-header premium-header">

    <div class="container-fluid">

        <div class="header-glass-card">

            <div class="row align-items-center">

                <div class="col-md-8">

                    <div class="title-section">

                        <div class="icon-box bg-primary-gradient shadow-sm">

                            <i class="fas fa-user-graduate"></i>

                        </div>

                        <div>

                            <h1 class="premium-title text-primary">

                                Student Information Management

                                <span class="premium-subtitle text-secondary">Manage Student</span>

                            </h1>
                            <div class="mt-1">
                              <?php if ($currentSessionName): ?>
                                <span class="badge badge-primary mr-1">
                                  <i class="fas fa-calendar-alt"></i>
                                  <?= htmlspecialchars($currentSessionName) ?>
                                </span>
                              <?php endif; ?>
                              <?php if ($currentTermName): ?>
                                <span class="badge badge-success">
                                  <i class="fas fa-bookmark"></i>
                                  <?= htmlspecialchars($currentTermName) ?>
                                </span>
                              <?php else: ?>
                                <span class="badge badge-warning">
                                  <i class="fas fa-exclamation-triangle"></i> No active term
                                </span>
                              <?php endif; ?>
                            </div>

                        </div>

                    </div>

                </div>

                <div class="col-md-4">

                    <nav aria-label="breadcrumb">

                        <ol class="breadcrumb premium-breadcrumb">

                            <li class="breadcrumb-item"><a href="dashboard1.php" class="text-primary">Home</a></li>

                            <li class="breadcrumb-item active" aria-current="page">New Student</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section>      







      <!-- Main content -->

      <section class="content">

        <div class="container-fluid">

          <div class="row ">

            <div class="col-md-12">

              <!-- general form elements -->

              <div class="card card-primary">

                <div class="card-header">

                  <h3 class="card-title font-weight-bold"> <i class="fas fa-user-plus"></i> Upload Existing Student Details (Admitted Students Only)</h3>

                </div>

                <!-- /.card-header -->

                <!-- form start -->

                <form role="form" method="POST" enctype="multipart/form-data">

                  <div class="card-body">

                    <div class="form-group col-md-12">

                      <label for="file">Upload Excel File</label>

                      <input type="file" class="form-control" name="file" accept=".xls, .xlsx" required>

                    </div>

                  </div>

                  <div class="card-footer">

                    <center><button type="submit" name="upload" class="btn btn-primary"><i class="fas fa-upload"></i> Upload</button></center>

                  </div>

                </form>







              </div>

              <!-- /.card -->

            </div>

            <!-- /.col -->

          </div>

          <!-- /.row -->

        </div>

        <!-- /.container-fluid -->

      </section>



      <!-- Manual adding of students -->

      <section class="content">

        <div class="container-fluid">

          <div class="row ">

            <div class="col-md-12">

              <!-- general form elements -->

              <div class="card card-primary">

                <div class="card-header">

                  <h5 class="card-title font-weight-bold"><i class="fas fa-user-plus"></i> Add New Students Using Registration Form</h5>

                </div>

                <!-- /.card-header -->

                <!-- form start -->

                <form role="form" method="POST" enctype="multipart/form-data">

                  <div class="card-body">

                    <span style="color: brown">

                      <h5><i class="fas fa-user"></i> Student Details</h5>

                    </span>

                    <hr>

                    <div class="row">

                      <div class="form-group col-md-4">

                        <label for="names">Student's Registration No.</label>

                        <input type="text" class="form-control" id="regno" name="regno" placeholder=" e.g. ACI/RN/0001" oninput="this.value = this.value.toUpperCase()" required>

                      </div>



                      <div class="form-group col-md-4">

                        <label for="names">Student's Fullname</label>

                        <input type="text" class="form-control" id="names" name="names" placeholder=" Surname  Firstname  Other name" required>

                      </div>

                      <div class="form-group col-md-4">

                        <label for="age">Date of Birth</label>

                        <input type="date" class="form-control" id="age" name="age" placeholder="age" required>

                      </div>

                      <div class="form-group col-md-4">

                        <label for="sex">Gender</label>

                        <select type="select" class="form-control" id="sex" name="sex" required>

                          <option></option>

                          <option value="Male">Male</option>

                          <option value="Female">Female</option>

                        </select>

                      </div>

                    </div>

                    <div class="row">

                      <div class="form-group col-md-4">

                        <label for="age">Class</label>

                        <select type="select" class="form-control" id="class" name="class" required>

                          <option value=""></option>

                          <option value="JSS 1">JSS 1</option>

                          <option value="JSS 2">JSS 2</option>

                          <option value="SS 1">SS 1</option>

                        </select>

                      </div>



                      <div class="form-group col-md-4">

                        <label for="age">School Type</label>

                        <select type="select" class="form-control" id="stream" name="stream" required>

                          <option value=""></option>

                          <option value="Boarding">Boarding</option>

                          <option value="Day">Day</option>

                        </select>

                      </div>

                      <div class="form-group col-md-4">

                        <label for="session_id">Academic Session to Resume</label>

                        <select name="session_id" id="session_id" class="form-control" required>

                          <option value="">-- Select Session --</option>



                          <?php

                          $sessionResult = $con->query("SELECT DISTINCT id, session_name FROM school_sessions ORDER BY session_name DESC");

                          while ($row = $sessionResult->fetch_assoc()) {

                            echo "<option value='{$row['session_name']}'>{$row['session_name']}</option>";

                          }

                          ?>

                        </select>

                      </div>

                      <div class="form-group col-md-4">

                        <label for="term_id">Term to Resume</label>

                        <select name="term_id" id="term_id" class="form-control" required>

                          <option value="">-- Select Term --</option>

                          <?php

                          $termResult = $con->query("SELECT DISTINCT term_name FROM school_terms ORDER BY term_name ASC");

                          while ($row1 = $termResult->fetch_assoc()) {

                            echo "<option value='{$row1['term_name']}'>{$row1['term_name']}</option>";

                          }

                          ?>

                        </select>

                      </div>

                      <div class="form-group col-md-4">

                        <!-- Physical Peculiarity Select Box -->

                        <label for="physical_peculiarity">Language (Add more if needed):</label>

                        <select id="language" name="language[]" multiple="multiple" class="form-control" required>

                          <option value="">-- Select Language --</option>

                          <option value="English">English</option>

                          <option value="Yoruba">Yoruba</option>

                          <option value="Hausa">Hausa</option>

                          <option value="Igbo">Igbo</option>

                          <option value="French">French</option>

                          <option value="Spanish">Spanish</option>

                          <option value="German">German</option>

                          <option value="none">None</option>

                        </select>

                      </div>

                      <div class="form-group col-md-4">

                        <!-- Physical Peculiarity Select Box -->

                        <label for="physical_peculiarity">Religion</label>

                        <select id="religion" name="religion" class="form-control" required>

                          <option value="">-- Select Religion --</option>

                          <option value="Christian">Christianity</option>

                          <option value="Islam">Islam</option>

                          <option value="Others">Others</option>

                          <option value="none">None</option>

                        </select>

                      </div>



                      <div class="form-group col-md-4">

                        <!-- Physical Peculiarity Select Box -->

                        <label for="physical_peculiarity">Physical Peculiarity (if any):</label>

                        <select id="physical_peculiarity" name="physical_peculiarity[]" multiple="multiple" class="form-control" required>

                          <option value="none">None</option>

                          <option value="birthmark">Birthmark</option>

                          <option value="scar">Scar</option>

                          <option value="mole">Mole</option>

                          <option value="missing_limb">Missing limb (arm/leg/finger)</option>

                          <option value="limping">Limping</option>

                          <option value="wheelchair">Uses wheelchair</option>

                          <option value="leg_brace">Uses leg brace</option>

                          <option value="scoliosis">Scoliosis</option>

                          <option value="bowed_legs">Bowed legs</option>

                          <option value="glasses">Wears glasses</option>

                          <option value="hearing_aid">Wears hearing aid</option>

                          <option value="cleft_lip">Cleft lip or palate</option>

                          <option value="speech_difficulty">Speech difficulty</option>

                          <option value="lazy_eye">Lazy eye</option>

                          <option value="albinism">Albinism</option>

                          <option value="vitiligo">Vitiligo</option>

                          <option value="alopecia">Hair loss (Alopecia)</option>

                          <option value="tics">Tics or involuntary movements</option>

                          <option value="tall_stature">Unusual height (Tall)</option>

                          <option value="short_stature">Unusual height (Short)</option>

                        </select>

                      </div>

                    </div>

                    <hr>

                    <span style="color: brown">

                      <h5><i class="fas fa-medkit"></i> Medical History</h5>

                    </span>

                    <hr>

                    <div class="row">

                      <!-- Medical History -->

                      <div class="form-group col-md-12">

                        <label for="medical_history">

                          <strong>Medical History:</strong> <br>

                          <small>Please give details of physical defects or incapacities, allergies, serious illness, bed wetting or other such matters the school should know about.</small>

                        </label>

                        <textarea class="form-control" id="medical_history" name="medical_history" rows="5" placeholder="Enter medical history details here..."></textarea>

                      </div>



                      <!-- Doctor Contact -->

                      <div class="form-group col-md-4">

                        <label for="doctor_address">Doctor's Name</label>

                        <input type="text" class="form-control" id="doctor_address" name="doctor_address" placeholder="Enter name of medical doctor">

                      </div>

                      <div class="form-group col-md-4">

                        <label for="doctor_phone">Doctor's Phone Number</label>

                        <input type="text" class="form-control" id="doctor_phone" name="doctor_phone" placeholder="Enter doctor's phone number">

                      </div>

                      <div class="form-group col-md-4">

                        <label for="doctor_phone">Hospital Name</label>

                        <input type="text" class="form-control" id="hospital_name" name="hospital_name" placeholder="Enter hospital name">

                      </div>

                      <div class="form-group col-md-4">

                        <label for="doctor_phone">Hospital Phone Number</label>

                        <input type="text" class="form-control" id="hospital_phone" name="hospital_phone" placeholder="Enter hospital phone number">

                      </div>

                      <div class="form-group col-md-8">

                        <label for="doctor_phone">Hospital Address</label>

                        <input type="text" class="form-control" id="hospital_address" name="hospital_address" placeholder="Enter hospital address">

                      </div>

                    </div>

                    <hr>

                    <span style="color: brown">

                      <h5><i class="fas fa-school"></i> Previous Schools Attended with Date (Add more if needed)</h5>

                    </span>

                    <hr>

                    <div class="row">

                      <div class="form-group col-md-12">

                        <div id="schools-attended-section">

                          <div class="row school-entry mb-2">

                            <div class="form-group col-md-4">

                              <label>School Name</label>

                              <input type="text" name="school_name[]" class="form-control" placeholder="School Name" required>

                            </div>

                            <div class="form-group col-md-3">

                              <label>Start Date</label>

                              <input type="date" name="school_start_date[]" class="form-control" placeholder="Start Date" required>

                            </div>

                            <div class="form-group col-md-3">

                              <label>End Date</label>

                              <input type="date" name="school_end_date[]" class="form-control" placeholder="End Date" required>

                            </div>

                            <div class="col-md-2">

                              <label>Action</label>

                              <br>

                              <button type="button" class="btn btn-danger" onclick="removeSchool(this)"><i class="fas fa-trash"></i> Remove</button>

                            </div>

                          </div>

                        </div>

                        <button type="button" class="btn btn-primary mt-2" onclick="addSchool()"><i class="fas fa-plus"></i> Add Another School</button>

                      </div>

                    </div>



                    <hr>

                    <span style="color: brown">

                      <h5><i class="fas fa-user-shield"></i> Guardian's Details</h5>

                    </span>

                    <hr>

                    <div class="row">

                      <div class="form-group col-md-4">

                        <label for="parentname">Guardian's Name</label>

                        <input type="text" class="form-control" id="parentname" name="parentname" placeholder="Enter Name" required>

                      </div>

                      <div class="form-group col-md-4">

                        <label for="relation">Relationship</label>

                        <select type="select" class="form-control" id="relation" name="relation" required>

                          <option></option>

                          <option value="Father">Father</option>

                          <option value="Mother">Mother</option>

                          <option value="Father">Uncle</option>

                          <option value="Mother">Aunt</option>

                          <option value="Mother">Grand Parent</option>

                          <option value="Sibling">Sibling</option>

                          <option value="Others">Others</option>

                        </select>

                      </div>

                      <div class="form-group col-md-4">

                        <label for="age">Email</label>

                        <input type="text" class="form-control" name="email" id="email" required>

                      </div>



                    </div>

                    <div class="row">

                      <div class="form-group col-md-4">

                        <label for="sex">Occupation</label>

                        <select type="select" class="form-control" id="ocupation" name="ocupation" required>

                          <option></option>

                          <option value="Civil Servant">Civil Servant</option>

                          <option value="Private Sector Employee">Private Sector Employee</option>

                          <option value="Self Employed">Self Employed</option>

                          <option value="Retired">Retired</option>

                          <option value="Business Owner">Business Owner</option>

                          <option value="Professional">Professional</option>

                          <option value="Others">Others</option>

                        </select>

                      </div>

                      <div class="form-group col-md-4">

                        <label for="phone1">Mobile Phone No.</label>

                        <input type="text" class="form-control" id="phone" name="phone" placeholder="Mobile Phone No." required>

                      </div>

                      <div class="form-group col-md-4">

                        <label for="nextphone">Work/Office Phone No.</label>

                        <input type="text" class="form-control" id="nextphone" name="nextphone" placeholder="Work/Office Phone No.">

                      </div>

                      <div class="form-group col-md-12">

                        <label for="office_address">Guardian's Address</label>

                        <input type="text" class="form-control" id="office_address" name="office_address" placeholder="Guardian's Address">

                      </div>

                    </div>

                    <hr>

                    <span style="color: brown">

                      <h5><i class="fas fa-home"></i> Address</h5>

                    </span>

                    <hr>

                    <div class="row">

                      <div class="form-group col-md-6">

                        <label for="nationality">Nationality</label>

                        <select id="nationality" class="form-control" name="nationality" required>

                          <option value="">-- Select Nationality --</option>

                          <option value="Nigerian">Nigerian</option>

                          <option value="Non-Nigerian">Non-Nigerian</option>

                        </select>

                      </div>

                      <div class="form-group col-md-6 ">

                        <label for="home_address">Home Address</label>

                        <input type="text" class="form-control" name="country" required placeholder="Home Address">

                      </div>



                      <div class="form-group col-md-6 ">

                        <label for="city">City</label>

                        <input type="text" class="form-control" name="district" placeholder="City">

                      </div>

                      <div class="form-group col-md-6 ">

                        <label for="city">State</label>

                        <input type="text" class="form-control" name="state2" placeholder="State">

                      </div>



                      <div class="form-group col-md-6">

                        <label for="state">State of Origin</label>

                        <select id="state" class="form-control" name="state" required>

                          <option value="">-- Select State --</option>

                        </select>

                      </div>



                      <div class="form-group col-md-6 ">

                        <label for="village">Local Government (LGA) of Origin</label>

                        <select id="village" class="form-control" name="village" required>

                          <option value="">-- Select state first --</option>

                        </select>

                      </div>

                    </div>



                    <hr>

                    <span style="color: brown">

                      <h5><i class="fas fa-bed"></i> Boarding Student Only</h5>

                    </span>

                    <hr>

                    <div class="row">

                      <div class="form-group col-md-6">

                        <label for="boarding_experience">Have you had any boarding experience before?</label>

                        <select type="select" class="form-control" id="boarding_experience" name="boarding_experience">

                          <option></option>

                          <option value="Yes">Yes</option>

                          <option value="No">No</option>

                        </select>

                      </div>

                      <div class="form-group col-md-6">

                        <label for="ifyes">If Yes, please specify how long?</label>

                        <input type="text" class="form-control" id="ifyes" name="ifyes" placeholder="Enter Details">

                      </div>

                      <div class="form-group col-md-12">

                        <label for="additional">Additional Information the school should know (optional):</label>

                        <input type="text" class="form-control" id="additional" name="additional" placeholder="Enter Details">

                      </div>

                    </div>





                  </div>

                  <!-- /.card-body -->

                  <div class="card-footer">

                    <center><button type="submit" name="submit" class="btn btn-primary"><i class="fas fa-check-circle"></i> Submit Registration Form</button></center>

                  </div>

                </form>

              </div>

              <!-- /.card -->

            </div>

            <!-- /.col -->

          </div>

          <!-- /.row -->

        </div>

        <!-- /.container-fluid -->

      </section>

      <!-- /.content -->

    </div>

    <!-- /.content-wrapper -->

    <?php @include("includes/footer.php"); ?>



  </div>



  <!-- ./wrapper -->

  <?php @include("includes/foot.php"); ?>



  <script src="dist/js/select2.min.js"></script>





  <script>

    $(document).ready(function() {

      const preselectedState = "<?php echo addslashes($row->state ?? ''); ?>";

      const preselectedLga = "<?php echo addslashes($row->village ?? ''); ?>";



      // Initialize Select2

      $('#class, #stream, #relation, #ocupation, #sc, #sex, #classarm, #session_id, #term_id, #physical_peculiarity, #religion, #language, #boarding_experience, #nationality, #state, #village').select2();



      // Load states

      $.getJSON('get_states.php', function(states) {

        let stateOptions = `<option value="">-- Select State --</option>`;

        $.each(states, function(i, state) {

          const selected = (state.name === preselectedState) ? 'selected' : '';

          stateOptions += `<option value="${state.name}" ${selected}>${state.name}</option>`;

        });

        $('#state').html(stateOptions).trigger('change'); // Trigger change to load LGAs

      });



      // When state changes, load LGAs

      $('#state').on('change', function() {

        const selectedState = $(this).val();

        if (!selectedState) {

          $('#village').html('<option value="">-- Loading........ --</option>').trigger('change');

          return;

        }



        $.getJSON(`get_local_governments.php?state_id=${encodeURIComponent(selectedState)}`, function(lgas) {

          let lgaOptions = `<option value="">-- Select LGA --</option>`;

          $.each(lgas, function(i, lga) {

            const selected = (lga.name === preselectedLga) ? 'selected' : '';

            lgaOptions += `<option value="${lga.name}" ${selected}>${lga.name}</option>`;

          });

          $('#village').html(lgaOptions).trigger('change'); // Must trigger change

        });

      });

    });

  </script>



  <script>

    function validateAndPreviewImage(event) {

      const file = event.target.files[0];

      const errorDisplay = document.getElementById('stdimageError');

      const preview = document.getElementById('stdimagePreview');



      // Reset messages and preview

      errorDisplay.style.display = 'none';

      preview.style.display = 'none';



      if (!file) return;



      // Check file type

      const validTypes = ['image/jpeg', 'image/png', 'image/jpg'];

      if (!validTypes.includes(file.type)) {

        errorDisplay.textContent = "Only JPG or PNG image files are allowed.";

        errorDisplay.style.display = 'block';

        event.target.value = ''; // Clear input

        return;

      }



      // Check file size (max 5MB)

      const maxSize = 5 * 1024 * 1024;

      if (file.size > maxSize) {

        errorDisplay.textContent = "File size must not exceed 5MB.";

        errorDisplay.style.display = 'block';

        event.target.value = ''; // Clear input

        return;

      }



      // Preview the image

      const reader = new FileReader();

      reader.onload = function(e) {

        preview.src = e.target.result;

        preview.style.display = 'block';

      };

      reader.readAsDataURL(file);

    }

  </script>

  <script>

    function addSchool() {

      const container = document.getElementById('schools-attended-section');

      const entry = container.querySelector('.school-entry');

      const clone = entry.cloneNode(true);

      clone.querySelectorAll('input').forEach(input => input.value = '');

      container.appendChild(clone);

    }



    function removeSchool(button) {

      const section = document.getElementById('schools-attended-section');

      if (section.children.length > 1) {

        button.closest('.school-entry').remove();

      }

    }

  </script>

</body>



</html>