<?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);
    }

    #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;
      }
    }
  </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">
  <!-- 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="tchpic" class="file-input-label">
    <i class="fas fa-camera"></i> Upload Photo
  </label>
  <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>

<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="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>

<script>
// Cache existing personal numbers
let existingNumbersCache = [];

document.getElementById('personalno').addEventListener('input', function() {
  const personalNo = this.value;
  const statusElement = document.getElementById('personalno-status');
  
  // Clear previous status immediately
  statusElement.textContent = "";
  this.setCustomValidity('');
  
  // Only check when we have exactly 8 digits
  if (personalNo.length === 8) {
    // First check cache if available
    if (existingNumbersCache.includes(personalNo)) {
      showDuplicateError(statusElement);
      return;
    }
    
    // Show checking status
    statusElement.textContent = "Checking...";
    statusElement.style.color = "#007bff";
    
    // AJAX check with timeout
    const xhr = new XMLHttpRequest();
    xhr.timeout = 2000; // 2 second timeout
    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
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();
  }
});
</script>



  <div class="form-col">
    <label for="tename" class="required-field">Full Name</label>
    <input id="tename" name="tename" type="text" 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>

<script>
// Cache existing CNICs (if preloaded)
let existingCNICsCache = [];

function formatCNIC(input) {
  // Remove all non-digit characters
  let value = input.value.replace(/\D/g, '');
  
  // Apply formatting
  if (value.length > 5) {
    value = value.substring(0, 5) + '-' + value.substring(5);
  }
  if (value.length > 13) {
    value = value.substring(0, 13) + '-' + value.substring(13);
  }
  
  // Limit to 15 characters (13 digits + 2 hyphens)
  if (value.length > 15) {
    value = value.substring(0, 15);
  }
  
  input.value = value;
  
  // Validate and check duplicates when complete
  const cnicDigits = value.replace(/\D/g, '');
  const statusElement = document.getElementById('cnic-status');
  
  if (cnicDigits.length === 13) {
    input.setCustomValidity('');
    checkCNICDuplicate(value); // Check for duplicates
  } else {
    input.setCustomValidity('CNIC must be exactly 13 digits');
    statusElement.textContent = "";
  }
}

function checkCNICDuplicate(cnic) {
  const statusElement = document.getElementById('cnic-status');
  
  // First check cache
  if (existingCNICsCache.includes(cnic)) {
    showCNICError(statusElement);
    return;
  }
  
  statusElement.textContent = "Checking CNIC...";
  statusElement.style.color = "#007bff";
  
  // AJAX check with timeout
  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 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();
  }
});
</script>
</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>
    <input id="tebirthday" name="tebirthday" type="date" required onchange="calculateRetirementDate()">
  </div>
  <div class="form-col">
    <label for="teretirement" class="required-field">Tentative Date of Retirement</label>
    <input id="teretirement" name="teretirement" type="date" required readonly>
  </div>
</div>

<script>
function calculateRetirementDate() {
  const birthDateInput = document.getElementById('tebirthday');
  const retirementDateInput = document.getElementById('teretirement');
  
  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="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
        // 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="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="validatePakNumber(this, 'mobile'); syncWhatsAppNumber(this)"
           onkeypress="return isNumberKey(event)"
           onblur="checkNumberStart(this)">
    <div class="error-message" id="temobno-error" style="color:red; display:none;">❌ Number must start with 03</div>
  </div>
  <div class="form-col">
    <label for="tewano">WhatsApp No (You can edit it, if WhatsApp is on anyother 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="validatePakNumber(this, 'whatsapp')"
           onkeypress="return isNumberKey(event)"
           onblur="checkNumberStart(this)">
    <div class="error-message" id="tewano-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('tewano');
  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('temobno').addEventListener('change', function() {
    syncWhatsAppNumber(this);
  });
});
</script>

<!-- 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">DDO Code</label>
    <input id="teddono" name="teddono" type="text">
  </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
        // 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="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
      // 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="unionCouncil" 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="iaa" class="required-field">Initially Appointed As</label>
	    <select id="iaa" name="iaa" 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="doapp" class="required-field">Date of Appointment</label>
        <input id="doapp" name="doapp" type="date" required>
    </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
		
        // 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="dojcp" class="required-field">Date of Promotion</label>
        <input id="dojcp" name="dojcp" type="date" required>
    </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
            // 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="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
        // 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="tetimes" class="required-field">Date of Current Time Scale</label>
        <input id="tetimes" name="tetimes" type="date" required>
    </div>
<div class="form-col">
    <label for="emis-select" class="required-field">Presently Working Institute EMIS Code</label>
    <select id="emis-select" name="workin" 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>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    // Set up datepicker for all date fields
    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, // This prevents future date selection
            showOtherMonths: true,
            selectOtherMonths: true,
            beforeShowDay: function(date) {
                // Disable future dates
                var today = new Date();
                today.setHours(0, 0, 0, 0);
                return [date <= today, ""];
            },
            onSelect: function(dateText, inst) {
                // Clear any error messages when a date is selected
                const errorElement = document.getElementById(this.id + '-error');
                if (errorElement) errorElement.style.display = 'none';
                
                if (fieldId === 'tebirthday') {
                    calculateRetirementDate();
                }
                
                // Validate the date when selected
                validateDateFormat(this);
            },
            onClose: function(dateText, inst) {
                // Validate date when datepicker is closed
                validateDateFormat(this);
            }
        }).on('keydown', function(e) {
            // Close datepicker when Enter key is pressed
            if (e.keyCode === 13) {
                $(this).datepicker('hide');
                validateDateFormat(this);
                
                if (fieldId === 'tebirthday') {
                    calculateRetirementDate();
                }
                
                // Prevent form submission
                e.preventDefault();
                return false;
            }
        }).on('blur', function() {
            // Validate date when field loses focus
            validateDateFormat(this);
            
            if (fieldId === 'tebirthday') {
                calculateRetirementDate();
            }
        });
    });
});
</script>

<script>
// Real-time validation for manual date input
document.querySelectorAll('input[type="text"][pattern="\\d{2}-\\d{2}-\\d{4}"]').forEach(input => {
    input.addEventListener('input', function() {
        const value = this.value;
        
        // Only validate when we have a complete date
        if (value.length === 10) {
            validateDateFormat(this);
        }
    });
});

</script>

</div>

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

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $('#emis-select').change(function() {
        const schoolName = $(this).find('option:selected').data('school');
        $('#workin1').val(schoolName || ''); // Show school name or clear if empty
    });
});
</script>
</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="tesscpass" type="date" class="date-input"></td>
        <td><input name="tesscsub" type="text" class="subject-input"></td>
        <td><input name="tesscuni" type="text" class="board-input"></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><input name="tehscpass" type="date" class="date-input"></td>
        <td><input name="tehscsub" type="text" class="subject-input"></td>
        <td><input name="tehscuni" type="text" class="board-input"></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><input name="tebspass" type="date" class="date-input"></td>
        <td><input name="tebssub" type="text" class="subject-input"></td>
        <td><input name="tebsuni" type="text" class="board-input"></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><input name="temapass" type="date" class="date-input"></td>
        <td><input name="temasub" type="text" class="subject-input"></td>
        <td><input name="temauni" type="text" class="board-input"></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><input name="temapass2" type="date" class="date-input"></td>
        <td><input name="temasub2" type="text" class="subject-input"></td>
        <td><input name="temauni2" type="text" class="board-input"></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><input name="temapass3" type="date" class="date-input"></td>
        <td><input name="temasub3" type="text" class="subject-input"></td>
        <td><input name="temauni3" type="text" class="board-input"></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><input name="temphillpass" type="date" class="date-input"></td>
        <td><input name="temphillsub" type="text" class="subject-input"></td>
        <td><input name="temphilluni" type="text" class="board-input"></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><input name="tephdpass" type="date" class="date-input"></td>
        <td><input name="tephdsub" type="text" class="subject-input"></td>
        <td><input name="tephduni" type="text" class="board-input"></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><input name="teotherpass" type="date" class="date-input"></td>
        <td><input name="teothersub" type="text" class="subject-input"></td>
        <td><input name="teotheruni" type="text" class="board-input"></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>
  
  <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>

<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="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);
  }
}
</script>

<!-- 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="teptpass" type="date" class="date-input"></td>
        <td><input name="teptis" type="text" class="institution-input"></td>
        <td><input name="tepttot" type="number" class="total-marks" value="1000"></td>
        <td><input name="teptom" type="number" min="0" class="obtained-marks"></td>
        <td><input name="teptdiv" type="text" class="division-grade" readonly></td>
      </tr>
      <tr>
        <td>B.Ed/BS.Ed</td>
        <td><input name="tebedpass" type="date" class="date-input"></td>
        <td><input name="tebedis" type="text" class="institution-input"></td>
        <td><input name="tebedtot" type="number" class="total-marks" value="1000"></td>
        <td><input name="tebedom" type="number" min="0" class="obtained-marks"></td>
        <td><input name="tebeddiv" type="text" class="division-grade" readonly></td>
      </tr>
      <tr>
        <td>M.Ed/M.A Education</td>
        <td><input name="temedpass" type="date" class="date-input"></td>
        <td><input name="temedis" type="text" class="institution-input"></td>
        <td><input name="temedtot" type="number" class="total-marks" value="1000"></td>
        <td><input name="temedom" type="number" min="0" class="obtained-marks"></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><input name="teo1pass" type="date" class="date-input"></td>
        <td><input name="teo1is" type="text" class="institution-input"></td>
        <td><input name="teo1tot" type="number" class="total-marks" value=""></td>
        <td><input name="teo1om" type="number" min="0" class="obtained-marks"></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><input name="teo2pass" type="date" class="date-input"></td>
        <td><input name="teo2is" type="text" class="institution-input"></td>
        <td><input name="teo2tot" type="number" class="total-marks" value=""></td>
        <td><input name="teo2om" type="number" min="0" class="obtained-marks"></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><input name="teo3pass" type="date" class="date-input"></td>
        <td><input name="teo3is" type="text" class="institution-input"></td>
        <td><input name="teo3tot" type="number" class="total-marks" value=""></td>
        <td><input name="teo3om" type="number" min="0" class="obtained-marks"></td>
        <td><input name="teo3div" 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="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
      // 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="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>

<script>
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);
  }
}
</script>


<!-- 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="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><input id="teprodate'.$i.'" name="teprodate'.$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>

<script>
function validatePromotions() {
  let isValid = true;
  const promotionDates = [];
  
  // 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);
  }
}
</script>

<!-- 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 "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="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><input id="tetdate'.$i.'" name="tetdate'.$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="step_7">
            <i class="fas fa-check"></i> Submit Form
          </button>
        </div>
      </div>
    </form>
  </div>

<script>
  // Enhanced form submission with AJAX
  document.getElementById('teacherForm').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('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', 'temobno', 'district', 'tehsil', 'constituency',
      'unionCouncil', 'iaa', 'doapp', 'tecudesig', 'tecups', 'dojcp',
      'current_time_scale', 'tetimes', 'workin'
    ];
    
    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';
      }
    });
  }

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(`tetfrom${i}`).value;
    const toSchool = document.getElementById(`tetto${i}`).value;
    const reason = document.getElementById(`tetreason${i}`).value;
    const transferDate = document.getElementById(`tetdate${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;
    }

// Enhanced employment date validation
function validateEmploymentDates() {
    const dateFields = ['tebirthday', 'doapp', 'dojcp', 'tetimes', 'wtis'];
    let allValid = true;
    
    // First validate all date formats
    dateFields.forEach(fieldId => {
        if (!validateDateFormat(fieldId)) {
            allValid = false;
        }
    });
    
    if (!allValid) return false;
    
    // Convert text dates to Date objects for comparison
    function parseDDMMYYYY(dateStr) {
        if (!dateStr || dateStr.length !== 10) 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;
        const year = parseInt(parts[2], 10);
        
        return new Date(year, month, day);
    }

    const dob = parseDDMMYYYY(document.getElementById('tebirthday').value);
    const appointment = parseDDMMYYYY(document.getElementById('doapp').value);
    const promotion = parseDDMMYYYY(document.getElementById('dojcp').value);
    const timeScale = parseDDMMYYYY(document.getElementById('tetimes').value);
    const workingSince = parseDDMMYYYY(document.getElementById('wtis').value);

    // Normalize times
    [dob, appointment, promotion, timeScale, workingSince].forEach(d => {
        if (d) d.setHours(0, 0, 0, 0);
    });

    // Validate chronological order
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    // Check DOB is reasonable (not too old or young)
    if (dob) {
        const minDOB = new Date();
        minDOB.setFullYear(minDOB.getFullYear() - 100); // Max 100 years old
        
        if (dob < minDOB) {
            alert("Date of birth seems unrealistic (over 100 years ago)!");
            document.getElementById('tebirthday').focus();
            return false;
        }
        
        const maxDOB = new Date();
        maxDOB.setFullYear(maxDOB.getFullYear() - 18); // At least 18 years old
        
        if (dob > maxDOB) {
            alert("Employee must be at least 18 years old!");
            document.getElementById('tebirthday').focus();
            return false;
        }
    }

    // Validate age at appointment (DOB + 18 years <= Appointment)
    if (dob && appointment) {
        const minAppointmentDate = new Date(dob);
        minAppointmentDate.setFullYear(dob.getFullYear() + 18);
        
        if (appointment < minAppointmentDate) {
            alert("Employee must be at least 18 years old at the time of appointment!");
            document.getElementById('doapp').focus();
            return false;
        }
    }

    // Check appointment before promotion
    if (appointment && promotion && appointment > promotion) {
        alert("Date of Appointment cannot be after Date of Promotion!");
        document.getElementById('dojcp').focus();
        return false;
    }

    // Check appointment before time scale
    if (appointment && timeScale && appointment > timeScale) {
        alert("Date of Appointment cannot be after Date of Current Time Scale!");
        document.getElementById('tetimes').focus();
        return false;
    }

    // Check appointment before working since
    if (appointment && workingSince && appointment > workingSince) {
        alert("Date of Appointment cannot be after Working Since date!");
        document.getElementById('wtis').focus();
        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 = [
            'personalno', 'tename', 'tefname', 'tecnic', 'tege',
            'tebirthday', 'teretirement', 'teemq', 'temobno',
            'district', 'tehsil', 'constituency', 'unionCouncil',
            'iaa', 'doapp', 'tecudesig', 'dojcp', 'tecups', 
             'current_time_scale', 'tetimes', 'workin' , 'workin1'
        ];
        
        let isValid = true;
        
        // 1. Validate required text/select/date fields
        requiredFields.forEach(field => {
            const element = document.getElementById(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="tege"]:checked');
        if (!genderSelected) {
            // Highlight the gender radio group
            document.querySelectorAll('[name="tege"]').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('tecnic');
        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('temobno');
        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('doapp');
    const promotionDate = document.getElementById('dojcp');
    const timeScaleDate = document.getElementById('tetimes');
    
    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>
// 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('tebirthday');
    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>