<?php

// Start session at the very top
session_start();

// Generate CSRF token only if it doesn't exist
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>

<!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">
  <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);
    }

    #employeePhoto {
      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;
      }
    }
  </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 Information</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="employeeForm" 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">
          <!-- Image preview container -->
          <div id="fileDisplayArea">
            <i class="fas fa-user-circle" style="font-size: 60px; color: #ccc;"></i>
          </div>
          
          <!-- File input (hidden, triggered by label) -->
          <label for="employeePhoto" class="file-input-label">
            <i class="fas fa-camera"></i> Upload Photo
          </label>
          <input 
            id="employeePhoto" 
            name="employee_photo" 
            type="file" 
            accept="image/jpeg, image/png" 
            onchange="validateAndPreviewImage(this)" 
            required
          >
          <p class="file-requirements">Accepted: JPEG, PNG (Max 2MB)</p>
        </div>

        <script>
        function validateAndPreviewImage(input) {
          const file = input.files[0]; // Get selected file
          const fileDisplayArea = document.getElementById('fileDisplayArea');
          const maxSizeMB = 2; // Max file size (2MB)
          
          // Reset if no file selected
          if (!file) {
            resetPhotoPreview();
            return;
          }
          
          // Validate file type (JPEG/PNG only)
          const validTypes = ['image/jpeg', 'image/png'];
          if (!validTypes.includes(file.type)) {
            alert('Error: Only JPEG or PNG images are allowed.');
            resetFileInput(input);
            return;
          }
          
          // Validate file size (max 2MB)
          if (file.size > maxSizeMB * 1024 * 1024) {
            alert(`Error: Image exceeds ${maxSizeMB}MB maximum size.`);
            resetFileInput(input);
            return;
          }
          
          // Create preview using FileReader API
          const reader = new FileReader();
          reader.onload = function(e) {
            fileDisplayArea.innerHTML = `<img src="${e.target.result}" alt="Employee Photo">`;
          };
          reader.readAsDataURL(file); // Convert image to Data URL
        }

        // Reset file input if invalid
        function resetFileInput(input) {
          input.value = '';
          resetPhotoPreview();
        }

        // Reset preview to default icon
        function resetPhotoPreview() {
          document.getElementById('fileDisplayArea').innerHTML = 
            '<i class="fas fa-user-circle" style="font-size: 60px; color: #ccc;"></i>';
        }
        </script>
        
        <!-- Personal Information -->
        <div class="form-row">
          <div class="form-col">
            <label for="personalNumber" class="required-field">A/C Office/AG Personal #</label>
            <input
              id="personalNumber"
              name="personal_number"
              type="text"
              required
              maxlength="8"
              minlength="8"
              inputmode="numeric"
              title="Please enter exactly 8 digits"
              pattern="[0-9]{8}">
            <div id="personalNumber-status" style="margin-top: 5px; font-size: 0.9em;"></div>
          </div>

          <div class="form-col">
            <label for="fullName" class="required-field">Full Name</label>
            <input id="fullName" name="full_name" type="text" required>
          </div>
        </div>

        <div class="form-row">
          <div class="form-col">
            <label for="fatherName" class="required-field">Father/Husband Name</label>
            <input id="fatherName" name="father_name" type="text" required>
          </div>

          <div class="form-col">
            <label for="cnicNumber" class="required-field">CNIC Number</label>
            <input 
              id="cnicNumber" 
              name="cnic_number" 
              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="genderMale" name="gender" type="radio" value="Male" required> Male
              </label>
              <label class="radio-option">
                <input id="genderFemale" name="gender" type="radio" value="Female" required> Female
              </label>
              <label class="radio-option">
                <input id="genderOther" name="gender" 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="maritalMarried" name="marital_status" type="radio" value="Married"> Married
              </label>
              <label class="radio-option">
                <input id="maritalUnmarried" name="marital_status" type="radio" value="Un-Married"> Unmarried
              </label>
              <label class="radio-option">
                <input id="maritalDivorced" name="marital_status" type="radio" value="Divorced"> Divorced
              </label>
              <label class="radio-option">
                <input id="maritalWidow" name="marital_status" type="radio" value="Widow"> Widow
              </label>
            </div>
          </div>
        </div>

        <!-- Date Information -->
        <div class="form-row">
          <div class="form-col">
            <label for="birthDate" class="required-field">Date of Birth</label>
            <input id="birthDate" name="birth_date" type="date" required onchange="calculateRetirementDate()">
          </div>
          <div class="form-col">
            <label for="retirementDate" class="required-field">Tentative Date of Retirement</label>
            <input id="retirementDate" name="retirement_date" type="date" required readonly>
          </div>
        </div>

        <script>
        function calculateRetirementDate() {
          const birthDateInput = document.getElementById('birthDate');
          const retirementDateInput = document.getElementById('retirementDate');
          
          if (birthDateInput.value) {
            const birthDate = new Date(birthDateInput.value);
            const retirementDate = new Date(birthDate);
            
            // Add 60 years minus one day
            retirementDate.setFullYear(birthDate.getFullYear() + 60);
            retirementDate.setDate(birthDate.getDate() - 1);
            
            // Format as YYYY-MM-DD for the date input
            const formattedDate = retirementDate.toISOString().split('T')[0];
            retirementDateInput.value = formattedDate;
          } else {
            retirementDateInput.value = '';
          }
        }
        </script>

        <div class="form-row">
          <div class="form-col">
            <label for="birthPlace">Birth Place</label>
            <input id="birthPlace" name="birth_place" type="text">
          </div>
          <div class="form-col">
            <label for="employmentQuota" class="required-field">Employment Quota</label>
            <select id="employmentQuota" name="employment_quota" required>
              <?php
              // Assuming you're using PHP to connect to your database
              include_once 'connect.php';
              
              // Fetch quota types from database
              $sql = "SELECT quota_id, quota_type FROM quota ORDER BY quota_id";
              $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="mobileNumber" class="required-field">Mobile No</label>
            <input id="mobileNumber" name="mobile_number" type="text" 
                   pattern="03[0-9]{9}" 
                   title="Must start with 03 and be 11 digits (e.g., 03123456789)" 
                   maxlength="11" 
                   required
                   oninput="validatePakNumber(this, 'mobile'); syncWhatsAppNumber(this)"
                   onkeypress="return isNumberKey(event)"
                   onblur="checkNumberStart(this)">
            <div class="error-message" id="mobileNumber-error" style="color:red; display:none;">❌ Number must start with 03</div>
          </div>
          <div class="form-col">
            <label for="whatsappNumber">WhatsApp No (You can edit it, if WhatsApp is on anyother number)</label>
            <input id="whatsappNumber" name="whatsapp_number" type="text" 
                   pattern="03[0-9]{9}" 
                   title="Must start with 03 and be 11 digits (e.g., 03123456789)" 
                   maxlength="11"
                   oninput="validatePakNumber(this, 'whatsapp')"
                   onkeypress="return isNumberKey(event)"
                   onblur="checkNumberStart(this)">
            <div class="error-message" id="whatsappNumber-error" style="color:red; display:none;">❌ Number must start with 03</div>
          </div>
        </div>

        <script>
        // Error display function
        function showError(input, show) {
          const errorElement = document.getElementById(`${input.id}-error`);
          errorElement.style.display = show ? 'block' : 'none';
          input.style.borderColor = show ? 'red' : '';
        }

        // Check if number starts with 03
        function checkNumberStart(input) {
          const isValid = input.value.startsWith('03');
          showError(input, !isValid && input.value.length > 0);
          return isValid;
        }

        // Allow only numeric input
        function isNumberKey(evt) {
          const charCode = (evt.which) ? evt.which : evt.keyCode;
          return !(charCode > 31 && (charCode < 48 || charCode > 57));
        }

        // Validate Pakistani number format (03XXXXXXXXX)
        function validatePakNumber(input, fieldType) {
          let value = input.value.replace(/\D/g, '');
          
          // Immediate error if starts with wrong digits
          if (value.length >= 2 && !value.startsWith('03')) {
            showError(input, true);
          } else {
            showError(input, false);
          }
          
          // Auto-correct if possible
          if (value.length === 1 && value !== '0') {
            value = '0' + value;
          }
          if (value.length === 2 && !value.startsWith('03')) {
            value = '03';
          }
          
          // Limit to 11 digits
          if (value.length > 11) {
            value = value.substring(0, 11);
          }
          
          input.value = value;
          
          // Validation for form submission
          if (value.length === 11 && value.startsWith('03')) {
            input.setCustomValidity('');
          } else {
            input.setCustomValidity('Must start with 03 and be exactly 11 digits');
          }
          
          // Special handling for mobile field
          if (fieldType === 'mobile') {
            syncWhatsAppNumber(input);
          }
        }

        // Sync WhatsApp number with mobile number
        function syncWhatsAppNumber(mobileInput) {
          const whatsappInput = document.getElementById('whatsappNumber');
          const mobileValue = mobileInput.value;
          
          if (mobileValue.startsWith('03') && mobileValue.length === 11 &&
              (!whatsappInput.value || whatsappInput.value === mobileInput.dataset.prevValue)) {
            whatsappInput.value = mobileValue;
          }
          mobileInput.dataset.prevValue = mobileValue;
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
          document.getElementById('mobileNumber').addEventListener('change', function() {
            syncWhatsAppNumber(this);
          });
        });
        </script>

        <!-- Official Information -->
        <div class="form-row">
          <div class="form-col">
            <label for="gpfNumber">GPF No</label>
            <input id="gpfNumber" name="gpf_number" type="text">
          </div>
          <div class="form-col">
            <label for="ddoCode">DDO Code</label>
            <input id="ddoCode" name="ddo_code" type="text">
          </div>
        </div>

        <!-- Next of Kin Information -->
        <div class="form-row">
          <div class="form-col">
            <label for="nextOfKin">Next of Kin (Name)</label>
            <input id="nextOfKin" name="next_of_kin" type="text">
          </div>
          
          <div class="form-col">
            <label for="kinRelation">Relation with Next of Kin</label>
            <select id="kinRelation" name="kin_relation">
              <?php
              // Include your database connection
              require 'connect.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";
              $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="village">Village</label>
            <input id="village" name="village" type="text">
          </div>
          <div class="form-col">
            <label for="postOffice">Post Office</label>
            <input id="postOffice" name="post_office" 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
              // Database connection
              include_once 'connect.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="union_council" disabled required>
              <option value="">Select Union Council</option>
            </select>
          </div>
        </div>

        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
        // Cache selectors
        const $district = $('#district');
        const $tehsil = $('#tehsil');
        const $constituency = $('#constituency');
        const $unionCouncil = $('#unionCouncil');

        // Error handling function
        function handleAjaxError(xhr, status, error) {
            console.error("AJAX Error:", status, error);
            alert("Error loading data. Please try again.");
        }

        // District changed - load tehsils
        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();
            }
        }

        // Tehsil changed - load constituencies
        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]);
            }
        }

        // Constituency changed - load UCs
        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]);
            }
        }

        // Reset specific dependent dropdowns
        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);
            });
        }

        // Reset all dependent dropdowns
        function resetAllDependentDropdowns() {
            resetDependentDropdowns([$tehsil, $constituency, $unionCouncil]);
        }
        </script>
        
        <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="employment_type" required>
              <?php
              // Assuming you're using PHP to connect to your database
              include_once 'connect.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="gross_pay" type="text" inputmode="numeric" placeholder="Enter amount" required>
          </div>
        </div>
         
        <div class="form-row">
          <div class="form-col">
            <label for="initialDesignation" class="required-field">Initially Appointed As</label>
            <select id="initialDesignation" name="initial_designation" required>
              <?php
              // Assuming you're using PHP to connect to your database
              include_once 'connect.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="appointmentDate" class="required-field">Date of Appointment</label>
            <input id="appointmentDate" name="appointment_date" type="date" required>
          </div>
        </div>

        <div class="form-row">
          <div class="form-col">
            <label for="currentDesignation" class="required-field">Current Designation</label>
            <select id="currentDesignation" name="current_designation" required>
              <?php
              // Assuming you're using PHP to connect to your database
              include_once 'connect.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="promotionDate" class="required-field">Date of Promotion</label>
            <input id="promotionDate" name="promotion_date" type="date" required>
          </div>
        </div>

        <div class="form-row">
          <div class="form-col">
            <label for="currentPayScale" class="required-field">Basic Pay Scale</label>
            <select id="currentPayScale" name="current_pay_scale" required>
              <option value="" selected disabled>Select Basic Pay Scale</option>
              <?php
              // Include your database connection
              require 'connect.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="currentTimeScale" class="required-field">Current Time Scale</label>
            <select id="currentTimeScale" name="current_time_scale" class="form-control" required>
              <option value="" selected disabled>Select Time Scale</option>
              <?php
              // Include your database connection
              require 'connect.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="timeScaleDate" class="required-field">Date of Current Time Scale</label>
            <input id="timeScaleDate" name="time_scale_date" type="date" required>
          </div>
          <div class="form-col">
            <label for="emisCode" class="required-field">Presently Working Institute EMIS Code</label>
            <select id="emisCode" name="emis_code" class="form-control" required>
              <option value="" selected disabled>Select School EMIS Code</option>
              <?php
              require 'connect.php';
              $query = "SELECT emis_code, school_name FROM school_emis ORDER BY emis_code";
              $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>';
              }
              $conn->close();
              ?>
            </select>
          </div>
        </div>

        <div class="form-row">
          <div class="form-col">
            <label for="workingSince" class="required-field">Working This Institution Since</label>
            <input id="workingSince" name="working_since" type="date" required>
          </div>
          <div class="form-col">
            <label for="schoolName">Presently Working Institute (Auto-filled)</label>
            <input id="schoolName" name="school_name" type="text" readonly>
          </div>
        </div>

        <div class="form-actions">
          <button type="button" class="btn btn-secondary" onclick="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>
        
        <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><input name="secondary_pass_date" type="date" class="date-input"></td>
              <td><input name="secondary_subjects" type="text" class="subject-input"></td>
              <td><input name="secondary_board" type="text" class="board-input"></td>
              <td><input name="secondary_total_marks" type="number" min="0" class="total-marks" value="850"></td>
              <td><input name="secondary_obtained_marks" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
              <td><input name="secondary_grade" type="text" class="division-grade" readonly></td>
            </tr>
            
            <!-- Higher Secondary Certificate -->
            <tr>
              <td>Higher Secondary Certificate</td>
              <td><input name="higher_secondary_pass_date" type="date" class="date-input"></td>
              <td><input name="higher_secondary_subjects" type="text" class="subject-input"></td>
              <td><input name="higher_secondary_board" type="text" class="board-input"></td>
              <td><input name="higher_secondary_total_marks" type="number" min="0" class="total-marks" value="1100"></td>
              <td><input name="higher_secondary_obtained_marks" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
              <td><input name="higher_secondary_grade" type="text" class="division-grade" readonly></td>
            </tr>
            
            <!-- B.A/B.Sc/BS -->
            <tr>
              <td>B.A/B.Sc/BS</td>
              <td><input name="bachelor_pass_date" type="date" class="date-input"></td>
              <td><input name="bachelor_subjects" type="text" class="subject-input"></td>
              <td><input name="bachelor_university" type="text" class="board-input"></td>
              <td><input name="bachelor_total_marks" type="number" min="0" class="total-marks" value="1000"></td>
              <td><input name="bachelor_obtained_marks" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
              <td><input name="bachelor_grade" type="text" class="division-grade" readonly></td>
            </tr>
            
            <!-- M.A/M.Sc/MCS -->
            <tr>
              <td>M.A/M.Sc/MCS</td>
              <td><input name="master_pass_date" type="date" class="date-input"></td>
              <td><input name="master_subjects" type="text" class="subject-input"></td>
              <td><input name="master_university" type="text" class="board-input"></td>
              <td><input name="master_total_marks" type="number" min="0" class="total-marks" value="1000"></td>
              <td><input name="master_obtained_marks" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
              <td><input name="master_grade" type="text" class="division-grade" readonly></td>
            </tr>
            
            <!-- Master In Other Subject (1) -->
            <tr>
              <td>Master In Other Subject</td>
              <td><input name="master2_pass_date" type="date" class="date-input"></td>
              <td><input name="master2_subjects" type="text" class="subject-input"></td>
              <td><input name="master2_university" type="text" class="board-input"></td>
              <td><input name="master2_total_marks" type="number" min="0" class="total-marks" value="1000"></td>
              <td><input name="master2_obtained_marks" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
              <td><input name="master2_grade" type="text" class="division-grade" readonly></td>
            </tr>
            
            <!-- Master In Other Subject (2) -->
            <tr>
              <td>Master In Other Subject</td>
              <td><input name="master3_pass_date" type="date" class="date-input"></td>
              <td><input name="master3_subjects" type="text" class="subject-input"></td>
              <td><input name="master3_university" type="text" class="board-input"></td>
              <td><input name="master3_total_marks" type="number" min="0" class="total-marks" value="1000"></td>
              <td><input name="master3_obtained_marks" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
              <td><input name="master3_grade" type="text" class="division-grade" readonly></td>
            </tr>
            
            <!-- M.Phil -->
            <tr>
              <td>M.Phil</td>
              <td><input name="mphil_pass_date" type="date" class="date-input"></td>
              <td><input name="mphil_subjects" type="text" class="subject-input"></td>
              <td><input name="mphil_university" type="text" class="board-input"></td>
              <td><input name="mphil_total_marks" type="number" min="0" class="total-marks" value="4"></td>
              <td><input name="mphil_obtained_marks" type="number" min="0" max="4" step="0.01" class="obtained-marks" oninput="calculateCGPA(this)"></td>
              <td><input name="mphil_grade" type="text" class="division-grade" readonly></td>
            </tr>
            
            <!-- Ph.D -->
            <tr>
              <td>Ph.D</td>
              <td><input name="phd_pass_date" type="date" class="date-input"></td>
              <td><input name="phd_subjects" type="text" class="subject-input"></td>
              <td><input name="phd_university" type="text" class="board-input"></td>
              <td><input name="phd_total_marks" type="number" min="0" class="total-marks" value="4"></td>
              <td><input name="phd_obtained_marks" type="number" min="0" max="4" step="0.01" class="obtained-marks" oninput="calculateCGPA(this)"></td>
              <td><input name="phd_grade" type="text" class="division-grade" readonly></td>
            </tr>
            
            <!-- Other -->
            <tr>
              <td>Other</td>
              <td><input name="other_pass_date" type="date" class="date-input"></td>
              <td><input name="other_subjects" type="text" class="subject-input"></td>
              <td><input name="other_university" type="text" class="board-input"></td>
              <td><input name="other_total_marks" type="number" min="0" class="total-marks" value=""></td>
              <td><input name="other_obtained_marks" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"></td>
              <td><input name="other_grade" type="text" class="division-grade" readonly></td>
            </tr>
          </tbody>
        </table>
        
        <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><input name="pt_pass_date" type="date" class="date-input"></td>
              <td><input name="pt_institution" type="text" class="institution-input"></td>
              <td><input name="pt_total_marks" type="number" class="total-marks" value="1000"></td>
              <td><input name="pt_obtained_marks" type="number" min="0" class="obtained-marks"></td>
              <td><input name="pt_grade" type="text" class="division-grade" readonly></td>
            </tr>
            <tr>
              <td>B.Ed/BS.Ed</td>
              <td><input name="bed_pass_date" type="date" class="date-input"></td>
              <td><input name="bed_institution" type="text" class="institution-input"></td>
              <td><input name="bed_total_marks" type="number" class="total-marks" value="1000"></td>
              <td><input name="bed_obtained_marks" type="number" min="0" class="obtained-marks"></td>
              <td><input name="bed_grade" type="text" class="division-grade" readonly></td>
            </tr>
            <tr>
              <td>M.Ed/M.A Education</td>
              <td><input name="med_pass_date" type="date" class="date-input"></td>
              <td><input name="med_institution" type="text" class="institution-input"></td>
              <td><input name="med_total_marks" type="number" class="total-marks" value="1000"></td>
              <td><input name="med_obtained_marks" type="number" min="0" class="obtained-marks"></td>
              <td><input name="med_grade" type="text" class="division-grade" readonly></td>
            </tr>
            <tr>
              <td><input name="other1_degree" type="text" placeholder="Other Qualification" class="degree-input"></td>
              <td><input name="other1_pass_date" type="date" class="date-input"></td>
              <td><input name="other1_institution" type="text" class="institution-input"></td>
              <td><input name="other1_total_marks" type="number" class="total-marks" value=""></td>
              <td><input name="other1_obtained_marks" type="number" min="0" class="obtained-marks"></td>
              <td><input name="other1_grade" type="text" class="division-grade" readonly></td>
            </tr>
            <tr>
              <td><input name="other2_degree" type="text" placeholder="Other Qualification" class="degree-input"></td>
              <td><input name="other2_pass_date" type="date" class="date-input"></td>
              <td><input name="other2_institution" type="text" class="institution-input"></td>
              <td><input name="other2_total_marks" type="number" class="total-marks" value=""></td>
              <td><input name="other2_obtained_marks" type="number" min="0" class="obtained-marks"></td>
              <td><input name="other2_grade" type="text" class="division-grade" readonly></td>
            </tr>
            <tr>
              <td><input name="other3_degree" type="text" placeholder="Other Qualification" class="degree-input"></td>
              <td><input name="other3_pass_date" type="date" class="date-input"></td>
              <td><input name="other3_institution" type="text" class="institution-input"></td>
              <td><input name="other3_total_marks" type="number" class="total-marks" value=""></td>
              <td><input name="other3_obtained_marks" type="number" min="0" class="obtained-marks"></td>
              <td><input name="other3_grade" type="text" class="division-grade" readonly></td>
            </tr>
          </tbody>
        </table>
        
        <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="nextStep(3)">
            <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="training1_name" name="training1_name" type="text" class="training-input" placeholder="e.g. Classroom Management"></td>
              <td><input id="training1_year" name="training1_year" type="month" class="training-date"></td>
              <td><input id="training1_institute" name="training1_institute" type="text" class="training-input" placeholder="Institute Name"></td>
              <td><input id="training1_place" name="training1_place" type="text" class="training-input" placeholder="City OR Country"></td>
              <td><input id="training1_duration" name="training1_duration" type="number" min="1" max="52" class="training-duration" placeholder="Days"></td>
            </tr>
            <tr>
              <td><input id="training2_name" name="training2_name" type="text" class="training-input" placeholder="e.g. Digital Pedagogy"></td>
              <td><input id="training2_year" name="training2_year" type="month" class="training-date"></td>
              <td><input id="training2_institute" name="training2_institute" type="text" class="training-input" placeholder="Institute Name"></td>
              <td><input id="training2_place" name="training2_place" type="text" class="training-input" placeholder="City OR Country"></td>
              <td><input id="training2_duration" name="training2_duration" type="number" min="1" max="52" class="training-duration" placeholder="Days"></td>
            </tr>
            <tr>
              <td><input id="training3_name" name="training3_name" type="text" class="training-input" placeholder="e.g. Assessment Techniques"></td>
              <td><input id="training3_year" name="training3_year" type="month" class="training-date"></td>
              <td><input id="training3_institute" name="training3_institute" type="text" class="training-input" placeholder="Institute Name"></td>
              <td><input id="training3_place" name="training3_place" type="text" class="training-input" placeholder="City OR Country"></td>
              <td><input id="training3_duration" name="training3_duration" type="number" min="1" max="52" class="training-duration" placeholder="Days"></td>
            </tr>
            <tr>
              <td><input id="training4_name" name="training4_name" type="text" class="training-input" placeholder="e.g. Special Education"></td>
              <td><input id="training4_year" name="training4_year" type="month" class="training-date"></td>
              <td><input id="training4_institute" name="training4_institute" type="text" class="training-input" placeholder="Institute Name"></td>
              <td><input id="training4_place" name="training4_place" type="text" class="training-input" placeholder="City OR Country"></td>
              <td><input id="training4_duration" name="training4_duration" type="number" min="1" max="52" class="training-duration" placeholder="Days"></td>
            </tr>
            <tr>
              <td><input id="training5_name" name="training5_name" type="text" class="training-input" placeholder="e.g. Leadership in Education"></td>
              <td><input id="training5_year" name="training5_year" type="month" class="training-date"></td>
              <td><input id="training5_institute" name="training5_institute" type="text" class="training-input" placeholder="Institute Name"></td>
              <td><input id="training5_place" name="training5_place" type="text" class="training-input" placeholder="City OR Country"></td>
              <td><input id="training5_duration" name="training5_duration" 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
            // Connect to database
            include_once 'connect.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="subject'.$i.'" name="subject'.$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="class'.$i.'" name="class'.$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="period'.$i.'" name="period'.$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
            // Connect to database
            include_once 'connect.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="previousDesignation'.$i.'" name="previousDesignation'.$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="previousScale'.$i.'" name="previousScale'.$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="newDesignation'.$i.'" name="newDesignation'.$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="newScale'.$i.'" name="newScale'.$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><input id="promotionDate'.$i.'" name="promotionDate'.$i.'" type="date" class="form-control"></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
            include_once "connect.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="transferFrom'.$i.'" name="transferFrom'.$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="transferTo'.$i.'" name="transferTo'.$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="transferReason'.$i.'" name="transferReason'.$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><input id="transferDate'.$i.'" name="transferDate'.$i.'" type="date" class="form-control"></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="submit">
            <i class="fas fa-check"></i> Submit Form
          </button>
        </div>
      </div>
    </form>
  </div>

  <script>
    // Enhanced form submission with AJAX
    document.getElementById('employeeForm').addEventListener('submit', function(e) {
      e.preventDefault();
      
      // 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('employee_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 = 'employee_view.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 = [
        'personal_number', 'full_name', 'father_name', 'cnic_number', 'birth_date', 
        'retirement_date', 'employment_quota', 'mobile_number', 'district', 'tehsil', 'constituency',
        'union_council', 'employment_type', 'gross_pay', 'initial_designation', 'appointment_date', 'current_designation', 
        'current_pay_scale', 'promotion_date', 'current_time_scale', 'time_scale_date', 'emis_code'
      ];
      
      let isValid = true;
      const errors = [];
      
      // Validate required fields
      requiredFields.forEach(field => {
        const element = document.getElementById(field) || document.querySelector(`[name="${field}"]`);
        if (!element || !element.value.trim()) {
          element.style.borderColor = '#e74c3c';
          errors.push(field);
          isValid = false;
        }
      });
      
      // Validate gender
      if (!document.querySelector('input[name="gender"]:checked')) {
        isValid = false;
        errors.push('gender');
      }
      
      // Validate CNIC format
      const cnic = document.getElementById('cnicNumber').value;
      if (!/^\d{5}-\d{7}-\d{1}$/.test(cnic)) {
        document.getElementById('cnicNumber').style.borderColor = '#e74c3c';
        isValid = false;
        errors.push('cnic_number');
      }
      
      // Validate mobile number
      const mobile = document.getElementById('mobileNumber').value;
      if (!/^03\d{9}$/.test(mobile)) {
        document.getElementById('mobileNumber').style.borderColor = '#e74c3c';
        isValid = false;
        errors.push('mobile_number');
      }
      
      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';
        }
      });
    }

    function validateTransfers() {
      let hasEntries = false;
      let isValid = true;
      const transferDates = [];
      
      // Check all transfer entries
      for (let i = 1; i <= 5; i++) {
        const fromSchool = document.getElementById(`transferFrom${i}`).value;
        const toSchool = document.getElementById(`transferTo${i}`).value;
        const reason = document.getElementById(`transferReason${i}`).value;
        const transferDate = document.getElementById(`transferDate${i}`).value;
        
        // Check if any field in the row is filled
        if (fromSchool || toSchool || reason || transferDate) {
          hasEntries = true;
          
          // Validate all fields in the row are filled
          if (!fromSchool || !toSchool || !reason || !transferDate) {
            isValid = false;
            alert(`Please complete all fields in transfer row ${i} or leave all blank`);
            break;
          }
          
          // Validate transfer date is not in future
          const today = new Date();
          today.setHours(0, 0, 0, 0);
          const dateObj = new Date(transferDate);
          if (dateObj > today) {
            isValid = false;
            alert(`Transfer date in row ${i} cannot be in the future`);
            break;
          }
          
          // Validate different schools
          if (fromSchool === toSchool) {
            isValid = false;
            alert(`Transfer from and to schools cannot be same in row ${i}`);
            break;
          }
          
          // Store date for chronological validation
          if (transferDate) transferDates.push(transferDate);
        }
      }
      
      // Validate chronological order if multiple entries
      if (transferDates.length > 1) {
        const sortedDates = [...transferDates].sort();
        if (transferDates.join() !== sortedDates.join()) {
          isValid = false;
          alert('Transfer dates must be in chronological order (oldest first)');
        }
      }
    }

    // Prevent same school selection
    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>
    let currentStep = 1;
    const totalSteps = 7;

    function showStep(step) {
      // Hide current step
      document.querySelector(`.form-step.active`).classList.remove('active');
      document.getElementById(`step${currentStep}`).classList.remove('active');
      
      // Show new step
      document.getElementById(`step-${step}`).classList.add('active');
      document.getElementById(`step${step}`).classList.add('active');
      
      // Update progress bar
      const progress = ((step - 1) / (totalSteps - 1)) * 100;
      document.getElementById('progressBar').style.width = `${progress}%`;
      
      // Update step indicators
      for (let i = 1; i <= totalSteps; i++) {
        const stepElement = document.getElementById(`step${i}`);
        if (i < step) {
          stepElement.classList.add('completed');
          stepElement.classList.remove('active');
        } else if (i === step) {
          stepElement.classList.add('active');
          stepElement.classList.remove('completed');
        } else {
          stepElement.classList.remove('active', 'completed');
        }
      }
      
      currentStep = step;
    }

    // Function to validate employment date sequence
    function validateEmploymentDates() {
      const appointmentDate = document.getElementById('appointmentDate').value;
      const promotionDate = document.getElementById('promotionDate').value;
      const timeScaleDate = document.getElementById('timeScaleDate').value;
      
      // Convert dates to Date objects for comparison
      const appointment = new Date(appointmentDate);
      const promotion = new Date(promotionDate);
      const timeScale = new Date(timeScaleDate);
      
      let isValid = true;
      
      // Check if dates are valid (not empty)
      if (appointmentDate && promotionDate) {
        if (appointment > promotion) {
          alert("Date of Appointment cannot be after Date of Promotion!");
          document.getElementById('appointmentDate').focus();
          isValid = false;
        }
      }
      
      if (appointmentDate && timeScaleDate) {
        if (appointment > timeScale) {
          alert("Date of Appointment cannot be after Date of Current Time Scale!");
          document.getElementById('appointmentDate').focus();
          isValid = false;
        }
      }
      
      return isValid;
    }

    // Function to validate all dates in step 1
    function validateStep1Dates() {
      if (!validateBirthDate(document.getElementById('birthDate'))) {
        return false;
      }
      
      if (!validateEmploymentDates()) {
        return false;
      }
      
      return true;
    }

    // Modify the nextStep function to include date validation
    function nextStep(step) {
      // Basic validation for current step
      if (step === 1) {
        // Validate all required fields first
        const requiredFields = [
          'personal_number', 'full_name', 'father_name', 'cnic_number', 'gender',
          'birth_date', 'retirement_date', 'employment_quota', 'mobile_number',
          'district', 'tehsil', 'constituency', 'union_council', 'employment_type', 'gross_pay',
          'initial_designation', 'appointment_date', 'current_designation', 
          'promotion_date', 'current_pay_scale', 'current_time_scale', 
          'time_scale_date', 'emis_code', 'school_name'
        ];
        
        let isValid = true;
        
        // 1. Validate required text/select/date fields
        requiredFields.forEach(field => {
          const element = document.getElementById(field) || document.querySelector(`[name="${field}"]`);
          if (!element || !element.value.trim()) {
            element.style.borderColor = '#e74c3c'; // Red border for error
            isValid = false;
          } else {
            element.style.borderColor = ''; // Remove error highlight
          }
        });
        
        if (!isValid) {
          alert('Please fill all required fields');
          return false;
        }
        
        // 2. Validate date sequence
        if (!validateStep1Dates()) {
          return false;
        }
        
        // 3. Validate gender (radio buttons)
        const genderSelected = document.querySelector('input[name="gender"]:checked');
        if (!genderSelected) {
          // Highlight the gender radio group
          document.querySelectorAll('[name="gender"]').forEach(radio => {
            radio.closest('.radio-group').style.border = '1px solid #e74c3c';
            radio.closest('.radio-group').style.padding = '5px';
            radio.closest('.radio-group').style.borderRadius = '4px';
          });
          alert('Please select a gender');
          return false;
        }
        
        // 4. Validate CNIC format
        const cnicField = document.getElementById('cnicNumber');
        if (cnicField && !/^\d{5}-\d{7}-\d{1}$/.test(cnicField.value)) {
          cnicField.style.borderColor = '#e74c3c';
          alert('CNIC must be in format: XXXXX-XXXXXXX-X');
          return false;
        }
        
        // 5. Validate mobile number
        const mobileField = document.getElementById('mobileNumber');
        if (mobileField && !/^03\d{9}$/.test(mobileField.value)) {
          mobileField.style.borderColor = '#e74c3c';
          alert('Mobile must start with 03 and be 11 digits (e.g., 03123456789)');
          return false;
        }
      }
      
      // Move to next step if validation passes
      showStep(step + 1);
    }

    function prevStep(step) {
      showStep(step - 1);
    }

    // Add event listeners for the date fields to validate when they change
    document.addEventListener('DOMContentLoaded', function() {
      const appointmentDate = document.getElementById('appointmentDate');
      const promotionDate = document.getElementById('promotionDate');
      const timeScaleDate = document.getElementById('timeScaleDate');
      
      if (appointmentDate && promotionDate) {
        promotionDate.addEventListener('change', function() {
          validateEmploymentDates();
        });
      }
      
      if (appointmentDate && timeScaleDate) {
        timeScaleDate.addEventListener('change', function() {
          validateEmploymentDates();
        });
      }
    });

    // Initialize the form
    document.addEventListener('DOMContentLoaded', function() {
      // Initialize progress bar
      document.getElementById('progressBar').style.width = '0%';
      
      // Add event listeners for required fields
      const requiredFields = document.querySelectorAll('[required]');
      requiredFields.forEach(field => {
        field.addEventListener('input', function() {
          if (this.value.trim()) {
            this.style.borderColor = '';
          }
        });
      });
    });
  </script>

  <script>
    // Automatic Division/Grade Calculation
    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="secondary_obtained_marks"]').value;
      const interMarks = document.querySelector('input[name="higher_secondary_obtained_marks"]').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);
      }
    }

    function validateSubjects() {
      let isValid = true;
      
      // Check at least one subject is selected
      for (let i = 1; i <= 10; i++) {
        const subject = document.getElementById(`subject${i}`).value;
        const classVal = document.getElementById(`class${i}`).value;
        const periods = document.getElementById(`period${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);
      }
    }

    function validatePromotions() {
      let isValid = true;
      const promotionDates = [];
      
      // Check all promotion entries
      for (let i = 1; i <= 5; i++) {
        const prevDesig = document.getElementById(`previousDesignation${i}`).value;
        const prevScale = document.getElementById(`previousScale${i}`).value;
        const newDesig = document.getElementById(`newDesignation${i}`).value;
        const newScale = document.getElementById(`newScale${i}`).value;
        const proDate = document.getElementById(`promotionDate${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);
      }
    }
  </script>

  <script>
    // General date validation - prevents future dates
    function validateDateInput(dateInput) {
      if (!dateInput.value) return true;
      
      const selectedDate = new Date(dateInput.value);
      const today = new Date();
      
      // Compare dates without time components
      selectedDate.setHours(0, 0, 0, 0);
      today.setHours(0, 0, 0, 0);
      
      if (selectedDate > today) {
        alert("You cannot select a date in the future!");
        dateInput.value = '';
        dateInput.focus();
        return false;
      }
      return true;
    }

    // Special validation for birth date
    function validateBirthDate(dateInput) {
      if (!dateInput.value) return true;
      
      const selectedDate = new Date(dateInput.value);
      const today = new Date();
      
      // Compare dates without time components
      selectedDate.setHours(0, 0, 0, 0);
      today.setHours(0, 0, 0, 0);
      
      // Minimum age 18 years
      const minDate = new Date();
      minDate.setFullYear(today.getFullYear() - 18);
      minDate.setHours(0, 0, 0, 0);
      
      if (selectedDate > today) {
        alert("Date of birth cannot be in the future!");
        dateInput.value = '';
        dateInput.focus();
        return false;
      } else if (selectedDate > minDate) {
        alert("Employee must be at least 18 years old!");
        dateInput.value = '';
        dateInput.focus();
        return false;
      }
      return true;
    }

    // Initialize date validations when DOM is loaded
    document.addEventListener('DOMContentLoaded', function() {
      // General date validation for all date inputs
      const dateInputs = document.querySelectorAll('input[type="date"]');
      dateInputs.forEach(input => {
        input.addEventListener('change', function() {
          validateDateInput(this);
        });
      });
      
      // Special validation for birth date
      const birthDateInput = document.getElementById('birthDate');
      if (birthDateInput) {
        birthDateInput.addEventListener('change', function() {
          if (validateBirthDate(this)) {
            calculateRetirementDate();
          }
        });
      }
      
      // Add validation to dynamically generated date inputs in tables
      document.querySelectorAll('.date-input').forEach(input => {
        input.addEventListener('change', function() {
          validateDateInput(this);
        });
      });
      
      // Set max date attribute to today for all date inputs
      const today = new Date().toISOString().split('T')[0];
      dateInputs.forEach(input => {
        input.setAttribute('max', today);
      });
      
      // Also set max date for dynamically generated date inputs
      document.querySelectorAll('.date-input').forEach(input => {
        input.setAttribute('max', today);
      });
    });
  </script>
  <script src="district_script.js"></script>
</body>
</html>