<?php
session_start();
error_reporting();
include('includes/dbconnection.php');
include('includes/flash.php');

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

require_once 'vendor/autoload.php'; // Load Composer dependencies
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Mpdf\Mpdf;
use Dotenv\Dotenv;

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();


$showForm = false;
$prefillData = [];

// If form is submitted with token
if (isset($_POST['check_token'])) {
  $token = strtoupper(trim($_POST['token']));
  $stmt = $con->prepare("SELECT * FROM registration_tokens WHERE token = ? AND token_status = 'pending'");
  $stmt->bind_param("s", $token);
  $stmt->execute();
  $result = $stmt->get_result();

  if ($result->num_rows > 0) {
    $showForm = true;
    $prefillData = $result->fetch_assoc(); // contains name, class, term, session etc.
  } else {
    $tokenError = "Invalid or used token. Please try again.";
  }
}


$school_name = $_ENV['SCHOOL_NAME'];
$school_address = $_ENV['SCHOOL_ADDRESS'];
$prefix = $_ENV['registration_prefix'];
$url = $_ENV['BASE_URL'];
$admin_email = $_ENV['ADMIN_EMAIL'];
$School_phone = $_ENV['SCHOOL_PHONE'];
$logo = $_ENV['WEBSITE_LOGO'];
$admission_email = $_ENV['ADMISSION_EMAIL'];

// Fetch future exam dates from the database
$today = date('Y-m-d');
$title = strtoupper("Entrance Examination");
$examDatesQuery = "SELECT event_date FROM events WHERE title = '$title' AND event_date >= '$today' ORDER BY event_date ASC";
$examDatesResult = mysqli_query($con, $examDatesQuery);



if (isset($_POST['submit'])) {
  // Collect form data
  $names = $_POST['names'];
  $age = isset($_POST['age']) && !empty(trim($_POST['age'])) ? trim($_POST['age']) : date('Y-m-d');
  $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'];
  $status = 4;
  $religion = $_POST['religion'];
  $hospital_name = $_POST['hospital_name'];
  $hospital_phone = $_POST['hospital_phone'];
  $boarding_experience = $_POST['boarding_experience'] ?? 'No'; // Default to 'No' if not set
  $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
  $token = strtoupper(trim($_POST['token']));
  $hospital_address = $_POST['hospital_address'];

  // Physical peculiarity array -> convert to comma separated string
  // Convert physical peculiarity array to comma-separated string
  $physical_peculiarity = '';
  if (!empty($_POST['physical_peculiarity']) && is_array($_POST['physical_peculiarity'])) {
    $physical_peculiarity = implode(',', array_map(function ($item) use ($con) {
      return $con->real_escape_string($item);
    }, $_POST['physical_peculiarity']));
  }

  // Convert language array to comma-separated string
  $language = '';
  if (!empty($_POST['language']) && is_array($_POST['language'])) {
    $language = implode(',', array_map(function ($item) use ($con) {
      return $con->real_escape_string($item);
    }, $_POST['language']));
  }

  // Handle student image upload
  $studentimage = 'but.jpg'; // Default image if no upload
  if (isset($_FILES['stdimage']) && $_FILES['stdimage']['error'] === UPLOAD_ERR_OK) {
    $originalName = $_FILES['stdimage']['name'];
    $tmpName = $_FILES['stdimage']['tmp_name']; // fixed here
    $uploadDir = "studentimages/";

    // Ensure the directory exists
    if (!is_dir($uploadDir)) {
      mkdir($uploadDir, 0755, true);
    }

    // Create a unique filename
    $newFileName = time() . "_" . basename($originalName);
    $destination = $uploadDir . $newFileName;

    if (move_uploaded_file($tmpName, $destination)) {
      $studentimage = $newFileName;
    } else {
      $studentimage = 'but.jpg'; // Log or handle error
    }
  }

  $medical_history = $con->real_escape_string(trim($_POST['medical_history']));
  $doctor_address = $con->real_escape_string(trim($_POST['doctor_address']));
  $doctor_phone = $con->real_escape_string(trim($_POST['doctor_phone']));

  // Fetch the student row created by entrancepay.php using the FormNo stored in the token
  $tokenRow = null;
  $stmtToken = $con->prepare("SELECT * FROM registration_tokens WHERE token = ? AND token_status = 'pending'");
  $stmtToken->bind_param("s", $token);
  $stmtToken->execute();
  $tokenRow = $stmtToken->get_result()->fetch_assoc();
  $stmtToken->close();

  $formNo = $tokenRow['studentno'] ?? '';

  // Look up the existing student row directly via student_id stored in the token
  $student_id = (int)($tokenRow['student_id'] ?? 0);

  if (!$student_id) {
    flash_alert('Error: Student record not found. Please contact the admissions office.');
    header('Location: registration.php');
    exit;
  }

  // Lock tables for the update + schools insert
  mysqli_query($con, "LOCK TABLES students WRITE, schools_attended WRITE, registration_tokens WRITE");

  // Update the existing student record (no INSERT, no reg number generation here)
  $query = "UPDATE students SET
    StudentName = '$names',
    class = '$class',
    stream = '$stream',
    age = '$age',
    gender = '$sex',
    email = '$email',
    parentName = '$parentname',
    relation = '$relation',
    occupation = '$occupation',
    country = '$country',
    district = '$district',
    state = '$state',
    village = '$village',
    contactno = '$phone',
    nextphone = '$nextphone',
    academic_session = '$acsession',
    admission_term = '$term',
    physical_peculiarity = '$physical_peculiarity',
    medical_history = '$medical_history',
    doctor_address = '$doctor_address',
    doctor_phone = '$doctor_phone',
    religion = '$religion',
    language = '$language',
    studentImage = '$studentimage',
    hospital_name = '$hospital_name',
    hospital_phone = '$hospital_phone',
    boarding_experience = '$boarding_experience',
    ifyes = '$ifyes',
    nationality = '$nationality',
    work_address = '$work_address',
    additional_info = '$additional',
    state2 = '$state2',
    hospital_address = '$hospital_address'
    WHERE id = $student_id AND status = 4";

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

  // Use FormNo as the display identifier (studentRegNo assigned later at admission)
  $studentno = $formNo;

    if ($result) {
      // 1. Update the token status to 'used'
      $stmt = $con->prepare("UPDATE registration_tokens SET token_status = 'used' WHERE token = ?");
      $stmt->bind_param("s", $token);
      $stmt->execute();


      // 3. Insert schools attended (multiple)
      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 = trim($school_names[$i]);

          $start_raw = trim($start_dates[$i] ?? '');
          $end_raw = trim($end_dates[$i] ?? '');

          $start_date = !empty($start_raw) ? $start_raw : date('Y-m-d');
          $end_date = !empty($end_raw) ? $end_raw : date('Y-m-d');

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

        $stmtSchools->close();
      }

      // Unlock tables after successful update + schools insert
      mysqli_query($con, "UNLOCK TABLES");

      $schoolnames = "";
      $dateranges = "";

      // Fetch all schools attended by this student
      $schoolsQuery = $con->prepare("SELECT school_name, start_date, end_date FROM schools_attended WHERE student_id = ?");
      $schoolsQuery->bind_param("i", $student_id);
      $schoolsQuery->execute();
      $schoolsResult = $schoolsQuery->get_result();

      $schools_list = [];
      $date_ranges = [];

      while ($row = $schoolsResult->fetch_assoc()) {
        $schools_list[] = $row['school_name'];
        $date_ranges[] = $row['start_date'] . ' - ' . $row['end_date'];
      }

      $schoolnames = implode("\n", $schools_list); // separate by new line for clarity
      $dateranges = implode("\n", $date_ranges);


      $mpdf2 = new Mpdf([
        'format' => 'A4',
        'margin_top' => 8,
        'margin_bottom' => 8,
        'margin_left' => 10,
        'margin_right' => 10
        // No default_font or default_font_size needed
      ]);



      function generateTableRowTwoCols($label1, $value1, $label2, $value2)
      {
        return '
        <tr>
            <td style="width: 200px; font-weight: bold;">' . htmlspecialchars($label1) . ':</td>
            <td style="width: 200px;">' . nl2br(htmlspecialchars($value1)) . '</td>
            <td style="width: 200px; font-weight: bold;">' . htmlspecialchars($label2) . ':</td>
            <td style="width: 400px;">' . nl2br(htmlspecialchars($value2)) . '</td>
        </tr>';
      }
      $boardingHtml = '';
      if (strtolower($stream) === 'boarding') {
        $boardingHtml = '
<h4 style="padding: 10px;"><u>BOARDING INFORMATION</u></h4>
<table>
    ' . generateTableRowTwoCols("Boarding Experience", $boarding_experience, "If Yes, Please Specify", $ifyes) . '
    <tr>
        <td style="font-weight: bold; width: 30%;">Additional Information:</td>
        <td colspan="3">' . htmlspecialchars($additional) . '</td>
    </tr>
</table>';
      }


      $entranceFormHtml = '
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Entrance Examination Form</title>
<style>
body {
    font-family: "Times New Roman", serif;
    background-color: #f9f9f9;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
    font-size: 20px;
}

td {
    padding: 8px 10px;
    vertical-align: top;
    font-size: 20px;
}

.passport {
    width: 70px;
    height: 70px;
    border-radius: 30%;
    object-fit: cover;
    border: 2px solid #2c3e50;
}
</style>
</head>
<body>
<table style="width: 100%; border-bottom: 1px solid #ccc; margin-bottom: 5px; padding-bottom: 15px;">
<tr>
    <td style="width: 80px; text-align: center;">
        <img src="' . $logo . '" width="120" height="120" alt="School Logo">
    </td>
    <td style="text-align: center;">
        <h1 style="margin: 0; font-size: 26px;"><strong>' . strtoupper($school_name) . '</strong></h1>
        <div style="font-size: 16px;">' . $school_address . '</div>
    </td>
</tr>
</table>

<div style="padding: 10px; margin-bottom: 5px; text-align: center; font-weight: bold; text-style: underline;">
    <h3><u>ENTRANCE EXAMINATION FORM</u></h3>
</div>

<table style="margin-bottom: 5px;">
<tr>
    <td style="width: 80px;">
        <img src="studentimages/' . $studentimage . '" alt="passport" class="passport">
    </td>
    <td>
        <h4 style="margin: 0;">' . htmlspecialchars($names) . '</h4>
        <h5 style="margin: 0;">Form No: ' . htmlspecialchars($studentno) . '</h5>
        <h5 style="margin: 0;">Class: ' . htmlspecialchars($class) . '</h5>
    </td>
</tr>
</table>

<h4 style="padding: 10px; text-style: underline;"><u>PERSONAL INFORMATION</u></h4>
<table>
    ' . generateTableRowTwoCols("Term", $term, "Session", $acsession) . '
    ' . generateTableRowTwoCols("Gender", $sex, "Date of Birth", $age) . '
    ' . generateTableRowTwoCols("Language", $language, "Nationality", $nationality) . '
    ' . generateTableRowTwoCols("State of Origin", $state, "L.G.A", $village) . '
    ' . generateTableRowTwoCols("Home Address", $country, "State of Residence", $state2) . '
    ' . generateTableRowTwoCols("Religion", $religion, "Physical Peculiarity", $physical_peculiarity) . '
    ' . generateTableRowTwoCols("Previous School(s)", $schoolnames, "Attended Dates", $dateranges) . '
</table>

<h4 style="padding: 10px; text-style: underline;"><u>MEDICAL INFORMATION</u></h4>
<table>
    ' . generateTableRowTwoCols("Medical History", $medical_history, "Doctor's Name", $doctor_address) . '

    ' . generateTableRowTwoCols("Doctor's Phone", $doctor_phone, "Hospital Name", $hospital_name) . '
    ' . generateTableRowTwoCols("Hospital Phone", $hospital_phone, "Hospital Address", $hospital_address) . '
</table>

<h4 style="padding: 10px; text-style: underline;"><u>PARENT/GUARDIAN INFORMATION</u></h4>
<table>
    ' . generateTableRowTwoCols("Name", $parentname, "Relationship", $relation) . '
    ' . generateTableRowTwoCols("Phone No. 1", $phone, "Phone No. 2", $nextphone) . '
    ' . generateTableRowTwoCols("Profession", $occupation, "Email Address", $email) . '
    ' . generateTableRowTwoCols("Address", $work_address, "Signature", "__________________________") . '
</table>

' . $boardingHtml . '

</body>
</html>';


      $mpdf2->SetDisplayMode('fullpage');
      $mpdf2->SetAutoPageBreak(false); // âœ… Disable page breaks
      $mpdf2->keep_table_proportions = true; // âœ… Preserve table sizing
      $mpdf2->shrink_tables_to_fit = 1; // âœ… Auto shrink tables if needed
      $mpdf2->SetDefaultBodyCSS('font-size', '0.8em'); // âœ… Shrinks all text slightly
      $mpdf2->SetDefaultBodyCSS('line-height', '1.1'); // âœ… Tightens spacing
      $mpdf2->SetHTMLHeader('');
      $mpdf2->SetHTMLFooter('');
      $mpdf2->SetWatermarkImage($logo, 0.1);
      $mpdf2->showWatermarkImage = true;

      $mpdf2->WriteHTML($entranceFormHtml);
      $pdfString2 = $mpdf2->Output('', 'S');


      // Generate PDF Exam Slip using mPDF
      $mpdf = new Mpdf();
      // Prepare exam dates HTML
      $examDatesHtml = '';
      if (mysqli_num_rows($examDatesResult) > 0) {
        $examDatesHtml .= '<div class="section-title">AVAILABLE EXAMINATION DATES</div><ul>';
        while ($row = mysqli_fetch_assoc($examDatesResult)) {
          $formattedDate = date('l, jS F Y', strtotime($row['event_date']));
          $description = !empty($row['description']) ? ' - ' . htmlspecialchars($row['description']) : '';
          // Append the fixed time
          $examDatesHtml .= '<li>' . $formattedDate . ' at 10:00 AM' . $description . '</li>';
        }
        $examDatesHtml .= '</ul>';
      } else {
        $examDatesHtml .= '<p class="note">No available exam dates at the moment. Please contact the school.</p>';
      }


      $examSlipHtml = '
      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <style>
               body {
            font-family: Times New Roman;

        }

     .container {
       border: 1px solid #000;
       padding: 10px;
     }

     .header {
       text-align: center;
     }

     .logo {
       float: left;
       width: 70px;
     }

     .school-info {
       text-align: center;
       font-weight: bold;
       font-size: 14pt;
     }
     
     .passport {
            width: 120px;
            height: 120px;
            border-radius: 30%;
            object-fit: cover;
            border: 2px solid #2c3e50;
        }

     .photobox {
       float: right;
       width: 130px;
       height: 150px;
       text-align: center;
       font-size: 10pt;
     }
     

     .clear {
       clear: both;
     }

     .section-title {
       text-align: center;
       font-weight: bold;
       font-size: 13pt;
       margin: 20px 0 10px;
     }

     .info-line {
       margin: 10px 0;
       font-size: 12pt;
     }

     .note {
       font-style: italic;
       font-size: 11pt;
       text-align: center;
       margin-top: 20px;
     }
  </style>
</head>
<body>
  <div class="container">
    <div class="logo">
      <img src="' . $logo . '" width="70">
    </div>
    <div class="photobox">
      <img src="studentimages/' . $studentimage . '" alt="passport" class="passport">
    </div>
    <div class="school-info">
     <h1 style="margin: 0; font-size: 26px;"><strong>' . strtoupper($school_name) . '</strong></h1>
      ' . $school_address . '
    </div>
    <div class="clear"></div>
    <hr>
    <div class="section-title">
      EXAMINATION IDENTIFICATION SLIP<br>
      <small>Please bring this slip into the  examination hall</small>
    </div>
    <hr>
    <div class="info-line">
      <strong>CANDIDATE&apos;S NAME:</strong> ' . strtoupper($names) . '<br><br>
      <strong>REGISTRATION NO:</strong> ' . $studentno . '
    </div>
        ' . $examDatesHtml . ' 
    <p class="note">
      Candidate should bring along his/her writing materials for the examination.
    </p>
  </div>
</body>
</html>';

      $mpdf->WriteHTML($examSlipHtml);
      $pdfString = $mpdf->Output('', 'S'); // Get the PDF as a string for email attachment


      // **SEND EMAIL WITH REGISTRATION DETAILS**
      $mail = new PHPMailer(true);
      try {
        $mail->isSMTP();
        $mail->Host = $_ENV['SMTP_HOST'];
        $mail->SMTPAuth = true;
        $mail->Username = $_ENV['SMTP_USERNAME'];
        $mail->Password = $_ENV['SMTP_PASSWORD'];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = $_ENV['SMTP_PORT'];
        $mail->Timeout = 10;

        $mail->setFrom($_ENV['SMTP_USERNAME'], $_ENV['SMTP_FROM_NAME']);
        $mail->addAddress($email, $names);


        $mail->Subject = 'Registration Form Submitted - Examination Details';
        $mail->isHTML(true);
        $mail->Body = "
        <html>
          <head>
            <meta charset='UTF-8'>
            <title>Entrance Exam Registration Successful</title>
          </head>
          <body style='font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 20px;'>
            <table align='center' width='100%' cellpadding='0' cellspacing='0' style='max-width:600px; background-color:#f4f4f4; padding:20px; margin:auto;'>
              <tr>
                <td>
                  <h1 style='color: #ffffff; text-align: center; padding: 10px 0; background-color: #4CAF50;'>SUCCESSFUL</h1>
                  <hr style='margin: 20px 0;'>
        
                  <h3 style='color: #4CAF50;'>Entrance Examination Registration Successful</h3>
        
                  <p>Dear <strong>" . htmlspecialchars($names) . "</strong>,</p>
        
                  <p>Thank you for registering for the entrance examination. Your registration has been successfully completed.</p>
        
                  <h4>Student Details</h4>
                  <p><strong>Full Name:</strong> " . htmlspecialchars($names) . "</p>
                  <p><strong>Form No:</strong> " . htmlspecialchars($studentno) . "</p>
                  <p><strong>Class Applied:</strong> " . htmlspecialchars($class) . "</p>
                  <p><strong>School Type:</strong> " . htmlspecialchars($stream) . "</p>
        
                  <h4>Important Instructions</h4>
                  <ul style='color: #444;'>
                    <li>Please find the attached Entrance Examination Slip (PDF) and Registration Form (PDF).</li>
                    <li>Print and bring both forms along on the examination day.</li>
                    <li>Arrive at least 30 minutes before the scheduled time.</li>
                  </ul>
        
                  <p>If you have any questions, feel free to contact us at 
                    <a href='mailto:" . htmlspecialchars($admission_email) . "'>" . htmlspecialchars($admission_email) . "</a>
                  </p>
        
                  <hr style='margin: 30px 0;'>
        
                  <p style='text-align: center; color: #999;'>" . htmlspecialchars($school_name) . " &copy; " . date("Y") . " All Rights Reserved.</p>
                </td>
              </tr>
            </table>
          </body>
        </html>
        ";


        $mail->addStringAttachment($pdfString, 'Entrance_Exam_Slip.pdf', 'base64', 'application/pdf');
        $mail->addStringAttachment($pdfString2, 'Registration_Form.pdf', 'base64', 'application/pdf');

        $mail->send();
        header('Location: registration.php?success=1');
        exit;
      } catch (Exception $e) {
        // Email failed but registration succeeded — still redirect with success flag
        header('Location: registration.php?success=1&email=0');
        exit;
      }
    } else {
      mysqli_query($con, "UNLOCK TABLES");
      flash_alert('Error: ' . 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/headerentrance.php"); ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php @include("includes/entrancesidebar.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">Registration Form</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="#" class="text-primary">Home</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Registration</li>
                  </ol>
                </nav>
              </div>
            </div>
          </div>
        </div>
      </section>
      <?php if (isset($_GET['success'])): ?>
        <script>
          document.addEventListener('DOMContentLoaded', function () {
            <?php if (isset($_GET['email']) && $_GET['email'] === '0'): ?>
            Swal.fire({
              icon: 'warning',
              title: 'Registration Successful',
              text: 'Your registration was submitted successfully, but the confirmation email could not be sent. Please contact the school for your registration details.',
              confirmButtonColor: '#3085d6'
            });
            <?php else: ?>
            Swal.fire({
              icon: 'success',
              title: 'Registration Submitted!',
              text: 'Your registration form has been submitted successfully. Check your email for your examination slip and registration form.',
              confirmButtonColor: '#3085d6'
            });
            <?php endif; ?>
          });
        </script>
      <?php endif; ?>

      <?php if (!$showForm): ?>
        <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> Registration Form for New
                      Students</h5>
                  </div>
                  <br>
                  <!-- /.card-header -->
                  <form method="POST">
                    <div class="row justify-content-center">
                      <div class="col-md-6">
                        <div class="card card-primary">
                          <div class="card-header">
                            <h3 class="card-title"><i class="fas fa-key"></i> Enter Your Registration Token</h3>
                          </div>
                          <div class="card-body">
                            <div class="form-group">
                              <label for="token">Token</label>
                              <input type="text" name="token" class="form-control" maxlength="10" required
                                placeholder="Enter your 10-character token">
                              <?php if (isset($tokenError)): ?>
                                <br>
                                <div class=" form-group text-center alert alert-danger"><?php echo $tokenError; ?></div>
                              <?php endif; ?>
                            </div>
                            <div class="form-group text-center">
                              <button type="submit" name="check_token" class="btn btn-primary justify-content-center"> <i
                                  class="fas fa-check-circle"></i> Validate Token</button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
        </section>
      <?php else: ?>

        <!-- 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">
                    <h5 class="card-title font-weight-bold"><i class="fas fa-user-plus"></i> Registration Form for New
                      Students</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 Fullname</label>
                          <input type="text" class="form-control" name="names" id="names" required readonly
                            value="<?php echo htmlspecialchars($prefillData['student_name'] ?? '', ENT_QUOTES); ?>">
                        </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" <?php if (($prefillData['class'] ?? '') == 'JSS 1')
                              echo 'selected'; ?>>
                              JSS 1</option>
                            <option value="JSS 2" <?php if (($prefillData['class'] ?? '') == 'JSS 2')
                              echo 'selected'; ?>>
                              JSS 2</option>
                            <option value="SS 1" <?php if (($prefillData['class'] ?? '') == 'SS 1')
                              echo 'selected'; ?>>SS 1
                            </option>
                          </select>
                        </div>

                        <div class="form-group col-md-4">
                          <label for="age">School Type</label>
                          <input type="text" class="form-control" name="stream" id="school_type" required readonly
                            value="<?php echo htmlspecialchars($prefillData['school_type'] ?? '', ENT_QUOTES); ?>">
                        </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()) {
                              $selected = ($prefillData['session'] ?? '') == $row['session_name'] ? 'selected' : '';
                              echo "<option value='{$row['session_name']}' $selected>{$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()) {
                              $selected = ($prefillData['term'] ?? '') == $row1['term_name'] ? 'selected' : '';
                              echo "<option value='{$row1['term_name']}' $selected>{$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 class="form-group col-md-4">
                          <label for="stdimage">Upload Passport Photograph</label>
                          <input type="file" class="form-control-file" id="stdimage" name="stdimage" accept="image/*"
                            onchange="validateAndPreviewImage(event)">
                          <small id="stdimageError" style="color: red; display: none;"></small>
                        </div>
                        <div class="form-group col-md-4">
                          <img id="stdimagePreview" src="#" alt="Passport Preview"
                            style="max-width: 40%; height: auto; display: none; border: 1px solid #ccc; padding: 5px;">
                        </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
                            value="<?php echo htmlspecialchars($prefillData['email'] ?? '', ENT_QUOTES); ?>">
                        </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>
                      <input type="hidden" name="token"
                        value="<?php echo htmlspecialchars($prefillData['token'] ?? '', ENT_QUOTES); ?>">


                    </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>
      <?php endif; ?>
      <!-- /.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, #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>