<?php
   session_start();
   if (empty($_SESSION['csrf_token'])) {
       $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
   }
   include_once 'connect.php';
   ?>
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Employee Profile Form</title>
      <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
      <!-- Add jQuery UI CSS for datepicker -->
      <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
      <style>
         :root {
         --primary-color: #3498db;
         --secondary-color: #2980b9;
         --accent-color: #e74c3c;
         --light-gray: #f5f5f5;
         --medium-gray: #e0e0e0;
         --dark-gray: #333;
         --success-color: #2ecc71;
         --warning-color: #f39c12;
         --border-radius: 6px;
         --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
         --transition: all 0.3s ease;
         }
         * {
         box-sizing: border-box;
         margin: 0;
         padding: 0;
         }
         body {
         font-family: 'Roboto', sans-serif;
         line-height: 1.6;
         color: var(--dark-gray);
         background-color: #f9f9f9;
         padding: 20px;
         }
         .form-container {
         max-width: 90%;
         margin: 10px auto;
         background: white;
         border-radius: var(--border-radius);
         box-shadow: var(--box-shadow);
         overflow: hidden;
         }
         .form-header {
         background: var(--primary-color);
         color: white;
         padding: 20px;
         text-align: center;
         }
         .form-header h1 {
         font-size: 24px;
         font-weight: 500;
         }
         .progress-container {
         display: flex;
         justify-content: space-between;
         position: relative;
         margin: 30px 50px;
         }
         .progress-container::before {
         content: "";
         position: absolute;
         top: 50%;
         left: 0;
         right: 0;
         height: 4px;
         background: var(--medium-gray);
         transform: translateY(-50%);
         z-index: 1;
         }
         .progress-bar {
         position: absolute;
         top: 50%;
         left: 0;
         height: 4px;
         background: var(--success-color);
         transform: translateY(-50%);
         z-index: 2;
         transition: var(--transition);
         }
         .step {
         width: 40px;
         height: 40px;
         border-radius: 50%;
         background: var(--medium-gray);
         color: var(--dark-gray);
         display: flex;
         align-items: center;
         justify-content: center;
         position: relative;
         z-index: 3;
         transition: var(--transition);
         }
         .step.active {
         background: var(--primary-color);
         color: white;
         transform: scale(1.1);
         }
         .step.completed {
         background: var(--success-color);
         color: white;
         }
         .step-label {
         position: absolute;
         top: 45px;
         font-size: 12px;
         color: var(--dark-gray);
         white-space: nowrap;
         }
         .step.active .step-label,
         .step.completed .step-label {
         color: var(--primary-color);
         font-weight: 500;
         }
         .form-step {
         display: none;
         padding: 30px;
         }
         .form-step.active {
         display: block;
         animation: fadeIn 0.5s ease;
         }
         @keyframes fadeIn {
         from { opacity: 0; transform: translateY(20px); }
         to { opacity: 1; transform: translateY(0); }
         }
         .section-title {
         color: var(--primary-color);
         margin-bottom: 20px;
         padding-bottom: 10px;
         border-bottom: 2px solid var(--medium-gray);
         font-size: 20px;
         }
         .form-group {
         margin-bottom: 20px;
         }
         .form-row {
         display: flex;
         flex-wrap: wrap;
         margin: 0 -10px;
         }
         .form-col {
         flex: 1;
         min-width: 250px;
         padding: 0 30px;
         margin-bottom: 15px;
         }
         label {
         display: block;
         margin-bottom: 8px;
         font-weight: 500;
         color: #555;
         }
         input[type="text"],
         input[type="number"],
         input[type="date"],
         input[type="month"],
         input[type="file"],
         select,
         textarea {
         width: 100%;
         padding: 12px;
         border: 1px solid var(--medium-gray);
         border-radius: var(--border-radius);
         font-size: 14px;
         transition: var(--transition);
         }
         input:focus,
         select:focus,
         textarea:focus {
         outline: none;
         border-color: var(--primary-color);
         box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
         }
         .radio-group {
         display: flex;
         flex-wrap: wrap;
         gap: 15px;
         margin-top: 8px;
         }
         .radio-option {
         display: flex;
         align-items: center;
         }
         .radio-option input {
         margin-right: 8px;
         }
         table {
         width: 100%;
         border-collapse: collapse;
         margin: 20px 0;
         box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
         }
         th, td {
         padding: 12px 15px;
         text-align: left;
         border-bottom: 1px solid var(--medium-gray);
         }
         th {
         background-color: var(--primary-color);
         color: white;
         font-weight: 500;
         }
         tr:nth-child(even) {
         background-color: var(--light-gray);
         }
         tr:hover {
         background-color: #f0f0f0;
         }
         .photo-upload {
         display: flex;
         flex-direction: column;
         align-items: center;
         margin: 20px 0;
         }
         #fileDisplayArea {
         width: 150px;
         height: 180px;
         border: 2px dashed var(--medium-gray);
         border-radius: var(--border-radius);
         display: flex;
         justify-content: center;
         align-items: center;
         margin-bottom: 15px;
         overflow: hidden;
         background-color: white;
         }
         #fileDisplayArea img {
         max-width: 100%;
         max-height: 100%;
         object-fit: cover;
         }
         .file-input-label {
         display: inline-block;
         padding: 10px 15px;
         background-color: var(--primary-color);
         color: white;
         border-radius: var(--border-radius);
         cursor: pointer;
         transition: var(--transition);
         text-align: center;
         }
         .file-input-label:hover {
         background-color: var(--secondary-color);
         }
         #tchpic {
         display: none;
         }
         .form-actions {
         display: flex;
         justify-content: space-between;
         margin-top: 30px;
         padding-top: 20px;
         border-top: 1px solid var(--medium-gray);
         }
         .btn {
         padding: 12px 24px;
         border: none;
         border-radius: var(--border-radius);
         font-size: 16px;
         font-weight: 500;
         cursor: pointer;
         transition: var(--transition);
         display: inline-flex;
         align-items: center;
         justify-content: center;
         }
         .btn-primary {
         background-color: var(--primary-color);
         color: white;
         }
         .btn-primary:hover {
         background-color: var(--secondary-color);
         }
         .btn-secondary {
         background-color: var(--medium-gray);
         color: var(--dark-gray);
         }
         .btn-secondary:hover {
         background-color: #d0d0d0;
         }
         .btn-success {
         background-color: var(--success-color);
         color: white;
         }
         .btn-success:hover {
         background-color: #27ae60;
         }
         .btn i {
         margin-right: 8px;
         }
         .required-field::after {
         content: " *";
         color: var(--accent-color);
         }
         @media (max-width: 768px) {
         .form-col {
         min-width: 100%;
         }
         .progress-container {
         margin: 30px 20px;
         }
         .step-label {
         display: none;
         }
         .form-step {
         padding: 20px;
         }
         }
         /* Additional styles for datepicker */
         .ui-datepicker {
         background: #fff;
         border: 1px solid #ccc;
         border-radius: 1px;
         padding: 5px;
         box-shadow: 0 2px 5px rgba(0,0,0,0.1);
         }
         .ui-datepicker-header {
         background: var(--primary-color);
         color: white;
         border: none;
         border-radius: 2px;
         }
         .ui-datepicker-calendar th {
         background: blue;
         }
         .ui-datepicker-calendar .ui-state-active {
         background: var(--primary-color);
         color: white;
         }
         .datepicker-trigger {
         cursor: pointer;
         margin-left: -25px;
         color: #666;
         }
         .date-input-container {
         position: relative;
         display: flex;
         align-items: center;
         }
         .date-input-container input {
         padding-right: 30px;
         }
         .error-message {
         color: red;
         font-size: 0.9em;
         margin-top: 5px;
         display: none;
         }
         /* Additional styles for Instructions window */
         .instructions {
         background-color: #e8f4fc;
         padding: 15px;
         border-radius: 6px;
         margin-top: 20px;
         font-size: 14px;
         line-height: 1.5;
         }
         .instructions h3 {
         color: #2c3e50;
         margin-bottom: 10px;
         }
         .instructions ul {
         padding-left: 20px;
         }
         .instructions li {
         margin-bottom: 5px;
         }
         .success-message {
         color: #27ae60;
         font-size: 13px;
         margin-top: 5px;
         display: none;
         }
      </style>
   </head>
   <body>
      <div class="form-container">
         <div class="form-header">
            <h1><i class="fas fa-user-tie"></i> Employee Profile Form</h1>
         </div>
         <div class="progress-container">
            <div class="progress-bar" id="progressBar"></div>
            <div class="step active" id="step1">
               <span>1</span>
               <span class="step-label">Personal Info</span>
            </div>
            <div class="step" id="step2">
               <span>2</span>
               <span class="step-label">Education</span>
            </div>
            <div class="step" id="step3">
               <span>3</span>
               <span class="step-label">Professional</span>
            </div>
            <div class="step" id="step4">
               <span>4</span>
               <span class="step-label">Training</span>
            </div>
            <div class="step" id="step5">
               <span>5</span>
               <span class="step-label">Subjects</span>
            </div>
            <div class="step" id="step6">
               <span>6</span>
               <span class="step-label">Promotions</span>
            </div>
            <div class="step" id="step7">
               <span>7</span>
               <span class="step-label">Transfers</span>
            </div>
         </div>
         <form id="teacherForm" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
            <!-- Step 1: Personal Information -->
            <div class="form-step active" id="step-1">
               <h2 class="section-title"><i class="fas fa-user"></i> Personal Information</h2>
               <div class="photo-upload">
                  <div id="fileDisplayArea">
                     <i class="fas fa-user-circle" style="font-size: 60px; color: #ccc;"></i>
                  </div>
                  <div>
                     <label for="tchpic" class="file-input-label">
                     <i class="fas fa-camera"></i> 
                     <span class="required-field">Upload Photo</span>
                     </label>
                  </div>
                  <input id="tchpic" name="tchpic" type="file" accept="image/jpeg, image/png" onchange="validateAndPreviewImage(this)" required>
                  <p class="file-requirements">Accepted: JPEG, PNG (Max 2MB)</p>
                  <div id="photo-error" style="color: red; display: none; margin-top: 5px;">Please upload a valid photo</div>
               </div>
               <!-- Personal Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label for="personalno" class="required-field">A/C Office/AG Personal #</label>
                     <input
                        id="personalno"
                        name="personalno"
                        type="text"
                        required
                        maxlength="8"
                        minlength="8"
                        inputmode="numeric"
                        title="Please enter exactly 8 digits"
                        pattern="[0-9]{8}">
                     <div id="personalno-status" style="margin-top: 5px; font-size: 0.9em;"></div>
                  </div>
                  <div class="form-col">
                     <label for="tename" class="required-field">Full Name</label>
                     <input id="tename" name="tename" type="text" pattern="[^0-9]*" title="Numbers are not allowed" required>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="tefname" class="required-field">Father/Husband Name</label>
                     <input id="tefname" name="tefname" type="text" required>
                  </div>
                  <div class="form-col">
                     <label for="tecnic" class="required-field">CNIC Number</label>
                     <input 
                        id="tecnic" 
                        name="tecnic" 
                        type="text"
                        placeholder="XXXXX-XXXXXXX-X"
                        pattern="[0-9]{5}-[0-9]{7}-[0-9]{1}"
                        title="Please enter CNIC in format: XXXXX-XXXXXXX-X"
                        maxlength="15"
                        required
                        oninput="formatCNIC(this)">
                     <div id="cnic-status" style="margin-top: 5px; font-size: 0.9em;"></div>
                  </div>
               </div>
               <!-- Demographic Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label class="required-field">Gender</label>
                     <div class="radio-group">
                        <label class="radio-option">
                        <input id="tegem" name="tege" type="radio" value="Male" required> Male
                        </label>
                        <label class="radio-option">
                        <input id="tegefem" name="tege" type="radio" value="Female" required> Female
                        </label>
                        <label class="radio-option">
                        <input id="tegeoth" name="tege" type="radio" value="Other" required> Other
                        </label>
                     </div>
                  </div>
                  <div class="form-col">
                     <label>Marital Status</label>
                     <div class="radio-group">
                        <label class="radio-option">
                        <input id="temarstm" name="temarst" type="radio" value="Married"> Married
                        </label>
                        <label class="radio-option">
                        <input id="temarstum" name="temarst" type="radio" value="Un-Married"> Unmarried
                        </label>
                        <label class="radio-option">
                        <input id="temarstdiv" name="temarst" type="radio" value="Divorced"> Divorced
                        </label>
                        <label class="radio-option">
                        <input id="temarstwid" name="temarst" type="radio" value="Widow"> Widow
                        </label>
                     </div>
                  </div>
               </div>
               <!-- Date Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label for="tebirthday" class="required-field">Date of Birth</label>
                     <div class="date-input-container">
                        <input id="tebirthday" name="tebirthday" type="text"  
                           placeholder="DD-MM-YYYY"
                           maxlength="10"
                           pattern="\d{2}-\d{2}-\d{4}"
                           title="Please enter date in DD-MM-YYYY format"
                           required>
                        <span class="datepicker-trigger" onclick="showDatePicker('tebirthday')">
                        <i class="fas fa-calendar-alt"></i>
                        </span>
                     </div>
                     <div id="tebirthday-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                  </div>
                  <div class="form-col">
                     <label for="teretirement" class="required-field">Tentative Date of Retirement</label>
                     <div class="date-input-container">
                        <input id="teretirement" name="teretirement" type="text" 
                           placeholder="DD-MM-YYYY"
                           maxlength="10" pattern="\d{2}-\d{2}-\d{4}" 
                           readonly required>
                     </div>
                     <div id="teretirement-error" class="error-message">Invalid date format</div>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="tebplace">Birth Place</label>
                     <input id="tebplace" name="tebplace" type="text">
                  </div>
                  <div class="form-col">
                     <label for="teemq" class="required-field">Employment Quota</label>
                     <select id="teemq" name="teemq" required>
                     <?php
                        // Fetch quota types from database
                        $sql = "SELECT quota_id, quota_type FROM quota ORDER BY quota_id ASC";
                        $result = $conn->query($sql);
                        
                        // Add a default option
                        echo '<option value="" selected disabled>Select Employment Quota</option>';
                        
                        if ($result && $result->num_rows > 0) {
                          // Output each Employment Quota as an option
                          while($row = $result->fetch_assoc()) {
                            echo '<option value="' . htmlspecialchars($row['quota_id']) . '">' 
                                 . htmlspecialchars($row['quota_type']) 
                                 . '</option>';
                          }
                        } else {
                          echo '<option value="">No Employment Quota found</option>';
                        }
                        ?>
                     </select>
                  </div>
               </div>
               <!-- Contact Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label for="temobno" class="required-field">Mobile No</label>
                     <input id="temobno" name="temobno" type="text" 
                        pattern="03[0-9]{9}" 
                        title="Must start with 03 and be 11 digits (e.g., 03123456789)" 
                        maxlength="11" 
                        required
                        oninput="handleMobileInput(this)"
                        onkeypress="return isNumberKey(event)"
                        onblur="validateCompleteNumber(this)">
                     <div class="error-message" id="temobno-error">❌ Must start with 03 and be 11 digits</div>
                  </div>
                  <div class="form-col">
                     <label for="tewano">WhatsApp No (You can edit it if WhatsApp is on another number)</label>
                     <input id="tewano" name="tewano" type="text" 
                        pattern="03[0-9]{9}" 
                        title="Must start with 03 and be 11 digits (e.g., 03123456789)" 
                        maxlength="11"
                        oninput="handleWhatsAppInput(this)"
                        onkeypress="return isNumberKey(event)"
                        onblur="validateCompleteNumber(this)">
                     <div class="error-message" id="tewano-error">❌ Must start with 03 and be 11 digits</div>
                  </div>
               </div>
               <!-- Official Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label for="tegpfno">GPF No</label>
                     <input id="tegpfno" name="tegpfno" type="text">
                  </div>
                  <div class="form-col">
                     <label for="teddono" class="required-field">DDO Code</label>
                     <input id="teddono" name="teddono" type="text" 
                        maxlength="6"
                        pattern="[A-Za-z]{2}\d{4}"
                        title="First 2 letters followed by 4 digits (e.g., AB1234)"
                        onkeypress="return allowDdoChars(event)" 
                        onblur="validateDdoCode(this)"
                        placeholder="Enter DDO Code Like AB1234" required>
                     <div class="error-message" id="teddono-error">
                        ❌ Must have 2 letters followed by 4 digits (e.g., AB1234)
                     </div>
                  </div>
               </div>
               <!-- Next of Kin Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label for="tenok">Next of Kin (Name)</label>
                     <input id="tenok" name="tenok" type="text">
                  </div>
                  <div class="form-col">
                     <label for="tenokre">Relation with Next of Kin</label>
                     <select id="tenokre" name="tenokre">
                     <?php
                        // Query to get relations from next_kin table
                        $query = "SELECT relationship_id, relationship_name, relationship_name_urdu FROM next_kin ORDER BY relationship_id ASC";
                        $result = $conn->query($query);
                        
                        // Check if there are results
                        if ($result->num_rows > 0) {
                          // Add a default option
                          echo '<option value="" selected disabled>Select Relation</option>';
                          
                          // Output each relation as an option
                          while($row = $result->fetch_assoc()) {
                            echo '<option value="' . htmlspecialchars($row['relationship_id']) . '">' 
                                 . htmlspecialchars($row['relationship_name']) 
                                 . ' (' . htmlspecialchars($row['relationship_name_urdu']) . ')' 
                                 . '</option>';
                          }
                        } else {
                          echo '<option value="">No relations found</option>';
                        }
                        ?>
                     </select>
                  </div>
               </div>
               <h3 class="section-title" style="margin-top: 30px;"><i class="fas fa-home"></i> Permanent Address</h3>
               <div class="form-row">
                  <div class="form-col">
                     <label for="tevillage">Village</label>
                     <input id="tevillage" name="tevillage" type="text">
                  </div>
                  <div class="form-col">
                     <label for="tepo">Post Office</label>
                     <input id="tepo" name="tepo" type="text">
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="district" class="required-field">District</label>
                     <select id="district" name="district" onchange="loadTehsils()" required>
                        <option value="">Select District</option>
                        <?php
                           // Fetch districts with security measures
                           $stmt = $conn->prepare("SELECT district_id, district_name FROM districts WHERE status = 1 ORDER BY district_name");
                           $stmt->execute();
                           $result = $stmt->get_result();
                           
                           while($row = $result->fetch_assoc()):
                           ?>
                        <option value="<?= htmlspecialchars($row['district_id']) ?>">
                           <?= htmlspecialchars($row['district_name']) ?>
                        </option>
                        <?php 
                           endwhile;
                           $stmt->close();
                           ?>
                     </select>
                  </div>
                  <div class="form-col">
                     <label for="tehsil" class="required-field">Tehsil</label>
                     <select id="tehsil" name="tehsil" onchange="loadConstituencies()" disabled required>
                        <option value="">Select Tehsil</option>
                     </select>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="constituency" class="required-field">Constituency</label>
                     <select id="constituency" name="constituency" onchange="loadUnionCouncils()" disabled required>
                        <option value="">Select Constituency</option>
                     </select>
                  </div>
                  <div class="form-col">
                     <label for="unionCouncil" class="required-field">Union Council</label>
                     <select id="unionCouncil" name="unionCouncil" disabled required>
                        <option value="">Select Union Council</option>
                     </select>
                  </div>
               </div>
               <h3 class="section-title" style="margin-top: 30px;"><i class="fas fa-briefcase"></i> Employment Details</h3>
               <div class="form-row">
                  <div class="form-col">
                     <label for="employmentType" class="required-field">Employment Type</label>
                     <select id="employmentType" name="employmentType" required>
                     <?php
                        // Fetch designations from database
                        $sql = "SELECT status_id, status_name FROM employment_status ORDER BY status_id ASC";
                        $result = $conn->query($sql);
                        
                        // Add a default option
                        echo '<option value="" selected disabled>Select Employment Status</option>';
                        
                        if ($result && $result->num_rows > 0) {
                          // Output each employment_status as an option
                          while($row = $result->fetch_assoc()) {
                            echo '<option value="' . htmlspecialchars($row['status_id']) . '">' 
                        
                                 . htmlspecialchars($row['status_name']) 
                                 . '</option>';
                          }
                        } else {
                          echo '<option value="" disabled>No Employment Status found</option>';
                        }
                        ?>
                     </select>
                  </div>
                  <div class="form-col">
                     <label for="grossPay" class="required-field">Gross Pay</label>
                     <input id="grossPay" name="grossPay" type="number" min="0" inputmode="numeric" placeholder="Enter Amount" required>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="iaa" class="required-field">Initially Appointed As</label>
                     <select id="iaa" name="iaa" required>
                     <?php
                        // Fetch designations from database
                        $sql = "SELECT des_id, designation_name FROM designations ORDER BY designation_name ASC";
                        $result = $conn->query($sql);
                        
                        // Add a default option
                        echo '<option value="" selected disabled>Select Designation</option>';
                        
                        if ($result && $result->num_rows > 0) {
                          // Output each designation as an option
                          while($row = $result->fetch_assoc()) {
                            echo '<option value="' . htmlspecialchars($row['des_id']) . '">' 
                                 . htmlspecialchars($row['designation_name']) 
                                 . '</option>';
                          }
                        } else {
                          echo '<option value="" disabled>No Designations found</option>';
                        }
                        ?>
                     </select>
                  </div>
                  <div class="form-col">
                     <label for="doapp" class="required-field">Date of Appointment</label>
                     <div class="date-input-container">
                        <input id="doapp" name="doapp" type="text" 
                           placeholder="DD-MM-YYYY" 
                           maxlength="10"
                           pattern="\d{2}-\d{2}-\d{4}"
                           title="Please enter date in DD-MM-YYYY format"
                           required>
                        <span class="datepicker-trigger" onclick="showDatePicker('doapp')">
                        <i class="fas fa-calendar-alt"></i>
                        </span>
                     </div>
                     <div id="doapp-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="tecudesig" class="required-field">Current Designation</label>
                     <select id="tecudesig" name="tecudesig" required>
                     <?php
                        // Fetch Current Designation from database
                        $sql = "SELECT des_id, designation_name FROM designations ORDER BY designation_name ASC";
                        $result = $conn->query($sql);
                        
                        // Add a default option
                        echo '<option value="" selected disabled>Select Current Designation</option>';
                        
                        if ($result && $result->num_rows > 0) {
                          // Output each designation as an option
                          while($row = $result->fetch_assoc()) {
                            echo '<option value="' . htmlspecialchars($row['des_id']) . '">' 
                                 . htmlspecialchars($row['designation_name']) 
                                 . '</option>';
                          }
                        } else {
                          echo '<option value="" disabled>No Designations found</option>';
                        }
                        ?>
                     </select>
                  </div>
                  <div class="form-col">
                     <label for="dojcp" class="required-field">Date of Promotion</label>
                     <div class="date-input-container">
                        <input id="dojcp" name="dojcp" type="text" 
                           placeholder="DD-MM-YYYY" 
                           maxlength="10"
                           pattern="\d{2}-\d{2}-\d{4}"
                           title="Please enter date in DD-MM-YYYY format"
                           required>
                        <span class="datepicker-trigger" onclick="showDatePicker('dojcp')">
                        <i class="fas fa-calendar-alt"></i>
                        </span>
                     </div>
                     <div id="dojcp-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="tecups" class="required-field">Basic Pay Scale</label>
                     <select id="tecups" name="tecups" required>
                        <option value="" selected disabled>Select Basic Pay Scale</option>
                        <?php
                           // Query to get BPS grades
                           $query = "SELECT bps_id, bps_name, bps_label FROM bps ORDER BY bps_id";
                           $result = $conn->query($query);
                           
                           if ($result->num_rows > 0) {
                             while($row = $result->fetch_assoc()) {
                               echo '<option value="' . htmlspecialchars($row['bps_id']) . '">' 
                                    . htmlspecialchars($row['bps_name'] . ' - ' . $row['bps_label']) 
                                    . '</option>';
                             }
                           } else {
                             echo '<option value="">No pay scales found</option>';
                           }
                           ?>
                     </select>
                  </div>
                  <div class="form-col">
                     <label for="current_time_scale" class="required-field">Current Time Scale</label>
                     <select id="current_time_scale" name="current_time_scale" class="form-control" required>
                        <option value="" selected disabled>Select Time Scale</option>
                        <?php
                           // Query to get time scales
                           $query = "SELECT ts_id, ts_name, ts_label FROM time_scales ORDER BY ts_id";
                           $result = $conn->query($query);
                           
                           if ($result->num_rows > 0) {
                             while($row = $result->fetch_assoc()) {
                               echo '<option value="' . htmlspecialchars($row['ts_id']) . '">' 
                                    . htmlspecialchars($row['ts_name'] . ' - ' . $row['ts_label']) 
                                    . '</option>';
                             }
                           } else {
                             echo '<option value="">No time scales found</option>';
                           }
                           ?>
                     </select>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="tetimes" class="required-field">Date of Current Time Scale</label>
                     <div class="date-input-container">
                        <input id="tetimes" name="tetimes" type="text" 
                           placeholder="DD-MM-YYYY" 
                           maxlength="10"
                           pattern="\d{2}-\d{2}-\d{4}"
                           title="Please enter date in DD-MM-YYYY format"
                           required>
                        <span class="datepicker-trigger" onclick="showDatePicker('tetimes')">
                        <i class="fas fa-calendar-alt"></i>
                        </span>
                     </div>
                     <div id="tetimes-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                  </div>
                  <div class="form-col">
                     <label for="workin" class="required-field">Presently Working Institute EMIS Code</label>
                     <select id="workin" name="workin" class="form-control" required>
                        <option value="" selected disabled>Select School EMIS Code</option>
                        <?php
                           $query = "SELECT emis_code, school_name FROM school_emis ORDER BY emis_code ASC";
                           $result = $conn->query($query);
                           
                           while($row = $result->fetch_assoc()) {
                             echo '<option value="' . htmlspecialchars($row['emis_code']) . '" 
                                   data-school="' . htmlspecialchars($row['school_name']) . '">'
                                   . htmlspecialchars($row['emis_code'] . ' - ' . $row['school_name']) 
                                   . '</option>';
                           }
                           ?>
                     </select>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="wtis" class="required-field">Working This Institution Since</label>
                     <div class="date-input-container">
                        <input id="wtis" name="wtis" type="text" 
                           placeholder="DD-MM-YYYY" 
                           maxlength="10"
                           pattern="\d{2}-\d{2}-\d{4}"
                           title="Please enter date in DD-MM-YYYY format"
                           required>
                        <span class="datepicker-trigger" onclick="showDatePicker('wtis')">
                        <i class="fas fa-calendar-alt"></i>
                        </span>
                     </div>
                     <div id="wtis-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                  </div>
                  <div class="form-col">
                     <label for="workin1">Presently Working Institute (Auto-filled)</label>
                     <input id="workin1" name="workin1" type="text" readonly>
                  </div>
               </div>
               <div class="form-actions" style="display: flex; justify-content: flex-end;">
                  <button type="button" class="btn btn-primary" onclick="if(validateStep1()) nextStep(1)">
                  <i class="fas fa-arrow-right"></i> Next
                  </button>
               </div>
            </div>
            <!-- Step 2: Academic Qualifications -->
            <div class="form-step" id="step-2">
               <h2 class="section-title"><i class="fas fa-graduation-cap"></i> Academic Qualifications</h2>
               <div class="instructions">
                  <h3>Instructions:</h3>
                  <ul>
                     <li>Enter the date in DD-MM-YYYY format or use the calendar picker.</li>
                     <li>Fill in all required fields marked with an asterisk (*).</li>
                     <li>Enter obtained marks to automatically calculate division.</li>
                     <li>Select the appropriate board/university from the dropdown.</li>
                     <li>Properly fill in the record. No partially record will be accepted.</li>
                  </ul>
               </div>
               <table>
                  <thead>
                     <tr>
                        <th>Degree</th>
                        <th>Result Declaration Date</th>
                        <th>Subject(s)</th>
                        <th>University/Board</th>
                        <th>Total Marks</th>
                        <th>Obtained Marks</th>
                        <th>Grade/Division</th>
                     </tr>
                  </thead>
                  <tbody>
                     <!-- Secondary Certificate -->
                     <tr>
                        <td>Secondary Certificate</td>
                        <td>
                           <div class="date-input-container">
                              <input id="tesscpass" name="tesscpass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format"
                                 required>
                              <span class="datepicker-trigger" onclick="showDatePicker('tesscpass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="tesscpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td><input name="tesscsub" type="text" class="subject-input"></td>
                        <td>
                           <select name="tesscuni" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection
                                 
                                 // Fetch boards from database
                                 $sql = "SELECT b_id, b_name FROM boards WHERE status = 1 ORDER by b_id ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result->num_rows > 0) {
                                     while($row = $result->fetch_assoc()) {
                                         echo '<option value="' . $row['b_id'] . '">' . $row['b_name'] . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tessctot" type="number" min="0" class="total-marks" value="850"></td>
                        <td><input name="tesscom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="tesscdiv" type="text" class="division-grade" readonly></td>
                     </tr>
                     <!-- Higher Secondary Certificate -->
                     <tr>
                        <td>Higher Secondary Certificate</td>
                        <td>
                           <div class="date-input-container">
                              <input id="tehscpass" name="tehscpass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format"
                                 required>
                              <span class="datepicker-trigger" onclick="showDatePicker('tehscpass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="tehscpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td><input name="tehscsub" type="text" class="subject-input"></td>
                        <td>
                           <select name="tehscuni" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection
                                 
                                 // Fetch boards from database
                                 $sql = "SELECT b_id, b_name FROM boards WHERE status = 1 ORDER by b_id ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result->num_rows > 0) {
                                     while($row = $result->fetch_assoc()) {
                                         echo '<option value="' . $row['b_id'] . '">' . $row['b_name'] . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tehsctot" type="number" min="0" class="total-marks" value="1100"></td>
                        <td><input name="tehscom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="tehscdiv" type="text" class="division-grade" readonly></td>
                     </tr>
                     <!-- B.A/B.Sc/BS -->
                     <tr>
                        <td>B.A/B.Sc/BS</td>
                        <td>
                           <div class="date-input-container">
                              <input id="tebspass" name="tebspass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format"
                                 required>
                              <span class="datepicker-trigger" onclick="showDatePicker('tebspass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="tebspass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td><input name="tebssub" type="text" class="subject-input"></td>
                        <td>
                           <select name="tebsuni" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tebstot" type="number" min="0" class="total-marks" value="1000"></td>
                        <td><input name="tebsom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="tebsdiv" type="text" class="division-grade" readonly></td>
                     </tr>
                     <!-- M.A/M.Sc/MCS -->
                     <tr>
                        <td>M.A/M.Sc/MCS</td>
                        <td>
                           <div class="date-input-container">
                              <input id="temapass" name="temapass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format"
                                 required>
                              <span class="datepicker-trigger" onclick="showDatePicker('temapass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="temapass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td><input name="temasub" type="text" class="subject-input"></td>
                        <td>
                           <select name="temauni" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tematot" type="number" min="0" class="total-marks" value="1000"></td>
                        <td><input name="temaom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="temadiv" type="text" class="division-grade" readonly></td>
                     </tr>
                     <!-- Master In Other Subject (1) -->
                     <tr>
                        <td>Master In Other Subject</td>
                        <td>
                           <div class="date-input-container">
                              <input id="temapass2" name="temapass2" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format"
                                 required>
                              <span class="datepicker-trigger" onclick="showDatePicker('temapass2')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="temapass2-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td><input name="temasub2" type="text" class="subject-input"></td>
                        <td>
                           <select name="temauni2" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tematot2" type="number" min="0" class="total-marks" value="1000"></td>
                        <td><input name="temaom2" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="temadiv2" type="text" class="division-grade" readonly></td>
                     </tr>
                     <!-- Master In Other Subject (2) -->
                     <tr>
                        <td>Master In Other Subject</td>
                        <td>
                           <div class="date-input-container">
                              <input id="temapass3" name="temapass3" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format"
                                 required>
                              <span class="datepicker-trigger" onclick="showDatePicker('temapass3')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="temapass3-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td><input name="temasub3" type="text" class="subject-input"></td>
                        <td>
                           <select name="temauni3" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tematot3" type="number" min="0" class="total-marks" value="1000"></td>
                        <td><input name="temaom3" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="temadiv3" type="text" class="division-grade" readonly></td>
                     </tr>
                     <!-- M.Phil -->
                     <tr>
                        <td>M.Phil</td>
                        <td>
                           <div class="date-input-container">
                              <input id="temphillpass" name="temphillpass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format"
                                 required>
                              <span class="datepicker-trigger" onclick="showDatePicker('temphillpass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="temphillpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td><input name="temphillsub" type="text" class="subject-input"></td>
                        <td>
                           <select name="temphilluni" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>

                           </select>
                        </td>
                        <td><input name="temphilltot" type="number" min="0" class="total-marks" value="4"></td>
                        <td><input name="temphillom" type="number" min="0" max="4" step="0.01" class="obtained-marks" oninput="calculateCGPA(this)"></td>
                        <td><input name="temphilldiv" type="text" class="division-grade" readonly></td>
                     </tr>
                     <!-- Ph.D -->
                     <tr>
                        <td>Ph.D</td>
                        <td>
                           <div class="date-input-container">
                              <input id="tephdpass" name="tephdpass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format"
                                 required>
                              <span class="datepicker-trigger" onclick="showDatePicker('tephdpass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="tephdpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td><input name="tephdsub" type="text" class="subject-input"></td>
                        <td>
                           <select name="tephduni" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tephdtot" type="number" min="0" class="total-marks" value="4"></td>
                        <td><input name="tephdom" type="number" min="0" max="4" step="0.01" class="obtained-marks" oninput="calculateCGPA(this)"></td>
                        <td><input name="tephddiv" type="text" class="division-grade" readonly></td>
                     </tr>
                     <!-- Other -->
                     <tr>
                        <td>Other</td>
                        <td>
                           <div class="date-input-container">
                              <input id="teotherpass" name="teotherpass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format"
                                 required>
                              <span class="datepicker-trigger" onclick="showDatePicker('teotherpass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="teotherpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td><input name="teothersub" type="text" class="subject-input"></td>
                        <td>
                           <select name="teotheruni" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="teothertot" type="number" min="0" class="total-marks" value=""></td>
                        <td><input name="teotherom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="teotherdiv" type="text" class="division-grade" readonly></td>
                     </tr>
                  </tbody>
               </table>
               <script>
                  function validateAcademicQualifications() {
                  // Validate all date fields in this step
                  const step2DateFields = [
                    'tesscpass', 'tehscpass', 'tebspass', 'temapass', 
                    'temapass2', 'temapass3', 'temphillpass', 'tephdpass', 'teotherpass'
                  ];
                  
                  let isValid = true;
                  
                  step2DateFields.forEach(field => {
                    const fieldElement = document.getElementById(field);
                    const errorElement = document.getElementById(field + '-error');
                    
                    if (fieldElement && fieldElement.value) {
                        if (!validateDateFormatGeneric(fieldElement, field + '-error')) {
                            isValid = false;
                        }
                    }
                  });
                  
                  if (isValid) {
                    nextStep(2);
                  } else {
                    alert('Please correct the date errors before proceeding.');
                  }
                  }
               </script>
               <div class="form-actions">
                  <button type="button" class="btn btn-secondary" onclick="prevStep(2)">
                  <i class="fas fa-arrow-left"></i> Back
                  </button>
                  <button type="button" class="btn btn-primary" onclick="validateAcademicQualifications()">
                  <i class="fas fa-arrow-right"></i> Next
                  </button>
               </div>
            </div>
            <!-- Step 3: Professional Qualifications -->
            <div class="form-step" id="step-3">
               <h2 class="section-title"><i class="fas fa-certificate"></i> Professional Qualifications</h2>
               <table>
                  <thead>
                     <tr>
                        <th>Degree Name</th>
                        <th>Result Declaration Date</th>
                        <th>Institution</th>
                        <th>Total Marks</th>
                        <th>Obtained Marks</th>
                        <th>Grade/Division</th>
                     </tr>
                  </thead>
                  <tbody>
                     <tr>
                        <td>PT/CT</td>
                        <td>
                           <div class="date-input-container">
                              <input id="teptpass" name="teptpass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format">
                              <span class="datepicker-trigger" onclick="showDatePicker('teptpass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="teptpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                           <select name="teptis" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tepttot" type="number" class="total-marks" value="1000" min="1" onchange="calculateDivision(this)"></td>
                        <td><input name="teptom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="teptdiv" type="text" class="division-grade" readonly></td>
                     </tr>
                     <tr>
                        <td>B.Ed/BS.Ed</td>
                         <td>
                           <div class="date-input-container">
                              <input id="tebedpass" name="tebedpass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format">
                              <span class="datepicker-trigger" onclick="showDatePicker('tebedpass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="tebedpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                           <select name="tebedis" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tebedtot" type="number" class="total-marks" value="1000" min="1" onchange="calculateDivision(this)"></td>
                        <td><input name="tebedom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="tebeddiv" type="text" class="division-grade" readonly></td>
                     </tr>
                     <tr>
                        <td>M.Ed/M.A Education</td>
                        <td>
                           <div class="date-input-container">
                              <input id="temedpass" name="temedpass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format">
                              <span class="datepicker-trigger" onclick="showDatePicker('temedpass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="temedpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                           <select name="temedis" class="board-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="temedtot" type="number" class="total-marks" value="1000" min="1" onchange="calculateDivision(this)"></td>
                        <td><input name="temedom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="temeddiv" type="text" class="division-grade" readonly></td>
                     </tr>
                     <tr>
                        <td><input name="teo1name" type="text" placeholder="Other Qualification" class="degree-input"></td>
                        <td>
                           <div class="date-input-container">
                              <input id="teo1pass" name="teo1pass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format">
                              <span class="datepicker-trigger" onclick="showDatePicker('teo1pass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="teo1pass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                           <select name="teo1is" class="institution-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="teo1tot" type="number" class="total-marks" min="1" onchange="calculateDivision(this)"></td>
                        <td><input name="teo1om" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="teo1div" type="text" class="division-grade" readonly></td>
                     </tr>
                     <tr>
                        <td><input name="teo2name" type="text" placeholder="Other Qualification" class="degree-input"></td>
                        <td>
                           <div class="date-input-container">
                              <input id="teo2pass" name="teo2pass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format">
                              <span class="datepicker-trigger" onclick="showDatePicker('teo2pass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="teo2pass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                           <select name="teo2is" class="institution-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="teo2tot" type="number" class="total-marks" min="1" onchange="calculateDivision(this)"></td>
                        <td><input name="teo2om" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="teo2div" type="text" class="division-grade" readonly></td>
                     </tr>
                     <tr>
                        <td><input name="teo3name" type="text" placeholder="Other Qualification" class="degree-input"></td>
                        <td>
                           <div class="date-input-container">
                              <input id="teo3pass" name="teo3pass" type="text" class="date-field"
                                 placeholder="DD-MM-YYYY"
                                 maxlength="10"
                                 pattern="\d{2}-\d{2}-\d{4}"
                                 title="Please enter date in DD-MM-YYYY format">
                              <span class="datepicker-trigger" onclick="showDatePicker('teo3pass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="teo3pass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                           <select name="teo3is" class="institution-input">
                              <option value="" selected disabled>Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         echo '<option value="' . $uni_id . '">' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="teo3tot" type="number" class="total-marks" min="1" onchange="calculateDivision(this)"></td>
                        <td><input name="teo3om" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
                        <td><input name="teo3div" type="text" class="division-grade" readonly></td>
                     </tr>
                  </tbody>
               </table>
               <script>
                  function validateProfessionalQualifications() {
                  const step3DateFields = [
                    'teptpass', 'tebedpass', 'temedpass', 'teo1pass', 'teo2pass', 'teo3pass'
                  ];
                  
                  let isValid = true;
                  
                  step3DateFields.forEach(field => {
                    const fieldElement = document.getElementById(field);
                    if (fieldElement && fieldElement.value) {
                        if (!validateDateFormatGeneric(fieldElement, field + '-error')) {
                            isValid = false;
                        }
                    }
                  });
                  
                  if (isValid) {
                    nextStep(3);
                  } else {
                    alert('Please correct the date errors before proceeding.');
                  }
                  }
               </script>
               <div class="form-actions">
                  <button type="button" class="btn btn-secondary" onclick="prevStep(3)">
                  <i class="fas fa-arrow-left"></i> Back
                  </button>
                  <button type="button" class="btn btn-primary" onclick="validateProfessionalQualifications()">
                  <i class="fas fa-arrow-right"></i> Next
                  </button>
               </div>
            </div>
            <!-- Step 4: In-Service Training -->
            <div class="form-step" id="step-4">
               <h2 class="section-title"><i class="fas fa-chalkboard-teacher"></i> In-Service Training (Last Five)</h2>
               <table>
                  <thead>
                     <tr>
                        <th>Title of Training</th>
                        <th>Year</th>
                        <th>Institute</th>
                        <th>Place</th>
                        <th>Duration</th>
                     </tr>
                  </thead>
                  <tbody>
                     <tr>
                        <td><input id="tr1name" name="tr1name" type="text" class="training-input" placeholder="e.g. Classroom Management"></td>
                        <td><input id="tr1year" name="tr1year" type="month" class="training-date"></td>
                        <td><input id="tr1institute" name="tr1institute" type="text" class="training-input" placeholder="Institute Name"></td>
                        <td><input id="tr1place" name="tr1place" type="text" class="training-input" placeholder="City OR Country"></td>
                        <td><input id="tr1duration" name="tr1duration" type="number" min="1" max="52" class="training-duration" placeholder="Days"></td>
                     </tr>
                     <tr>
                        <td><input id="tr2name" name="tr2name" type="text" class="training-input" placeholder="e.g. Digital Pedagogy"></td>
                        <td><input id="tr2year" name="tr2year" type="month" class="training-date"></td>
                        <td><input id="tr2institute" name="tr2institute" type="text" class="training-input" placeholder="Institute Name"></td>
                        <td><input id="tr2place" name="tr2place" type="text" class="training-input" placeholder="City OR Country"></td>
                        <td><input id="tr2duration" name="tr2duration" type="number" min="1" max="52" class="training-duration" placeholder="Days"></td>
                     </tr>
                     <tr>
                        <td><input id="tr3name" name="tr3name" type="text" class="training-input" placeholder="e.g. Assessment Techniques"></td>
                        <td><input id="tr3year" name="tr3year" type="month" class="training-date"></td>
                        <td><input id="tr3institute" name="tr3institute" type="text" class="training-input" placeholder="Institute Name"></td>
                        <td><input id="tr3place" name="tr3place" type="text" class="training-input" placeholder="City OR Country"></td>
                        <td><input id="tr3duration" name="tr3duration" type="number" min="1" max="52" class="training-duration" placeholder="Days"></td>
                     </tr>
                     <tr>
                        <td><input id="tr4name" name="tr4name" type="text" class="training-input" placeholder="e.g. Special Education"></td>
                        <td><input id="tr4year" name="tr4year" type="month" class="training-date"></td>
                        <td><input id="tr4institute" name="tr4institute" type="text" class="training-input" placeholder="Institute Name"></td>
                        <td><input id="tr4place" name="tr4place" type="text" class="training-input" placeholder="City OR Country"></td>
                        <td><input id="tr4duration" name="tr4duration" type="number" min="1" max="52" class="training-duration" placeholder="Days"></td>
                     </tr>
                     <tr>
                        <td><input id="tr5name" name="tr5name" type="text" class="training-input" placeholder="e.g. Leadership in Education"></td>
                        <td><input id="tr5year" name="tr5year" type="month" class="training-date"></td>
                        <td><input id="tr5institute" name="tr5institute" type="text" class="training-input" placeholder="Institute Name"></td>
                        <td><input id="tr5place" name="tr5place" type="text" class="training-input" placeholder="City OR Country"></td>
                        <td><input id="tr5duration" name="tr5duration" type="number" min="1" max="52" class="training-duration" placeholder="Days"></td>
                     </tr>
                  </tbody>
               </table>
               <div class="form-actions">
                  <button type="button" class="btn btn-secondary" onclick="prevStep(4)">
                  <i class="fas fa-arrow-left"></i> Back
                  </button>
                  <button type="button" class="btn btn-primary" onclick="nextStep(4)">
                  <i class="fas fa-arrow-right"></i> Next
                  </button>
               </div>
            </div>
            <!-- Step 5: Subjects Teaching -->
            <div class="form-step" id="step-5">
               <h2 class="section-title"><i class="fas fa-book-open"></i> Subjects Teaching</h2>
               <table>
                  <thead>
                     <tr>
                        <th>S.No</th>
                        <th>Subject Name</th>
                        <th>Class</th>
                        <th>Periods Per Week</th>
                     </tr>
                  </thead>
                  <tbody>
                     <?php
                        // Fetch subjects and classes from database
                        $subjects = $conn->query("SELECT * FROM subjects ORDER BY subj_name");
                        $classes = $conn->query("SELECT * FROM class ORDER BY class_id");
                        
                        // Generate 10 rows
                        for ($i = 1; $i <= 10; $i++) {
                          echo '<tr>
                                  <td>'.$i.'</td>
                                  <td>
                                    <select id="tesubject'.$i.'" name="tesubject'.$i.'" class="form-control">
                                      <option value="" selected disabled>Select Subject</option>';
                        
                          // Populate subjects dropdown
                          if ($subjects->num_rows > 0) {
                            while($subject = $subjects->fetch_assoc()) {
                              echo '<option value="'.$subject['subj_id'].'">'.$subject['subj_name'].'</option>';
                            }
                            $subjects->data_seek(0); // Reset pointer for next row
                          }
                          
                          echo '  </select>
                                </td>
                                <td>
                                  <select id="teclass'.$i.'" name="teclass'.$i.'" class="form-control">
                                    <option value=""selected disabled>Select Class</option>';
                        
                          // Populate classes dropdown
                          if ($classes->num_rows > 0) {
                            while($class = $classes->fetch_assoc()) {
                              echo '<option value="'.$class['class_id'].'">'.$class['class_name'].'</option>';
                            }
                            $classes->data_seek(0); // Reset pointer for next row
                          }
                          
                          echo '  </select>
                                </td>
                                <td>
                                  <input id="teperiod'.$i.'" name="teperiod'.$i.'" type="number" value="0" min="0" class="form-control">
                                </td>
                              </tr>';
                        }
                        ?>
                  </tbody>
               </table>
               <div class="form-actions">
                  <button type="button" class="btn btn-secondary" onclick="prevStep(5)">
                  <i class="fas fa-arrow-left"></i> Back
                  </button>
                  <button type="button" class="btn btn-primary" onclick="validateSubjects()">
                  <i class="fas fa-arrow-right"></i> Next
                  </button>
               </div>
            </div>
            
           <!-- Step 6: Promotion History -->
<div class="form-step" id="step-6">
    <h2 class="section-title"><i class="fas fa-chart-line"></i> Promotion History (Last Five in Ascending, If applicable)</h2>
    <table>
        <thead>
            <tr>
                <th>Previous Designation</th>
                <th>Scale</th>
                <th>New Designation</th>
                <th>Scale</th>
                <th>Date of Promotion</th>
            </tr>
        </thead>
        <tbody>
            <?php
            // Fetch data from database
            $designations = $conn->query("SELECT * FROM designations ORDER BY des_id");
            $bps_scales = $conn->query("SELECT * FROM bps ORDER BY bps_id");
            
            // Generate 5 promotion history rows
            for ($i = 1; $i <= 5; $i++) {
                echo '<tr>
                        <td>
                            <select id="tepredesig'.$i.'" name="tepredesig'.$i.'" class="form-control">
                                <option value="">Select Previous Designation</option>';
                
                // Populate previous designation dropdown
                if ($designations->num_rows > 0) {
                    while($desg = $designations->fetch_assoc()) {
                        echo '<option value="'.$desg['des_id'].'">'.$desg['designation_name'].'</option>';
                    }
                    $designations->data_seek(0);
                }
                
                echo '</select>
                    </td>
                    <td>
                        <select id="teprescale'.$i.'" name="teprescale'.$i.'" class="form-control">
                            <option value="">Select Scale</option>';
                
                // Populate previous scale dropdown
                if ($bps_scales->num_rows > 0) {
                    while($scale = $bps_scales->fetch_assoc()) {
                        echo '<option value="'.$scale['bps_id'].'">'.$scale['bps_label'].' ('.$scale['bps_name'].')</option>';
                    }
                    $bps_scales->data_seek(0);
                }
                
                echo '</select>
                    </td>
                    <td>
                        <select id="tenewdesig'.$i.'" name="tenewdesig'.$i.'" class="form-control">
                            <option value="">Select New Designation</option>';
                
                // Populate new designation dropdown
                if ($designations->num_rows > 0) {
                    while($desg = $designations->fetch_assoc()) {
                        echo '<option value="'.$desg['des_id'].'">'.$desg['designation_name'].'</option>';
                    }
                    $designations->data_seek(0);
                }
                
                echo '</select>
                    </td>
                    <td>
                        <select id="tenewscale'.$i.'" name="tenewscale'.$i.'" class="form-control">
                            <option value="">Select Scale</option>';
                
                // Populate new scale dropdown
                if ($bps_scales->num_rows > 0) {
                    while($scale = $bps_scales->fetch_assoc()) {
                        echo '<option value="'.$scale['bps_id'].'">'.$scale['bps_label'].' ('.$scale['bps_name'].')</option>';
                    }
                    $bps_scales->data_seek(0);
                }
                
                echo '</select>
                    </td>
                    <td>
                        <div class="date-input-container">
                            <input id="teprodate'.$i.'" name="teprodate'.$i.'" type="text" class="date-field"
                                   placeholder="DD-MM-YYYY"
                                   maxlength="10"
                                   pattern="\d{2}-\d{2}-\d{4}"
                                   title="Please enter date in DD-MM-YYYY format">
                            <span class="datepicker-trigger" onclick="showDatePicker(\'teprodate'.$i.'\')">
                                <i class="fas fa-calendar-alt"></i>
                            </span>
                        </div>
                        <div id="teprodate'.$i.'-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                    </td>
                </tr>';
            }
            ?>
        </tbody>
    </table>
    <div class="form-actions">
        <button type="button" class="btn btn-secondary" onclick="prevStep(6)">
            <i class="fas fa-arrow-left"></i> Back
        </button>
        <button type="button" class="btn btn-primary" onclick="validatePromotions()">
            <i class="fas fa-arrow-right"></i> Next
        </button>
    </div>
</div>
     <!-- Step 7: Transfer History -->
<div class="form-step" id="step-7">
    <h2 class="section-title"><i class="fas fa-exchange-alt"></i> Transfer History (Last Five in Ascending, If applicable)</h2>
    <table>
        <thead>
            <tr>
                <th>Transfer From (Institute)</th>
                <th>Transfer To (Institute)</th>
                <th>Reason of Transfer</th>
                <th>Date of Transfer</th>
            </tr>
        </thead>
        <tbody>
            <?php
            // Fetch schools and reasons from database
            $schools = $conn->query("SELECT emis_code, school_name FROM school_emis ORDER BY emis_code");
            $reasons = $conn->query("SELECT * FROM transfer_reasons WHERE is_active = TRUE");
            
            // Generate 5 transfer history rows
            for ($i = 1; $i <= 5; $i++) {
                echo '<tr>
                        <td>
                            <select id="tetfrom'.$i.'" name="tetfrom'.$i.'" class="form-control transfer-from">
                                <option value="">Select School</option>';
                
                // Populate transfer from dropdown
                if ($schools->num_rows > 0) {
                    while($school = $schools->fetch_assoc()) {
                        echo '<option value="'.$school['emis_code'].'">'.$school['school_name'].' ('.$school['emis_code'].')</option>';
                    }
                    $schools->data_seek(0);
                }
                
                echo '</select>
                    </td>
                    <td>
                        <select id="tetto'.$i.'" name="tetto'.$i.'" class="form-control transfer-to">
                            <option value="">Select School</option>';
                
                // Populate transfer to dropdown
                if ($schools->num_rows > 0) {
                    while($school = $schools->fetch_assoc()) {
                        echo '<option value="'.$school['emis_code'].'">'.$school['school_name'].' ('.$school['emis_code'].')</option>';
                    }
                    $schools->data_seek(0);
                }
                
                echo '</select>
                    </td>
                    <td>
                        <select id="tetreason'.$i.'" name="tetreason'.$i.'" class="form-control">
                            <option value="">Select Reason</option>';
                
                // Populate transfer reasons dropdown
                if ($reasons->num_rows > 0) {
                    while($reason = $reasons->fetch_assoc()) {
                        echo '<option value="'.$reason['reason_id'].'">'.$reason['reason_name'].'</option>';
                    }
                    $reasons->data_seek(0);
                }
                
                echo '</select>
                    </td>
                    <td>
                        <div class="date-input-container">
                            <input id="tetdate'.$i.'" name="tetdate'.$i.'" type="text" class="date-field"
                                   placeholder="DD-MM-YYYY"
                                   maxlength="10"
                                   pattern="\d{2}-\d{2}-\d{4}"
                                   title="Please enter date in DD-MM-YYYY format">
                            <span class="datepicker-trigger" onclick="showDatePicker(\'tetdate'.$i.'\')">
                                <i class="fas fa-calendar-alt"></i>
                            </span>
                        </div>
                        <div id="tetdate'.$i.'-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                    </td>
                </tr>';
            }
            ?>
        </tbody>
    </table>
    <div class="form-actions">
        <button type="button" class="btn btn-secondary" onclick="prevStep(7)">
            <i class="fas fa-arrow-left"></i> Back
        </button>
        <button type="submit" class="btn btn-success" name="step_7" onclick="return validateTransfers()">
            <i class="fas fa-check"></i> Submit Form
        </button>
    </div>
</div>
      </form>
      </div>
      <!-- Add jQuery and jQuery UI -->
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
      <script>
         // Initialize datepickers for ALL date fields
         $(document).ready(function() {
           // Initialize datepickers for all date fields
           $('.date-field').datepicker({
             dateFormat: 'dd-mm-yy',
             changeMonth: true,
             changeYear: true,
             yearRange: '1950:2050',
             maxDate: 0,
             showOtherMonths: true,
             selectOtherMonths: true,
             beforeShowDay: function(date) {
               var today = new Date();
               today.setHours(0, 0, 0, 0);
               return [date <= today, ""];
             }
           });
           
           // Make sure the calendar icon triggers the datepicker
           $('.datepicker-trigger').on('click', function() {
             var fieldId = $(this).closest('.date-input-container').find('.date-field').attr('id');
             $('#' + fieldId).datepicker('show');
           });
         });
         
         // Show date picker for a specific field
         function showDatePicker(fieldId) {
           $('#' + fieldId).datepicker('show');
         }
         
             // Cache existing personal numbers and CNICs
             let existingNumbersCache = [];
             let existingCNICsCache = [];
         
             // ===== NEW DATE VALIDATION FUNCTIONS =====
             function parseDDMMYYYY(dateStr) {
                 if (!dateStr || typeof dateStr !== 'string') return null;
                 
                 const parts = dateStr.split('-');
                 if (parts.length !== 3) return null;
                 
                 const day = parseInt(parts[0], 10);
                 const month = parseInt(parts[1], 10) - 1; // Months are 0-indexed in JS
                 const year = parseInt(parts[2], 10);
                 
                 if (isNaN(day) || isNaN(month) || isNaN(year)) return null;
                 
                 // Create date object (note: month is 0-indexed)
                 const date = new Date(year, month, day);
                 
                 // Check if the date is valid
                 if (date.getDate() !== day || date.getMonth() !== month || date.getFullYear() !== year) {
                     return null;
                 }
                 
                 return date;
             }
         
             function validateFutureDate(inputId) {
                 const input = document.getElementById(inputId);
                 const errorElement = document.getElementById(inputId + '-error');
                 const value = input.value.trim();
                 
                 if (!value) {
                     if (errorElement) errorElement.style.display = 'none';
                     input.setCustomValidity('');
                     return true;
                 }
                 
                 const date = parseDDMMYYYY(value);
                 if (!date) {
                     if (errorElement) {
                         errorElement.textContent = "Invalid date format (DD-MM-YYYY)";
                         errorElement.style.display = 'block';
                     }
                     input.setCustomValidity('Invalid date format');
                     return false;
                 }
                 
                 const today = new Date();
                 today.setHours(0, 0, 0, 0);
                 
                 if (date > today) {
                     if (errorElement) {
                         errorElement.textContent = "Date cannot be in the future!";
                         errorElement.style.display = 'block';
                     }
                     input.setCustomValidity('Date cannot be in the future');
                     return false;
                 }
                 
                 if (errorElement) errorElement.style.display = 'none';
                 input.setCustomValidity('');
                 return true;
             }
         
             function validateAgeGap() {
                 const dobInput = document.getElementById('tebirthday');
                 const appointmentInput = document.getElementById('doapp');
                 const errorElement = document.getElementById('doapp-error');
                 
                 if (!dobInput.value || !appointmentInput.value) return true;
                 
                 const dobDate = parseDDMMYYYY(dobInput.value);
                 const appointmentDate = parseDDMMYYYY(appointmentInput.value);
                 
                 if (!dobDate || !appointmentDate) return true;
                 
                 // Calculate age at appointment
                 let age = appointmentDate.getFullYear() - dobDate.getFullYear();
                 const monthDiff = appointmentDate.getMonth() - dobDate.getMonth();
                 
                 if (monthDiff < 0 || (monthDiff === 0 && appointmentDate.getDate() < dobDate.getDate())) {
                     age--;
                 }
                 
                 if (age < 18) {
                     if (errorElement) {
                         errorElement.textContent = "Employee must be at least 18 years old at appointment!";
                         errorElement.style.display = 'block';
                     }
                     appointmentInput.setCustomValidity('Employee must be at least 18 years old at appointment');
                     return false;
                 }
                 
                 if (errorElement) errorElement.style.display = 'none';
                 appointmentInput.setCustomValidity('');
                 return true;
             }
         
             function validatePromotionAfterAppointment() {
                 const appointmentInput = document.getElementById('doapp');
                 const promotionInput = document.getElementById('dojcp');
                 const errorElement = document.getElementById('dojcp-error');
                 
                 if (!appointmentInput.value || !promotionInput.value) return true;
                 
                 const appointmentDate = parseDDMMYYYY(appointmentInput.value);
                 const promotionDate = parseDDMMYYYY(promotionInput.value);
                 
                 if (!appointmentDate || !promotionDate) return true;
                 
                 if (promotionDate < appointmentDate) {
                     if (errorElement) {
                         errorElement.textContent = "Promotion date must be on or after appointment date!";
                         errorElement.style.display = 'block';
                     }
                     promotionInput.setCustomValidity('Promotion date must be on or after appointment date');
                     return false;
                 }
                 
                 if (errorElement) errorElement.style.display = 'none';
                 promotionInput.setCustomValidity('');
                 return true;
             }
         
             function validateTimeScaleAfterAppointment() {
                 const appointmentInput = document.getElementById('doapp');
                 const timeScaleInput = document.getElementById('tetimes');
                 const errorElement = document.getElementById('tetimes-error');
                 
                 if (!appointmentInput.value || !timeScaleInput.value) return true;
                 
                 const appointmentDate = parseDDMMYYYY(appointmentInput.value);
                 const timeScaleDate = parseDDMMYYYY(timeScaleInput.value);
                 
                 if (!appointmentDate || !timeScaleDate) return true;
                 
                 if (timeScaleDate < appointmentDate) {
                     if (errorElement) {
                         errorElement.textContent = "Time scale date must be on or after appointment date!";
                         errorElement.style.display = 'block';
                     }
                     timeScaleInput.setCustomValidity('Time scale date must be on or after appointment date');
                     return false;
                 }
                 
                 if (errorElement) errorElement.style.display = 'none';
                 timeScaleInput.setCustomValidity('');
                 return true;
             }
         
             function validateAllDates() {
                 const dateFields = ['tebirthday', 'doapp', 'dojcp', 'tetimes', 'wtis'];
                 let isValid = true;
                 
                 // First validate all dates are not in the future
                 dateFields.forEach(field => {
                     if (!validateFutureDate(field)) {
                         isValid = false;
                     }
                 });
                 
                 // Then validate specific date relationships
                 if (!validateAgeGap()) isValid = false;
                 if (!validatePromotionAfterAppointment()) isValid = false;
                 if (!validateTimeScaleAfterAppointment()) isValid = false;
                 
                 return isValid;
             }
             // ===== END OF NEW DATE VALIDATION FUNCTIONS =====
         
             // Personal number validation
             document.getElementById('personalno').addEventListener('input', function() {
               const personalNo = this.value;
               const statusElement = document.getElementById('personalno-status');
               
               statusElement.textContent = "";
               this.setCustomValidity('');
               
               if (personalNo.length === 8) {
                 if (existingNumbersCache.includes(personalNo)) {
                   showDuplicateError(statusElement);
                   return;
                 }
                 
                 statusElement.textContent = "Checking...";
                 statusElement.style.color = "#007bff";
         
                 const xhr = new XMLHttpRequest();
                 xhr.timeout = 2000;
                 xhr.open("GET", "check_personalno.php?personal_no=" + personalNo, true);
                 
                 xhr.onload = function() {
                   if (xhr.status === 200) {
                     const response = JSON.parse(xhr.responseText);
                     if (response.exists) {
                       showDuplicateError(statusElement);
                       existingNumbersCache.push(personalNo);
                     } else {
                       statusElement.textContent = "✓ Available for New Employee entry";
                       statusElement.style.color = "#28a745";
                     }
                   }
                 };
                 
                 xhr.ontimeout = function() {
                   statusElement.textContent = "Server busy - will verify on submit";
                   statusElement.style.color = "#ffc107";
                 };
                 
                 xhr.send();
               }
             });
         
             function showDuplicateError(element) {
               element.textContent = "⚠ This personal number already exists in DataBase!";
               element.style.color = "#dc3545";
               document.getElementById('personalno').setCustomValidity('Personal number already exists');
               document.getElementById('personalno').focus();
             }
         
         
             // Prevent non-numeric input for personal number
             document.getElementById('personalno').addEventListener('keydown', function(e) {
               const allowedKeys = ['Backspace', 'ArrowLeft', 'ArrowRight', 'Tab', 'Delete'];
               const isNumberKey = e.key >= '0' && e.key <= '9';
         
               if (!isNumberKey && !allowedKeys.includes(e.key)) {
                 e.preventDefault();
               }
             });
         
             // CNIC formatting and validation
             function formatCNIC(input) {
               let value = input.value.replace(/\D/g, '');
               
               if (value.length > 5) {
                 value = value.substring(0, 5) + '-' + value.substring(5);
               }
               if (value.length > 13) {
                 value = value.substring(0, 13) + '-' + value.substring(13);
               }
               
               if (value.length > 15) {
                 value = value.substring(0, 15);
               }
               
               input.value = value;
               
               const cnicDigits = value.replace(/\D/g, '');
               const statusElement = document.getElementById('cnic-status');
               
               if (cnicDigits.length === 13) {
                 input.setCustomValidity('');
                 checkCNICDuplicate(value);
               } else {
                 input.setCustomValidity('CNIC must be exactly 13 digits');
                 statusElement.textContent = "";
               }
             }
         
             function checkCNICDuplicate(cnic) {
               const statusElement = document.getElementById('cnic-status');
               
               if (existingCNICsCache.includes(cnic)) {
                 showCNICError(statusElement);
                 return;
               }
               
               statusElement.textContent = "Checking CNIC...";
               statusElement.style.color = "#007bff";
               
               const xhr = new XMLHttpRequest();
               xhr.timeout = 2000;
               xhr.open("GET", "check_cnic.php?cnic=" + encodeURIComponent(cnic), true);
               
               xhr.onload = function() {
                 if (xhr.status === 200) {
                   const response = JSON.parse(xhr.responseText);
                   if (response.exists) {
                     showCNICError(statusElement);
                     existingCNICsCache.push(cnic);
                   } else {
                     statusElement.textContent = "✓ CNIC available for new registration";
                     statusElement.style.color = "#28a745";
                   }
                 }
               };
               
               xhr.ontimeout = function() {
                 statusElement.textContent = "Server busy - will verify on submit";
                 statusElement.style.color = "#ffc107";
               };
               
               xhr.send();
             }
         
             function showCNICError(element) {
               element.textContent = "⚠ This CNIC already exists in DataBase!";
               element.style.color = "#dc3545";
               document.getElementById('tecnic').setCustomValidity('CNIC already registered');
               document.getElementById('tecnic').focus();
             }
         
             // Prevent invalid CNIC input
             document.getElementById('tecnic').addEventListener('keydown', function(e) {
               const allowedKeys = ['Backspace', 'ArrowLeft', 'ArrowRight', 'Tab', 'Delete'];
               const isDigitOrHyphen = (e.key >= '0' && e.key <= '9') || e.key === '-';
               
               if (!isDigitOrHyphen && !allowedKeys.includes(e.key)) {
                 e.preventDefault();
               }
             });
         
             // Mobile number validation
             function isNumberKey(evt) {
               const charCode = (evt.which) ? evt.which : evt.keyCode;
               return !(charCode > 31 && (charCode < 48 || charCode > 57));
             }
         
             function handleMobileInput(input) {
               const value = input.value.replace(/\D/g, '');
               if (value.length > 11) {
                 input.value = value.substring(0, 11);
               } else {
                 input.value = value;
               }
               
               if (value.length === 11) {
                 validateCompleteNumber(input);
               } else {
                 clearError(input);
               }
               
               if (value.length === 11 && value.startsWith('03')) {
                 syncWhatsAppNumber(input);
               }
             }
         
             function handleWhatsAppInput(input) {
               const value = input.value.replace(/\D/g, '');
               if (value.length > 11) {
                 input.value = value.substring(0, 11);
               } else {
                 input.value = value;
               }
               
               if (value.length === 11) {
                 validateCompleteNumber(input);
               } else {
                 clearError(input);
               }
             }
         
             function validateCompleteNumber(input) {
               const value = input.value;
               const isValid = value.startsWith('03') && value.length === 11;
               
               if (value.length > 0) {
                 showError(input, !isValid);
                 input.setCustomValidity(!isValid ? 'Must start with 03 and be exactly 11 digits' : '');
               } else {
                 clearError(input);
               }
               
               return isValid;
             }
         
             function showError(input, show) {
               const errorElement = document.getElementById(`${input.id}-error`);
               errorElement.style.display = show ? 'block' : 'none';
               input.style.borderColor = show ? 'red' : '';
             }
         
             function clearError(input) {
               showError(input, false);
               input.setCustomValidity('');
             }
         
             function syncWhatsAppNumber(mobileInput) {
               const whatsappInput = document.getElementById('tewano');
               const mobileValue = mobileInput.value;
               
               if (!whatsappInput.value || whatsappInput.value === mobileInput.dataset.prevValue) {
                 whatsappInput.value = mobileValue;
                 clearError(whatsappInput);
               }
               mobileInput.dataset.prevValue = mobileValue;
             }
         
             // DDO code validation
             function allowDdoChars(event) {
               const input = event.target;
               const charCode = event.which ? event.which : event.keyCode;
               const currentLength = input.value.length;
               
               if (currentLength < 2) {
                 return (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122);
               } else if (currentLength < 6) {
                 return charCode >= 48 && charCode <= 57;
               }
               return false;
             }
         
             function validateDdoCode(input) {
               const value = input.value;
               const isValid = /^[A-Za-z]{2}\d{4}$/.test(value);
               
               if (value.length <= 2) {
                 input.value = value.toUpperCase();
               } else if (value.length > 2) {
                 const letters = value.substring(0, 2).toUpperCase();
                 const numbers = value.substring(2);
                 input.value = letters + numbers;
               }
               
               const errorElement = document.getElementById('teddono-error');
               if (value.length > 0 && !isValid) {
                 errorElement.style.display = 'block';
                 input.setCustomValidity('Must have 2 letters followed by 4 digits');
               } else {
                 errorElement.style.display = 'none';
                 input.setCustomValidity('');
               }
               
               return isValid;
             }
         
             // Prevent numeric input in name fields
             function preventNumbers(e) {
               if ([46, 8, 9, 27, 13, 110].includes(e.keyCode) || 
                   (e.keyCode >= 35 && e.keyCode <= 40)) {
                 return;
               }
               
               if ((e.keyCode >= 48 && e.keyCode <= 57) || 
                   (e.keyCode >= 96 && e.keyCode <= 105)) {
                 e.preventDefault();
               }
             }
         
             const noNumberFields = ['tename', 'tefname', 'tebplace', 'tenok', 'tevillage', 'tepo'];
             noNumberFields.forEach(fieldId => {
               const field = document.getElementById(fieldId);
               if (field) {
                 field.addEventListener('keydown', preventNumbers);
                 
                 field.addEventListener('paste', (e) => {
                   const pasteData = e.clipboardData.getData('text');
                   if (/\d/.test(pasteData)) {
                     e.preventDefault();
                     alert('Numbers are not allowed in this field');
                   }
                 });
               }
             });
         
             // Auto-capitalize names
             function autoCapitalize(input) {
               const connectors = ['ul', 'e', 'bin', 'al', 'da', 'de', 'ud'];
               
               input.value = input.value
                 .toLowerCase()
                 .split(' ')
                 .map(word => {
                   return word
                     .split('-')
                     .map((part, index) => {
                       if (connectors.includes(part)) {
                         return part;
                       }
                       return part.charAt(0).toUpperCase() + part.slice(1);
                     })
                     .join('-');
                 })
                 .join(' ');
             }
         
             const nameFields = ['tename', 'tefname', 'tebplace', 'tenok', 'tevillage', 'tepo'];
             nameFields.forEach(fieldId => {
               const field = document.getElementById(fieldId);
               if (field) {
                 field.addEventListener('input', function () {
                   autoCapitalize(this);
                 });
               }
             });
         
             // District, Tehsil, Constituency, Union Council loading
             const $district = $('#district');
             const $tehsil = $('#tehsil');
             const $constituency = $('#constituency');
             const $unionCouncil = $('#unionCouncil');
         
             function handleAjaxError(xhr, status, error) {
               console.error("AJAX Error:", status, error);
               alert("Error loading data. Please try again.");
             }
         
             function loadTehsils() {
               const district_id = $district.val();
               
               if (district_id) {
                 $tehsil.html('<option value="">Loading...</option>');
                 $.ajax({
                   url: 'fetch_tehsils.php',
                   method: 'POST',
                   data: { district_id: district_id },
                   dataType: 'html',
                   success: function(response) {
                     $tehsil.html(response).prop('disabled', false);
                     resetDependentDropdowns([$constituency, $unionCouncil]);
                   },
                   error: handleAjaxError
                 });
               } else {
                 resetAllDependentDropdowns();
               }
             }
         
             function loadConstituencies() {
               const tehsil_id = $tehsil.val();
               
               if (tehsil_id) {
                 $constituency.html('<option value="">Loading...</option>');
                 $.ajax({
                   url: 'fetch_constituencies.php',
                   method: 'POST',
                   data: { tehsil_id: tehsil_id },
                   dataType: 'html',
                   success: function(response) {
                     $constituency.html(response).prop('disabled', false);
                     resetDependentDropdowns([$unionCouncil]);
                   },
                   error: handleAjaxError
                 });
               } else {
                 resetDependentDropdowns([$constituency, $unionCouncil]);
               }
             }
         
             function loadUnionCouncils() {
               const cons_id = $constituency.val();
               
               if (cons_id) {
                 $unionCouncil.html('<option value="">Loading...</option>');
                 $.ajax({
                   url: 'fetch_ucs.php',
                   method: 'POST',
                   data: { cons_id: cons_id },
                   dataType: 'html',
                   success: function(response) {
                     $unionCouncil.html(response).prop('disabled', false);
                   },
                   error: handleAjaxError
                 });
               } else {
                 resetDependentDropdowns([$unionCouncil]);
               }
             }
         
             function resetDependentDropdowns(dropdowns) {
               dropdowns.forEach($dropdown => {
                 $dropdown.html('<option value="">Select ' + $dropdown.attr('name').charAt(0).toUpperCase() + 
                               $dropdown.attr('name').slice(1) + '</option>').prop('disabled', true);
               });
             }
         
             function resetAllDependentDropdowns() {
               resetDependentDropdowns([$tehsil, $constituency, $unionCouncil]);
             }
         
             // School selection handling
             $(document).ready(function() {
               const originalOptions = $('#workin').html();
               
               $('#workin').on('focus', function() {
                 $(this).html(originalOptions);
               }).change(function() {
                 const selectedEmis = $(this).val();
                 const selectedText = selectedEmis;
                 
                 const tempOptions = $(this).html();
                 
                 $(this).html(originalOptions);
                 $(this).val(selectedEmis);
                 $(this).find('option:selected').text(selectedText);
                 
                 const schoolName = $(this).find('option:selected').data('school');
                 $('#workin1').val(schoolName || '');
               });
             });
         
             // Datepicker initialization
             $(document).ready(function() {
               const dateFields = ['tebirthday', 'doapp', 'dojcp', 'tetimes', 'wtis'];
               
               dateFields.forEach(fieldId => {
                 const $field = $('#' + fieldId);
                 
                 $field.datepicker({
                   dateFormat: 'dd-mm-yy',
                   changeMonth: true,
                   changeYear: true,
                   yearRange: '-100:+0',
                   maxDate: 0,
                   showOtherMonths: true,
                   selectOtherMonths: true,
                   beforeShowDay: function(date) {
                     var today = new Date();
                     today.setHours(0, 0, 0, 0);
                     return [date <= today, ""];
                   },
                   onSelect: function(dateText, inst) {
                     const errorElement = document.getElementById(this.id + '-error');
                     if (errorElement) errorElement.style.display = 'none';
                     
                     if (fieldId === 'tebirthday') {
                       calculateRetirementDate();
                     }
                     
                     validateAllDates();
                   },
                   onClose: function(dateText, inst) {
                     validateAllDates();
                   }
                 }).on('keydown', function(e) {
                   if (e.keyCode === 13) {
                     $(this).datepicker('hide');
                     
                     if (fieldId === 'tebirthday') {
                       calculateRetirementDate();
                     }
                     
                     validateAllDates();
                     
                     e.preventDefault();
                     return false;
                   }
                 }).on('blur', function() {
                   if (fieldId === 'tebirthday') {
                     calculateRetirementDate();
                   }
                   
                   validateAllDates();
                 });
               });
             });
         
             // Date validation functions
             function validateDateFormat(input) {
               if (typeof input === 'string') {
                 input = document.getElementById(input);
               }
               
               const errorElement = document.getElementById(input.id + '-error');
               const value = input.value.trim();
               
               if (!value) {
                 if (errorElement) errorElement.style.display = 'none';
                 input.setCustomValidity('');
                 return true;
               }
               
               const datePattern = /^(\d{2})-(\d{2})-(\d{4})$/;
               if (!datePattern.test(value)) {
                 if (errorElement) {
                   errorElement.textContent = "Invalid date format (DD-MM-YYYY)";
                   errorElement.style.display = 'block';
                 }
                 input.setCustomValidity('Please enter date in DD-MM-YYYY format');
                 return false;
               }
               
               const parts = value.split('-');
               const day = parseInt(parts[0], 10);
               const month = parseInt(parts[1], 10) - 1;
               const year = parseInt(parts[2], 10);
               
               const inputDate = new Date(year, month, day);
               if (isNaN(inputDate.getTime()) || 
                   inputDate.getDate() !== day || 
                   inputDate.getMonth() !== month || 
                   inputDate.getFullYear() !== year) {
                 if (errorElement) {
                   errorElement.textContent = "Invalid date!";
                   errorElement.style.display = 'block';
                 }
                 input.setCustomValidity('Invalid date');
                 return false;
               }
               
               const today = new Date();
               today.setHours(0, 0, 0, 0);
               
               if (inputDate > today) {
                 if (errorElement) {
                   errorElement.textContent = "Date cannot be in the future!";
                   errorElement.style.display = 'block';
                 }
                 input.setCustomValidity('Date cannot be in the future');
                 input.value = '';
                 return false;
               }
               
               if (errorElement) errorElement.style.display = 'none';
               input.setCustomValidity('');
               return true;
             }
         
             function calculateRetirementDate() {
               const birthDateInput = document.getElementById('tebirthday');
               const retirementDateInput = document.getElementById('teretirement');
               
               if (!birthDateInput.value) {
                 retirementDateInput.value = '';
                 return;
               }
               
               try {
                 const parts = birthDateInput.value.split('-');
                 const day = parseInt(parts[0], 10);
                 const month = parseInt(parts[1], 10) - 1;
                 const year = parseInt(parts[2], 10);
                 
                 const birthDate = new Date(year, month, day);
                 const retirementDate = new Date(birthDate);
                 retirementDate.setFullYear(retirementDate.getFullYear() + 60);
                 retirementDate.setDate(retirementDate.getDate() - 1);
                 
                 const today = new Date();
                 today.setHours(0, 0, 0, 0);
                 
                 if (retirementDate > today) {
                   const dd = String(retirementDate.getDate()).padStart(2, '0');
                   const mm = String(retirementDate.getMonth() + 1).padStart(2, '0');
         
                   const yyyy = retirementDate.getFullYear();
                   
                   retirementDateInput.value = `${dd}-${mm}-${yyyy}`;
                 } else {
                   retirementDateInput.value = '';
                 }
               } catch (error) {
                 console.error('Error calculating retirement date:', error);
                 retirementDateInput.value = '';
               }
             }
         
             function showDatePicker(fieldId) {
               $('#' + fieldId).datepicker('show');
             }
         
             // Image validation
             function validateAndPreviewImage(input) {
               const file = input.files[0];
               const fileDisplayArea = document.getElementById('fileDisplayArea');
               const maxSizeMB = 2;
         
               if (!file) {
                 resetPhotoPreview();
                 return;
               }
         
               const validTypes = ['image/jpeg', 'image/png'];
               if (!validTypes.includes(file.type)) {
                 alert('Error: Only JPEG or PNG images are allowed.');
                 resetFileInput(input);
                 return;
               }
         
               if (file.size > maxSizeMB * 1024 * 1024) {
                 alert(`Error: Image exceeds ${maxSizeMB}MB maximum size.`);
                 resetFileInput(input);
                 return;
               }
         
               const reader = new FileReader();
               reader.onload = function(e) {
                 fileDisplayArea.innerHTML = `<img src="${e.target.result}" alt="Employee Photo">`;
               };
               reader.readAsDataURL(file);
             }
         
             function resetFileInput(input) {
               input.value = '';
               resetPhotoPreview();
             }
         
             function resetPhotoPreview() {
               document.getElementById('fileDisplayArea').innerHTML =
                 '<i class="fas fa-user-circle" style="font-size: 60px; color: #ccc;"></i>';
             }
         
             function validateStep1() {
               document.querySelectorAll('input, select').forEach(el => {
                 el.style.borderColor = '';
               });
               
               const requiredFields = [
                 'personalno', 'tename', 'tefname', 'tecnic', 'tebirthday',
                 'teemq', 'temobno', 'teddono', 'district', 'tehsil', 'constituency', 'unionCouncil',
                 'employmentType', 'grossPay', 'iaa', 'doapp', 'tecudesig', 'dojcp',
                 'tecups', 'current_time_scale', 'tetimes', 'workin', 'wtis'
               ];
         
               let isValid = true;
               
               requiredFields.forEach(field => {
                 const element = document.getElementById(field);
                 if (!element || !element.value.trim()) {
                   if (element) element.style.borderColor = '#e74c3c';
                   isValid = false;
                 }
               });
         
               // Use our date validation functions
               if (!validateAllDates()) {
                 isValid = false;
               }
               
               const retirementDateInput = document.getElementById('teretirement');
               if (retirementDateInput && retirementDateInput.value) {
                 if (!retirementDateInput.value.trim()) {
                   retirementDateInput.style.borderColor = '#e74c3c';
                   isValid = false;
                 } else {
                   retirementDateInput.style.borderColor = '';
                 }
               }
         
               const genderSelected = document.querySelector('input[name="tege"]:checked');
               if (!genderSelected) {
                 document.querySelectorAll('[name="tege"]').forEach(radio => {
                   radio.closest('.radio-group').style.border = '1px solid #e74c3c';
                 });
                 isValid = false;
               }
         
               const cnicField = document.getElementById('tecnic');
               if (cnicField && !/^\d{5}-\d{7}-\d{1}$/.test(cnicField.value)) {
                 cnicField.style.borderColor = '#e74c3c';
                 isValid = false;
               }
         
               const mobileField = document.getElementById('temobno');
               if (mobileField && !/^03\d{9}$/.test(mobileField.value)) {
                 mobileField.style.borderColor = '#e74c3c';
                 isValid = false;
               }
         
               const photoField = document.getElementById('tchpic');
               if (!photoField.files || photoField.files.length === 0) {
                 document.getElementById('photo-error').style.display = 'block';
                 isValid = false;
               } else {
                 document.getElementById('photo-error').style.display = 'none';
               }
         
               if (!isValid) {
                 alert('Please fill all required fields correctly');
                 return false;
               }
         
               return true;
             }
         
             // Initialize mobile input tracking
             document.addEventListener('DOMContentLoaded', function() {
               const mobileInput = document.getElementById('temobno');
               const whatsappInput = document.getElementById('tewano');
               
               mobileInput.dataset.prevValue = mobileInput.value;
               whatsappInput.dataset.prevValue = whatsappInput.value;
               
               // Add employment date validation listeners
               const employmentDateFields = ['tebirthday', 'doapp', 'dojcp', 'tetimes'];
               employmentDateFields.forEach(fieldId => {
                 const field = document.getElementById(fieldId);
                 if (field) {
                   field.addEventListener('change', validateAllDates);
                   field.addEventListener('blur', validateAllDates);
                 }
               });
               
               // Add retirement date calculation listener
               const birthDateInput = document.getElementById('tebirthday');
               if (birthDateInput) {
                 birthDateInput.addEventListener('change', calculateRetirementDate);
                 
                 if (birthDateInput.value) {
                   calculateRetirementDate();
                 }
               }
             });
         
         // Multi-Step Form Navigation
         let currentStep = 1;
         const totalSteps = 7;
         
         function showStep(step) {
             document.querySelectorAll('.form-step').forEach(el => el.classList.remove('active'));
             document.querySelectorAll('.step').forEach(el => el.classList.remove('active', 'completed'));
             
             document.getElementById(`step-${step}`).classList.add('active');
             document.getElementById(`step${step}`).classList.add('active');
         
             const progress = ((step - 1) / (totalSteps - 1)) * 100;
             document.getElementById('progressBar').style.width = `${progress}%`;
         
             for (let i = 1; i < step; i++) {
                 document.getElementById(`step${i}`).classList.add('completed');
             }
         
             currentStep = step;
         }
         
         function nextStep(step) {
             if (step === 1) {
                 if (!validateStep1()) return false;
             }
             showStep(step + 1);
         }
         
         function prevStep(step) {
             showStep(step - 1);
         }
         
         // Initialize the form
         document.addEventListener('DOMContentLoaded', function() {
             document.getElementById('progressBar').style.width = '0%';
             showStep(1);
             
             // Add required field validation
             const requiredFields = document.querySelectorAll('[required]');
             requiredFields.forEach(field => {
                 field.addEventListener('input', function() {
                     if (this.value.trim()) {
                         this.style.borderColor = '';
                     }
                 });
             });
         });

         
         // Academic Qualifications Validation
             function calculateDivision(inputElement) {
               const row = inputElement.closest('tr');
               const totalMarksInput = row.querySelector('.total-marks');
               const obtainedMarksInput = inputElement;
               const divisionInput = row.querySelector('.division-grade');
               
               const totalMarks = parseFloat(totalMarksInput.value) || 0;
               const obtainedMarks = parseFloat(obtainedMarksInput.value) || 0;
               
               if (totalMarks <= 0 || obtainedMarks < 0) {
                 divisionInput.value = '';
                 return;
               }
               
               const percentage = (obtainedMarks / totalMarks) * 100;
               
               // Pakistani Grading System
               if (percentage >= 80) {
                 divisionInput.value = "A+ (First Division with Distinction)";
               } else if (percentage >= 70) {
                 divisionInput.value = "A (First Division)";
               } else if (percentage >= 60) {
                 divisionInput.value = "B (Second Division)";
               } else if (percentage >= 50) {
                 divisionInput.value = "C (Second Division)";
               } else if (percentage >= 40) {
                 divisionInput.value = "D (Third Division)";
               } else {
                 divisionInput.value = "F (Fail)";
               }
             }
         
             // For CGPA-based degrees (M.Phil, PhD)
             function calculateCGPA(inputElement) {
               const row = inputElement.closest('tr');
               const divisionInput = row.querySelector('.division-grade');
               const cgpa = parseFloat(inputElement.value) || 0;
               
               if (cgpa >= 3.67) {
                 divisionInput.value = "A+ (Excellent)";
               } else if (cgpa >= 3.33) {
                 divisionInput.value = "A (Very Good)";
               } else if (cgpa >= 3.00) {
                 divisionInput.value = "B+ (Good)";
               } else if (cgpa >= 2.67) {
                 divisionInput.value = "B (Satisfactory)";
               } else if (cgpa >= 2.33) {
                 divisionInput.value = "C+ (Pass)";
               } else if (cgpa >= 2.00) {
                 divisionInput.value = "C (Minimum Pass)";
               } else {
                 divisionInput.value = "F (Fail)";
               }
             }
         
             function validateAcademicQualifications() {
               let hasMinimumQualifications = false;
               
               // Check if at least matric and intermediate are filled
               const matricMarks = document.querySelector('input[name="tesscom"]').value;
               const interMarks = document.querySelector('input[name="tehscom"]').value;
               
               if (matricMarks && interMarks) {
                 hasMinimumQualifications = true;
               }
               
               if (!hasMinimumQualifications) {
                 if (confirm('Minimum qualifications (Matric and Intermediate) are not complete. Continue anyway?')) {
                   nextStep(2);
                 }
               } else {
                 nextStep(2);
               }
             }
         
             // Subjects Validation
             function validateSubjects() {
               let isValid = true;
               
               // Check at least one subject is selected
               for (let i = 1; i <= 10; i++) {
                 const subject = document.getElementById(`tesubject${i}`).value;
                 const classVal = document.getElementById(`teclass${i}`).value;
                 const periods = document.getElementById(`teperiod${i}`).value;
                 
                 // If any field in a row is filled, all must be filled
                 if (subject || classVal || (periods && periods != 0)) {
                   if (!subject || !classVal || !periods) {
                     isValid = false;
                     alert(`Please complete all fields in row ${i} or leave all blank`);
                     break;
                   }
                 }
               }
               
               if (isValid) {
                 nextStep(5);
               }
             }
         
             // Promotions Validation
             function validatePromotions() {
               let isValid = true;
               const promotionDates = [];
         // Validate promotion dates
         for (let i = 1; i <= 5; i++) {
         const field = document.getElementById(`teprodate${i}`);
         if (field && field.value) {
            if (!validateDateFormatGeneric(field, `teprodate${i}-error`)) {
                isValid = false;
            }
         }
         }
               
               // Check all promotion entries
               for (let i = 1; i <= 5; i++) {
                 const prevDesig = document.getElementById(`tepredesig${i}`).value;
                 const prevScale = document.getElementById(`teprescale${i}`).value;
                 const newDesig = document.getElementById(`tenewdesig${i}`).value;
                 const newScale = document.getElementById(`tenewscale${i}`).value;
                 const proDate = document.getElementById(`teprodate${i}`).value;
                 
                 // Check if any field in the row is filled
                 if (prevDesig || prevScale || newDesig || newScale || proDate) {
                   // Validate all fields in the row are filled
                   if (!prevDesig || !prevScale || !newDesig || !newScale || !proDate) {
                     isValid = false;
                     alert(`Please complete all fields in promotion row ${i} or leave all blank`);
                     break;
                   }
                   
                   // Validate promotion date is not in future
                   const today = new Date();
                   today.setHours(0, 0, 0, 0);
                   const promotionDate = new Date(proDate);
                   if (promotionDate > today) {
                     isValid = false;
                     alert(`Promotion date in row ${i} cannot be in the future`);
                     break;
                   }
                   
                   // Store date for chronological validation
                   if (proDate) promotionDates.push(proDate);
                 }
               }
               
               // Validate chronological order if multiple entries
               if (promotionDates.length > 1) {
                 const sortedDates = [...promotionDates].sort();
                 if (promotionDates.join() !== sortedDates.join()) {
                   isValid = false;
                   alert('Promotion dates must be in chronological order (oldest first)');
                 }
               }
               
              if (isValid) {
         nextStep(6);
         } else {
         alert('Please correct the date errors before proceeding.');
         }
         }
         
             // Enhanced form submission with AJAX
             document.getElementById('teacherForm').addEventListener('submit', function(e) {
               e.preventDefault();
               
         // Validate transfer dates
         let isValid = true;
         for (let i = 1; i <= 5; i++) {
         const field = document.getElementById(`tetdate${i}`);
         if (field && field.value) {
            if (!validateDateFormatGeneric(field, `tetdate${i}-error`)) {
                isValid = false;
            }
         }
         }
         
         if (!isValid) {
         alert('Please correct the date errors before submitting.');
         return;
         }
         
               // Validate all steps first
               if (!validateAllSteps()) {
                 return;
               }
               
               // Create FormData object
               const formData = new FormData(this);
               
               // Add CSRF token to FormData
               formData.append('csrf_token', '<?php echo $_SESSION['csrf_token']; ?>');
               
               // Show loading indicator
               const submitBtn = this.querySelector('button[type="submit"]');
               submitBtn.disabled = true;
               submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
               
               // Submit via AJAX
               fetch('teacher_multi_save.php', {
                 method: 'POST',
                 body: formData
               })
               .then(response => response.json())
               .then(data => {
                 if (data.success) {
                   // Success - redirect or show success message
                   alert('Form submitted successfully!');
                   window.location.href = 'teacher_multi.php?id=' + data.employee_id;
                 } else {
                   // Show error message
                   alert('Error: ' + data.message);
                   // Highlight problematic fields if provided in response
                   if (data.errors) {
                     highlightErrors(data.errors);
                   }
                 }
               })
               .catch(error => {
                 console.error('Error:', error);
                 alert('An error occurred while submitting the form');
               })
               .finally(() => {
                 submitBtn.disabled = false;
                 submitBtn.innerHTML = '<i class="fas fa-check"></i> Submit Form';
               });
             });
         
             function validateAllSteps() {
               // Step 1 validation
               const requiredFields = [
                 'personalno', 'tename', 'tefname', 'tecnic', 
                 'tebirthday', 'teretirement', 'teemq', 'temobno', 'teddono',
                 'district', 'tehsil', 'constituency', 'unionCouncil', 'employmentType', 'grossPay',
                 'iaa', 'doapp', 'tecudesig', 'dojcp', 'tecups', 
                 'current_time_scale', 'tetimes', 'workin' , 'workin1' , 'wtis' , 'tchpic'
               ];
               
               let isValid = true;
               const errors = [];
               
               // Validate required fields
               requiredFields.forEach(field => {
                 const element = document.getElementById(field);
                 if (!element || !element.value.trim()) {
                   element.style.borderColor = '#e74c3c';
                   errors.push(field);
                   isValid = false;
                 }
               });
               
               // Validate gender
               if (!document.querySelector('input[name="tege"]:checked')) {
                 isValid = false;
                 errors.push('tege');
               }
               
               // Validate CNIC format
               const cnic = document.getElementById('tecnic').value;
               if (!/^\d{5}-\d{7}-\d{1}$/.test(cnic)) {
                 document.getElementById('tecnic').style.borderColor = '#e74c3c';
                 isValid = false;
                 errors.push('tecnic');
               }
               
               // Validate mobile number
               const mobile = document.getElementById('temobno').value;
               if (!/^03\d{9}$/.test(mobile)) {
                 document.getElementById('temobno').style.borderColor = '#e74c3c';
                 isValid = false;
                 errors.push('temobno');
               }
               
               if (!isValid) {
                 alert('Please correct the highlighted fields');
                 showStep(1); // Return to first step with errors
                 return false;
               }
               
               return true;
             }
         
             function highlightErrors(errors) {
               // Reset all error highlights
               document.querySelectorAll('input, select').forEach(el => {
                 el.style.borderColor = '';
               });
               
               // Highlight errors
               errors.forEach(field => {
                 const element = document.getElementById(field) || 
                                document.querySelector(`[name="${field}"]`);
                 if (element) {
                   element.style.borderColor = '#e74c3c';
                 }
               });
             }
         
             // Prevent same school selection for transfers
             document.querySelectorAll('.transfer-from, .transfer-to').forEach(select => {
               select.addEventListener('change', function() {
                 const row = this.closest('tr');
                 const fromSelect = row.querySelector('.transfer-from');
                 const toSelect = row.querySelector('.transfer-to');
                 
                 if (fromSelect.value && fromSelect.value === toSelect.value) {
                   alert('Cannot transfer to the same school');
                   this.value = '';
                 }
               });
             });
           
      </script>
      </script>
      
      <script>
	  // ===== GLOBAL DATE VALIDATION FUNCTION =====
// Function to validate date format for any field
function validateDateFormatGeneric(inputElement, errorElementId) {
    const value = inputElement.value.trim();
    const errorElement = document.getElementById(errorElementId);
    
    if (!value) {
        if (errorElement) errorElement.style.display = 'none';
        inputElement.setCustomValidity('');
        return true;
    }
    
    const datePattern = /^(\d{2})-(\d{2})-(\d{4})$/;
    if (!datePattern.test(value)) {
        if (errorElement) {
            errorElement.textContent = "Invalid date format (DD-MM-YYYY)";
            errorElement.style.display = 'block';
        }
        inputElement.setCustomValidity('Please enter date in DD-MM-YYYY format');
        return false;
    }
    
    const parts = value.split('-');
    const day = parseInt(parts[0], 10);
    const month = parseInt(parts[1], 10) - 1;
    const year = parseInt(parts[2], 10);
    
    const inputDate = new Date(year, month, day);
    if (isNaN(inputDate.getTime()) || 
        inputDate.getDate() !== day || 
        inputDate.getMonth() !== month || 
        inputDate.getFullYear() !== year) {
        if (errorElement) {
            errorElement.textContent = "Invalid date!";
            errorElement.style.display = 'block';
        }
        inputElement.setCustomValidity('Invalid date');
        return false;
    }
    
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    if (inputDate > today) {
        if (errorElement) {
            errorElement.textContent = "Date cannot be in the future!";
            errorElement.style.display = 'block';
        }
        inputElement.setCustomValidity('Date cannot be in the future');
        return false;
    }
    
    if (errorElement) errorElement.style.display = 'none';
    inputElement.setCustomValidity('');
    return true;
}

// Function to add date validation to all date fields in steps 2-7
function initializeAllDateValidations() {
    // Step 2: Academic Qualifications
    const step2DateFields = [
        {field: 'tesscpass', error: 'tesscpass-error'},
        {field: 'tehscpass', error: 'tehscpass-error'},
        {field: 'tebspass', error: 'tebspass-error'},
        {field: 'temapass', error: 'temapass-error'},
        {field: 'temapass2', error: 'temapass2-error'},
        {field: 'temapass3', error: 'temapass3-error'},
        {field: 'temphillpass', error: 'temphillpass-error'},
        {field: 'tephdpass', error: 'tephdpass-error'},
        {field: 'teotherpass', error: 'teotherpass-error'}
    ];
    
    step2DateFields.forEach(item => {
        const field = document.getElementById(item.field);
        if (field) {
            field.addEventListener('blur', function() {
                validateDateFormatGeneric(this, item.error);
            });
            field.addEventListener('change', function() {
                validateDateFormatGeneric(this, item.error);
            });
        }
    });
    
    // Step 3: Professional Qualifications
    const step3DateFields = [
        {field: 'teptpass', error: 'teptpass-error'},
        {field: 'tebedpass', error: 'tebedpass-error'},
        {field: 'temedpass', error: 'temedpass-error'},
        {field: 'teo1pass', error: 'teo1pass-error'},
        {field: 'teo2pass', error: 'teo2pass-error'},
        {field: 'teo3pass', error: 'teo3pass-error'}
    ];
    
    step3DateFields.forEach(item => {
        const field = document.getElementById(item.field);
        if (field) {
            field.addEventListener('blur', function() {
                validateDateFormatGeneric(this, item.error);
            });
            field.addEventListener('change', function() {
                validateDateFormatGeneric(this, item.error);
            });
        }
    });
    
    // Step 6: Promotion History
    for (let i = 1; i <= 5; i++) {
        const fieldId = `teprodate${i}`;
        const errorId = `teprodate${i}-error`;
        const field = document.getElementById(fieldId);
        
        if (field) {
            field.addEventListener('blur', function() {
                validateDateFormatGeneric(this, errorId);
            });
            field.addEventListener('change', function() {
                validateDateFormatGeneric(this, errorId);
            });
        }
    }
    
    // Step 7: Transfer History
    for (let i = 1; i <= 5; i++) {
        const fieldId = `tetdate${i}`;
        const errorId = `tetdate${i}-error`;
        const field = document.getElementById(fieldId);
        
        if (field) {
            field.addEventListener('blur', function() {
                validateDateFormatGeneric(this, errorId);
            });
            field.addEventListener('change', function() {
                validateDateFormatGeneric(this, errorId);
            });
        }
    }
}

// Call this function when the document is ready
document.addEventListener('DOMContentLoaded', function() {
    initializeAllDateValidations();
});

// ===== REST OF YOUR JAVASCRIPT CODE =====
// Cache existing personal numbers and CNICs
let existingNumbersCache = [];
let existingCNICsCache = [];
      </script>
   </body>
</html>