<!-- 

**File Structure:**
- emp1.php (Personal Information)
- emp2.php (Academic Qualifications)
- emp3.php (Professional Qualifications)
- emp4.php (In-Service Training)
- emp5.php (Subjects Teaching)
- emp6.php (Promotion History)
- emp7.php (Transfer History)

Here's the first file (emp1.php):

-->

<?php
require_once 'session_config_emp.php';
include_once 'connect.php';

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check if session is valid
if (!validateUserSession()) {
    // Redirect to login
    header('Location: login_emp.php');
    exit();
}

// Customize for each step
$stepNumber = 1;
$nextFile = 'emp2.php';
$previousFile = 'emp1.php';

$formData = $_SESSION['form_data'] ?? [];
$csrf_error = '';

// Get employee data from session (from registrations_emp table)
$employeeData = $_SESSION['employee_data'] ?? [];

// If employee data is not in session, try to fetch it
if (empty($employeeData) && isset($_SESSION['cnic'])) {
    $stmt = $conn->prepare("SELECT full_name, emp_numb, cnic, dob FROM registrations_emp WHERE cnic = ?");
    $stmt->bind_param("s", $_SESSION['cnic']);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $employeeData = $result->fetch_assoc();
        $_SESSION['employee_data'] = $employeeData;
    }
    $stmt->close();
}

// Format the date from database (YYYY-MM-DD) to DD-MM-YYYY for display
function formatDateForDisplay($dbDate) {
    if (empty($dbDate) || $dbDate == '0000-00-00') return '';
    $date = DateTime::createFromFormat('Y-m-d', $dbDate);
    return $date ? $date->format('d-m-Y') : '';
}

// Calculate retirement date (60 years from DOB)
function calculateRetirementDateFromDOB($dob) {
    if (empty($dob) || $dob == '0000-00-00') return '';
    
    try {
        $date = DateTime::createFromFormat('Y-m-d', $dob);
        if (!$date) return '';
        
        // Add 60 years
        $date->modify('+60 years');
        // Subtract 1 day (retirement is day before 60th birthday)
        $date->modify('-1 day');
        
        return $date->format('d-m-Y');
    } catch (Exception $e) {
        return '';
    }
}

// If employee data exists, pre-calculate retirement date
if (isset($employeeData['dob']) && !empty($employeeData['dob'])) {
    $retirementDate = calculateRetirementDateFromDOB($employeeData['dob']);
    // Store in formData for display
    if (!isset($formData['teretirement']) && $retirementDate) {
        $formData['teretirement'] = $retirementDate;
    }
}

// Get selected EMIS data for search input pre-filling
$selectedEMISData = null;
if (isset($formData['workin']) && !empty($formData['workin'])) {
    $stmt = $conn->prepare("SELECT emis_code, school_name FROM school_emis WHERE emis_code = ?");
    $stmt->bind_param("s", $formData['workin']);
    $stmt->execute();
    $result = $stmt->get_result();
    $selectedEMISData = $result->fetch_assoc();
    $stmt->close();
}

// Handle form submission for current step
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["step_$stepNumber"])) {
    if (!isset($_POST['csrf_token']) || !validateCsrfToken($_POST['csrf_token'])) {
        $csrf_error = "Security token expired. Please try again.";
        regenerateCsrfToken();
    } else {
        // ✅ FIX: Handle photo upload FIRST and store result
        $photoResult = handlePhotoUploadWithSession();
        
        // Store all form data in session
        $postData = $_POST;
        unset($postData['csrf_token']);
        unset($postData["step_$stepNumber"]);
        
        // ✅ CRITICAL FIX: Store photo info in session
        if ($photoResult['success']) {
            $postData['photo_path'] = $photoResult['file_path'];
            $postData['photo_uploaded'] = 'yes';
            $postData['photo_filename'] = $photoResult['file_name'];
        } else {
            $postData['photo_path'] = 'uploads/employee_photos/default.jpg';
            $postData['photo_uploaded'] = 'no';
            // Don't store error in session as it might cause issues
        }
        
        $_SESSION['form_data'] = array_merge($formData, $postData);
        
        // ✅ DEBUG: Log what we're storing (FROM CODE 2)
        error_log("=== STEP 1 COMPLETED ===");
        error_log("Personal No: " . ($_SESSION['form_data']['personalno'] ?? 'NOT SET'));
        error_log("Photo Path: " . ($_SESSION['form_data']['photo_path'] ?? 'NOT SET'));
        error_log("Photo Uploaded: " . ($_SESSION['form_data']['photo_uploaded'] ?? 'NOT SET'));
        error_log("Session keys: " . implode(', ', array_keys($_SESSION['form_data'])));
        
        regenerateCsrfToken();
        
        // Redirect to next step
        header("Location: $nextFile");
        exit();
    }
}

function handlePhotoUploadWithSession() {
    error_log("=== PHOTO UPLOAD PROCESS START ===");
    
    if (!isset($_FILES['tchpic']) || $_FILES['tchpic']['error'] !== UPLOAD_ERR_OK) {
        $error = $_FILES['tchpic']['error'] ?? 'No file uploaded';
        error_log("No file or upload error: " . $error);
        return ['success' => false, 'message' => 'No photo uploaded'];
    }
    
    $file = $_FILES['tchpic'];
    $personal_no = $_POST['personalno'] ?? '';
    
    if (empty($personal_no)) {
        error_log("No personal number provided");
        return ['success' => false, 'message' => 'Personal number required'];
    }
    
    error_log("Uploading file for personal no: " . $personal_no);
    error_log("File info: " . $file['name'] . ", " . $file['size'] . " bytes, " . $file['type']); // FROM CODE 2
    
    // Create upload directory
    $uploadDir = "uploads/employee_photos/";
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0755, true);
        error_log("Created upload directory: " . $uploadDir); // FROM CODE 2
    }
    
    // Generate filename using personal number
    $sanitizedPersonalNo = preg_replace('/[^0-9]/', '', $personal_no);
    $filename = $sanitizedPersonalNo . '.jpg';
    $filepath = $uploadDir . $filename;
    
    error_log("Target file: " . $filepath); // FROM CODE 2
    
    // Move uploaded file first
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        error_log("✅ File moved successfully to: " . $filepath);
        
        // Resize the image
        $resizeResult = resizeImageToExactSize($filepath, $filepath);
        if ($resizeResult['success']) {
            error_log("✅ Image resized successfully to 450x600 pixels");
            error_log("Final file size: " . filesize($filepath) . " bytes"); // FROM CODE 2
            
            return [
                'success' => true, 
                'file_path' => $filepath,
                'file_name' => $filename,
                'file_size' => filesize($filepath)
            ];
        } else {
            error_log("❌ Resize failed: " . $resizeResult['message']); // FROM CODE 2
            // Still return success since the file was uploaded
            return [
                'success' => true, 
                'file_path' => $filepath,
                'file_name' => $filename,
                'file_size' => filesize($filepath)
            ];
        }
    } else {
        error_log("❌ Failed to move uploaded file");
        return ['success' => false, 'message' => 'Failed to save uploaded file'];
    }
}

function resizeImageToExactSize($sourcePath, $targetPath) {
    try {
        error_log("Resizing image to 450x600 pixels: " . $sourcePath); // FROM CODE 2
        
        $imageInfo = getimagesize($sourcePath);
        if (!$imageInfo) {
            throw new Exception('Invalid image file');
        }
        
        $originalWidth = $imageInfo[0];
        $originalHeight = $imageInfo[1];
        $mimeType = $imageInfo['mime'];
        
        error_log("Original dimensions: {$originalWidth}x{$originalHeight}, Type: {$mimeType}"); // FROM CODE 2
        
        // Create source image
        switch ($mimeType) {
            case 'image/jpeg':
            case 'image/jpg':
                $sourceImage = imagecreatefromjpeg($sourcePath);
                break;
            case 'image/png':
                $sourceImage = imagecreatefrompng($sourcePath);
                break;
            default:
                throw new Exception('Unsupported image type: ' . $mimeType);
        }
        
        if (!$sourceImage) {
            throw new Exception('Could not create image from source');
        }
        
        // Create new image with exact dimensions
        $newWidth = 450;
        $newHeight = 600;
        $newImage = imagecreatetruecolor($newWidth, $newHeight);
        
        // Fill with white background
        $white = imagecolorallocate($newImage, 255, 255, 255);
        imagefill($newImage, 0, 0, $white);
        
        // Calculate scaling to fit without cropping
        $widthRatio = $newWidth / $originalWidth;
        $heightRatio = $newHeight / $originalHeight;
        $scale = min($widthRatio, $heightRatio);
        
        $scaledWidth = round($originalWidth * $scale);
        $scaledHeight = round($originalHeight * $scale);
        
        // Calculate position to center the image
        $x = round(($newWidth - $scaledWidth) / 2);
        $y = round(($newHeight - $scaledHeight) / 2);
        
        error_log("Scaled dimensions: {$scaledWidth}x{$scaledHeight}, Position: {$x},{$y}"); // FROM CODE 2
        
        // Resize and center the image
        imagecopyresampled(
            $newImage, $sourceImage,
            $x, $y, 0, 0,
            $scaledWidth, $scaledHeight,
            $originalWidth, $originalHeight
        );
        
        // Save as high quality JPEG
        if (imagejpeg($newImage, $targetPath, 90)) {
            imagedestroy($sourceImage);
            imagedestroy($newImage);
            error_log("✅ Resized image saved successfully: " . $targetPath); // FROM CODE 2
            return ['success' => true];
        } else {
            throw new Exception('Failed to save resized image');
        }
        
    } catch (Exception $e) {
        error_log("Resize error: " . $e->getMessage());
        return ['success' => false, 'message' => $e->getMessage()];
    }
}

$currentToken = $_SESSION['csrf_token'];
?>

<!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 - Step 1</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">
      <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
      <link rel="stylesheet" href="css/emp_form.css">
      <style>
        input[readonly] {
            background-color: #f5f5f5 !important;
            cursor: not-allowed !important;
            color: #666 !important;
            border-color: #ddd !important;
        }

        input[readonly]:focus {
            border-color: #ddd !important;
            box-shadow: none !important;
        }
        
        .warning-message {
            color: #ff9800;
            font-size: 0.9em;
            margin-top: 5px;
            display: none;
        }
        
        .retirement-field-container {
            position: relative;
        }
        
        .retirement-field-container .datepicker-trigger {
            display: none !important;
        }
        
        .auto-filled-note {
            color: #666;
            font-size: 0.85em;
            margin-top: 5px;
            font-style: italic;
        }
        
        .info-box {
            background-color: #e8f4fd;
            border-left: 4px solid #3498db;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
        
        .info-box h4 {
            margin-top: 0;
            color: #2c3e50;
        }
        
        .info-box p {
            margin-bottom: 10px;
        }
        
        .locked-field {
            background-color: #f9f9f9;
            border: 1px solid #e0e0e0;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        
        .locked-field label {
            font-weight: bold;
            color: #2c3e50;
        }
        
        .locked-field .field-value {
            font-size: 1.1em;
            color: #333;
            padding: 5px 0;
        }
        
        /* Searchable Dropdown Styles - SIMPLE */
        .searchable-dropdown {
            position: relative;
            width: 100%;
        }

        .dropdown-search-container {
            position: relative;
            margin-bottom: 5px;
        }

        .dropdown-search-input {
            width: 100%;
            padding: 10px 40px 10px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
            transition: border-color 0.3s;
            background-color: white;
            color: #333;
        }

        .dropdown-search-input:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }

        .search-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #666;
            pointer-events: none;
            z-index: 1;
        }

        .search-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            max-height: 300px;
            overflow-y: auto;
            background: white;
            border: 1px solid #ddd;
            border-top: none;
            border-radius: 0 0 4px 4px;
            z-index: 1000;
            display: none;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            margin-top: -1px;
        }

        .search-result-item {
            padding: 10px 12px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
            transition: background-color 0.2s;
            font-size: 14px;
        }

        .search-result-item:hover {
            background-color: #f5f9ff;
        }

        .search-result-item.selected {
            background-color: #e8f4fd;
            border-left: 3px solid #3498db;
        }

        .search-result-item .emis-code {
            font-weight: bold;
            color: #2c3e50;
            display: block;
            margin-bottom: 2px;
        }

        .search-result-item .school-name {
            color: #666;
            font-size: 12px;
            display: block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .no-results {
            padding: 15px;
            text-align: center;
            color: #999;
            font-style: italic;
            font-size: 14px;
        }

        .clear-search {
            position: absolute;
            right: 35px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #999;
            cursor: pointer;
            padding: 0;
            display: none;
            font-size: 20px;
            line-height: 1;
            width: 20px;
            height: 20px;
            text-align: center;
        }

        .clear-search:hover {
            color: #e74c3c;
            background-color: #f5f5f5;
            border-radius: 50%;
        }
        
        .error-message {
            color: #e74c3c;
            font-size: 0.85em;
            margin-top: 5px;
            display: none;
        }

      </style>
   </head>
   <body> 
   
	<!-- Floating Logout Button -->
<div class="floating-logout-btn" style="position: fixed; bottom: 20px; right: 20px; z-index: 9999;">
    <button type="button" class="btn btn-danger shadow-lg" onclick="confirmLogout()" 
            style="border-radius: 50px; padding: 12px 25px; box-shadow: 0 4px 15px rgba(220, 53, 69, 0.4); font-weight: 600; transition: all 0.3s;">
        <i class="fas fa-sign-out-alt" style="margin-right: 8px;"></i> Logout
    </button>
</div>

      <div class="form-container">
         <div class="form-header">
            <h1><i class="fas fa-user-tie"></i> Employee Profile Form - (Step 1 of 7)</h1>
         </div>
         
         <!-- Information Box -->
         <div class="info-box">
            <h4><i class="fas fa-info-circle"></i> Profile Completion Notice</h4>
            <p>
                Your basic information (Personal Number, Full Name, CNIC, and Date of Birth) has been automatically filled from your registration data. 
                These fields cannot be modified. If you find any errors in these fields, please contact the system administrator.
            </p>
            <p style="margin-bottom: 0;">
                <strong>Note:</strong> Date of retirement is automatically calculated as 60 years from your date of birth.
            </p>
        </div>
        
         <div class="progress-container">
            <div class="progress-bar" id="progressBar" style="width: 0%"></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" method="POST" enctype="multipart/form-data">
					<input type="hidden" name="csrf_token" value="<?php echo $currentToken; ?>">
					<input type="hidden" name="step_1" value="1">
            
            <!-- Step 1: Personal Information -->
            <div class="form-step active" id="step-1">
               <h2 class="section-title"><i class="fas fa-user"></i> Personal Information</h2>
<div class="photo-upload">
    <div id="fileDisplayArea">
        <i class="fas fa-user-circle" style="font-size: 60px; color: #ccc;"></i>
    </div>
    <div>
        <label for="tchpic" class="file-input-label">
        <i class="fas fa-camera"></i> 
        <span class="required-field">Upload Photo</span>
        </label>
    </div>
    <input id="tchpic" name="tchpic" type="file" accept="image/jpeg, image/png" onchange="validateAndPreviewImage(this)" required>
    <p class="file-requirements" style="font-size: 12px; color: #666; margin-top: 8px;">
        <strong>Photo Requirements:</strong><br>
        • Format: JPEG or PNG <br>
        • Size: 2MB Maximum <br>
    </p>
    <div id="photo-error" style="color: red; display: none; margin-top: 5px;">Please upload a valid photo</div>
</div>
               <!-- Personal Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label for="personalno" class="required-field">A/C Office/AG Personal #</label>
                     <input
                        id="personalno"
                        name="personalno"
                        type="text"
                        required
                        maxlength="8"
                        minlength="8"
                        inputmode="numeric"
                        title="Personal number from registration"
                        pattern="[0-9]{8}"
                        value="<?php echo isset($employeeData['emp_numb']) ? htmlspecialchars($employeeData['emp_numb']) : (isset($formData['personalno']) ? htmlspecialchars($formData['personalno']) : ''); ?>"
                        readonly
                        style="background-color: #f5f5f5; cursor: not-allowed;">
                  </div>
                  <div class="form-col">
                     <label for="tename" class="required-field">Full Name</label>
                     <input 
                        id="tename" 
                        name="tename" 
                        type="text" 
                        pattern="[^0-9]*" 
                        title="Numbers are not allowed"
                        required
                        value="<?php echo isset($employeeData['full_name']) ? htmlspecialchars($employeeData['full_name']) : (isset($formData['tename']) ? htmlspecialchars($formData['tename']) : ''); ?>"
                        readonly
                        style="background-color: #f5f5f5; cursor: not-allowed;">
                  </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
                        value="<?php echo isset($formData['tefname']) ? htmlspecialchars($formData['tefname']) : ''; ?>">
                  </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="CNIC from registration"
                        maxlength="15"
                        required
                        value="<?php echo isset($employeeData['cnic']) ? htmlspecialchars($employeeData['cnic']) : (isset($formData['tecnic']) ? htmlspecialchars($formData['tecnic']) : ''); ?>"
                        readonly
                        style="background-color: #f5f5f5; cursor: not-allowed;">
                  </div>
               </div>
               <!-- Demographic Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label class="required-field">Gender</label>
                     <div class="radio-group">
                        <label class="radio-option">
                        <input id="tegem" name="tege" type="radio" value="Male" required <?php echo (isset($formData['tege']) && $formData['tege'] == 'Male') ? 'checked' : ''; ?>> Male
                        </label>
                        <label class="radio-option">
                        <input id="tegefem" name="tege" type="radio" value="Female" required <?php echo (isset($formData['tege']) && $formData['tege'] == 'Female') ? 'checked' : ''; ?>> Female
                        </label>
                        <label class="radio-option">
                        <input id="tegeoth" name="tege" type="radio" value="Other" required <?php echo (isset($formData['tege']) && $formData['tege'] == 'Other') ? 'checked' : ''; ?>> 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" <?php echo (isset($formData['temarst']) && $formData['temarst'] == 'Married') ? 'checked' : ''; ?>> Married
                        </label>
                        <label class="radio-option">
                        <input id="temarstum" name="temarst" type="radio" value="Un-Married" <?php echo (isset($formData['temarst']) && $formData['temarst'] == 'Un-Married') ? 'checked' : ''; ?>> Unmarried
                        </label>
                        <label class="radio-option">
                        <input id="temarstdiv" name="temarst" type="radio" value="Divorced" <?php echo (isset($formData['temarst']) && $formData['temarst'] == 'Divorced') ? 'checked' : ''; ?>> Divorced
                        </label>
                        <label class="radio-option">
                        <input id="temarstwid" name="temarst" type="radio" value="Widow" <?php echo (isset($formData['temarst']) && $formData['temarst'] == 'Widow') ? 'checked' : ''; ?>> Widow
                        </label>
                     </div>
                  </div>
               </div>
               <!-- Date Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label for="tebirthday" class="required-field">Date of Birth</label>
                     <div class="date-input-container">
                        <input 
                            id="tebirthday" 
                            name="tebirthday" 
                            type="text" 
                            class="date-field"
                            placeholder="DD-MM-YYYY"
                            maxlength="10"
                            pattern="\d{2}-\d{2}-\d{4}"
                            title="Date of Birth from registration" 
                            required
                            value="<?php echo isset($employeeData['dob']) ? formatDateForDisplay($employeeData['dob']) : (isset($formData['tebirthday']) ? htmlspecialchars($formData['tebirthday']) : ''); ?>"
                            readonly
                            style="background-color: #f5f5f5; cursor: not-allowed;">
                        <span class="datepicker-trigger" style="display: none;">
                            <i class="fas fa-calendar-alt"></i>
                        </span>
                     </div>
                     <div id="tebirthday-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                  </div>
                  <div class="form-col">
                     <label for="teretirement" class="required-field">Tentative Date of Retirement</label>
                     <div class="date-input-container retirement-field-container">
                        <input 
                            id="teretirement" 
                            name="teretirement" 
                            type="text" 
                            class="date-field"
                            placeholder="DD-MM-YYYY"
                            maxlength="10" 
                            pattern="\d{2}-\d{2}-\d{4}" 
                            readonly 
                            required
                            value="<?php echo isset($formData['teretirement']) ? htmlspecialchars($formData['teretirement']) : ''; ?>"
                            style="background-color: #f5f5f5; cursor: not-allowed;">
                        <span class="datepicker-trigger" onclick="return false;">
                        <i class="fas fa-calendar-alt"></i>
                        </span>
                     </div>
                     <div id="teretirement-error" class="error-message">Invalid date format</div>
                     <div class="info-message" style="font-size: 12px; color: #666; margin-top: 5px;">
                        <i class="fas fa-info-circle"></i> Automatically calculated from Date of Birth (Retirement at age 60) 
                     </div>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="tebplace">Birth Place</label>
                     <input id="tebplace" name="tebplace" type="text"
                        value="<?php echo isset($formData['tebplace']) ? htmlspecialchars($formData['tebplace']) : ''; ?>">
                  </div>
                  <div class="form-col">
                     <label for="teemq" class="required-field">Employment Quota</label>
                     <select id="teemq" name="teemq" required>
                     <?php
                        $sql = "SELECT quota_id, quota_type FROM quota ORDER BY quota_id ASC";
                        $result = $conn->query($sql);
                        
                        echo '<option value="" selected disabled>Select Employment Quota</option>';
                        
                        if ($result && $result->num_rows > 0) {
                          while($row = $result->fetch_assoc()) {
                            $selected = (isset($formData['teemq']) && $formData['teemq'] == $row['quota_id']) ? 'selected' : '';
                            echo '<option value="' . htmlspecialchars($row['quota_id']) . '" ' . $selected . '>' 
                                 . htmlspecialchars($row['quota_type']) 
                                 . '</option>';
                          }
                        } else {
                          echo '<option value="">No Employment Quota found</option>';
                        }
                        ?>
                     </select>
                  </div>
               </div>
               <!-- Contact Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label for="temobno" class="required-field">Mobile No</label>
                     <input id="temobno" name="temobno" type="text" 
                        pattern="03[0-9]{9}" 
                        title="Must start with 03 and be 11 digits (e.g., 03123456789)" 
                        maxlength="11" 
                        required
                        oninput="handleMobileInput(this)"
                        onkeypress="return isNumberKey(event)"
                        onblur="validateCompleteNumber(this)"
                        value="<?php echo isset($formData['temobno']) ? htmlspecialchars($formData['temobno']) : ''; ?>">
                     <div class="error-message" id="temobno-error">❌ Must start with 03 and be 11 digits</div>
                  </div>
                  <div class="form-col">
                     <label for="tewano">WhatsApp No (You can edit it if WhatsApp is on another number)</label>
                     <input id="tewano" name="tewano" type="text" 
                        pattern="03[0-9]{9}" 
                        title="Must start with 03 and be 11 digits (e.g., 03123456789)" 
                        maxlength="11"
                        oninput="handleWhatsAppInput(this)"
                        onkeypress="return isNumberKey(event)"
                        onblur="validateCompleteNumber(this)"
                        value="<?php echo isset($formData['tewano']) ? htmlspecialchars($formData['tewano']) : ''; ?>">
                     <div class="error-message" id="tewano-error">❌ Must start with 03 and be 11 digits</div>
                  </div>
               </div>
               <!-- Official Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label for="tegpfno">GPF No</label>
                     <input id="tegpfno" name="tegpfno" type="text"
                        value="<?php echo isset($formData['tegpfno']) ? htmlspecialchars($formData['tegpfno']) : ''; ?>">
                  </div>
                  <div class="form-col">
                     <label for="teddono" class="required-field">DDO Code</label>
                     <input id="teddono" name="teddono" type="text" 
                        maxlength="6"
                        pattern="[A-Za-z]{2}\d{4}"
                        title="First 2 letters followed by 4 digits (e.g., AB1234)" 
                        onkeypress="return allowDdoChars(event)" 
                        onblur="validateDdoCode(this)"
                        placeholder="Enter DDO Code Like AB1234" required
                        value="<?php echo isset($formData['teddono']) ? htmlspecialchars($formData['teddono']) : ''; ?>">
                     <div class="error-message" id="teddono-error">
                        ❌ Must have 2 letters followed by 4 digits (e.g., AB1234)
                     </div>
                  </div>
               </div>
               <!-- Next of Kin Information -->
               <div class="form-row">
                  <div class="form-col">
                     <label for="tenok" class="required-field">Next of Kin (Name)</label>
                     <input id="tenok" name="tenok" type="text"
                        value="<?php echo isset($formData['tenok']) ? htmlspecialchars($formData['tenok']) : ''; ?>" required>
                  </div>
                  <div class="form-col">
                     <label for="tenokre" class="required-field">Relation with Next of Kin</label>
                     <select id="tenokre" name="tenokre" required>
                     <?php
                        // FROM CODE 2: Query with Urdu names
                        $query = "SELECT relationship_id, relationship_name, relationship_name_urdu FROM next_kin ORDER BY relationship_id ASC";
                        $result = $conn->query($query);
                        
                        echo '<option value="" selected disabled>Select Relation</option>';
                        
                        if ($result->num_rows > 0) {
                          while($row = $result->fetch_assoc()) {
                            $selected = (isset($formData['tenokre']) && $formData['tenokre'] == $row['relationship_id']) ? 'selected' : '';
                            echo '<option value="' . htmlspecialchars($row['relationship_id']) . '" ' . $selected . '>' 
                                 . 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"
                        value="<?php echo isset($formData['tevillage']) ? htmlspecialchars($formData['tevillage']) : ''; ?>">
                  </div>
                  <div class="form-col">
                     <label for="tepo">Post Office</label>
                     <input id="tepo" name="tepo" type="text"
                        value="<?php echo isset($formData['tepo']) ? htmlspecialchars($formData['tepo']) : ''; ?>">
                  </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
                           $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()):
                               $selected = (isset($formData['district']) && $formData['district'] == $row['district_id']) ? 'selected' : '';
                           ?>
                        <option value="<?= htmlspecialchars($row['district_id']) ?>" <?= $selected ?>>
                           <?= 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()" <?php echo (!isset($formData['district']) || empty($formData['district'])) ? 'disabled' : ''; ?> required>
                        <option value="">Select Tehsil</option>
                        <?php
                           if (isset($formData['district']) && !empty($formData['district'])) {
                               $district_id = $formData['district'];
                               $stmt = $conn->prepare("SELECT tehsil_id, tehsil_name FROM tehsils WHERE district_id = ? AND status = 1 ORDER BY tehsil_name");
                               $stmt->bind_param("i", $district_id);
                               $stmt->execute();
                               $tehsilResult = $stmt->get_result();
                               
                               while($tehsil = $tehsilResult->fetch_assoc()) {
                                   $selected = (isset($formData['tehsil']) && $formData['tehsil'] == $tehsil['tehsil_id']) ? 'selected' : '';
                                   echo '<option value="' . htmlspecialchars($tehsil['tehsil_id']) . '" ' . $selected . '>' 
                                        . htmlspecialchars($tehsil['tehsil_name']) 
                                        . '</option>';
                               }
                               $stmt->close();
                           }
                        ?>
                     </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()" <?php echo (!isset($formData['tehsil']) || empty($formData['tehsil'])) ? 'disabled' : ''; ?> required>
                        <option value="">Select Constituency</option>
                        <?php
                           if (isset($formData['tehsil']) && !empty($formData['tehsil'])) {
                               $tehsil_id = $formData['tehsil'];
                               $stmt = $conn->prepare("SELECT cons_id, cons_name FROM constituency WHERE tehsil_id = ? AND status = 1 ORDER BY cons_name");
                               $stmt->bind_param("i", $tehsil_id);
                               $stmt->execute();
                               $constituencyResult = $stmt->get_result();
                               
                               while($constituency = $constituencyResult->fetch_assoc()) {
                                   $selected = (isset($formData['constituency']) && $formData['constituency'] == $constituency['cons_id']) ? 'selected' : '';
                                   echo '<option value="' . htmlspecialchars($constituency['cons_id']) . '" ' . $selected . '>' 
                                        . htmlspecialchars($constituency['cons_name']) 
                                        . '</option>';
                               }
                               $stmt->close();
                           }
                        ?>
                     </select>
                  </div>
                  <div class="form-col">
                     <label for="unionCouncil" class="required-field">Union Council</label>
                     <select id="unionCouncil" name="unionCouncil" <?php echo (!isset($formData['constituency']) || empty($formData['constituency'])) ? 'disabled' : ''; ?> required>
                        <option value="">Select Union Council</option>
                        <?php
                           if (isset($formData['constituency']) && !empty($formData['constituency'])) {
                               $cons_id = $formData['constituency'];
                               $stmt = $conn->prepare("SELECT uc_id, uc_name FROM union_councils WHERE cons_id = ? AND status = 1 ORDER BY uc_name");
                               $stmt->bind_param("i", $cons_id);
                               $stmt->execute();
                               $ucResult = $stmt->get_result();
                               
                               while($uc = $ucResult->fetch_assoc()) {
                                   $selected = (isset($formData['unionCouncil']) && $formData['unionCouncil'] == $uc['uc_id']) ? 'selected' : '';
                                   echo '<option value="' . htmlspecialchars($uc['uc_id']) . '" ' . $selected . '>' 
                                        . htmlspecialchars($uc['uc_name']) 
                                        . '</option>';
                               }
                               $stmt->close();
                           }
                        ?>
                     </select>
                  </div>
               </div>
               <h3 class="section-title" style="margin-top: 30px;"><i class="fas fa-briefcase"></i> Employment Details</h3>
               <div class="form-row">
                  <div class="form-col">
                     <label for="employmentType" class="required-field">Employment Type</label>
                     <select id="employmentType" name="employmentType" required>
                     <?php
                        $sql = "SELECT status_id, status_name FROM employment_status ORDER BY status_id ASC";
                        $result = $conn->query($sql);
                        
                        echo '<option value="" selected disabled>Select Employment Status</option>';
                        
                        if ($result && $result->num_rows > 0) {
                          while($row = $result->fetch_assoc()) {
                            $selected = (isset($formData['employmentType']) && $formData['employmentType'] == $row['status_id']) ? 'selected' : '';
                            echo '<option value="' . htmlspecialchars($row['status_id']) . '" ' . $selected . '>' 
                                 . htmlspecialchars($row['status_name']) 
                                 . '</option>';
                          }
                        } else {
                          echo '<option value="" disabled>No Employment Status found</option>';
                        }
                        ?>
                     </select>
                  </div>
                  <div class="form-col">
                     <label for="grossPay" class="required-field">Gross Pay</label>
                     <input id="grossPay" name="grossPay" type="number" min="10000" inputmode="numeric" placeholder="Enter Amount" required 
                        value="<?php echo isset($formData['grossPay']) ? htmlspecialchars($formData['grossPay']) : ''; ?>">
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="iaa" class="required-field">Initially Appointed As</label>
                     <select id="iaa" name="iaa" required>
                     <?php
                        $sql = "SELECT des_id, designation_name FROM designations ORDER BY designation_name ASC";
                        $result = $conn->query($sql);
                        
                        echo '<option value="" selected disabled>Select Designation</option>';
                        
                        if ($result && $result->num_rows > 0) {
                          while($row = $result->fetch_assoc()) {
                            $selected = (isset($formData['iaa']) && $formData['iaa'] == $row['des_id']) ? 'selected' : '';
                            echo '<option value="' . htmlspecialchars($row['des_id']) . '" ' . $selected . '>' 
                                 . htmlspecialchars($row['designation_name']) 
                                 . '</option>';
                          }
                        } else {
                          echo '<option value="" disabled>No Designations found</option>';
                        }
                        ?>
                     </select>
                  </div>
                  <div class="form-col">
                     <label for="doapp" class="required-field">Date of Appointment</label>
                     <div class="date-input-container">
                        <input id="doapp" name="doapp" type="text" class="date-field"
                           placeholder="DD-MM-YYYY" 
                           maxlength="10"
                           pattern="\d{2}-\d{2}-\d{4}"
                           title="Please enter date in DD-MM-YYYY format"
                           required
                           value="<?php echo isset($formData['doapp']) ? htmlspecialchars($formData['doapp']) : ''; ?>">
                        <span class="datepicker-trigger" onclick="showDatePicker('doapp')">
                        <i class="fas fa-calendar-alt"></i>
                        </span>
                     </div>
                     <div id="doapp-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="tecudesig" class="required-field">Current Designation</label>
                     <select id="tecudesig" name="tecudesig" required>
                     <?php
                        $sql = "SELECT des_id, designation_name FROM designations ORDER BY designation_name ASC";
                        $result = $conn->query($sql);
                        
                        echo '<option value="" selected disabled>Select Current Designation</option>';
                        
                        if ($result && $result->num_rows > 0) {
                          while($row = $result->fetch_assoc()) {
                            $selected = (isset($formData['tecudesig']) && $formData['tecudesig'] == $row['des_id']) ? 'selected' : '';
                            echo '<option value="' . htmlspecialchars($row['des_id']) . '" ' . $selected . '>' 
                                 . htmlspecialchars($row['designation_name']) 
                                 . '</option>';
                          }
                        } else {
                          echo '<option value="" disabled>No Designations found</option>';
                        }
                        ?>
                     </select>
                  </div>
                  <div class="form-col">
                     <label for="dojcp" class="optional-field">Date of Promotion</label>
                     <div class="date-input-container">
                        <input id="dojcp" name="dojcp" type="text" class="date-field"
                           placeholder="DD-MM-YYYY" 
                           maxlength="10"
                           pattern="\d{2}-\d{2}-\d{4}"
                           title="Please enter date in DD-MM-YYYY format"
                           value="<?php echo isset($formData['dojcp']) ? htmlspecialchars($formData['dojcp']) : ''; ?>">
                        <span class="datepicker-trigger" onclick="showDatePicker('dojcp')">
                        <i class="fas fa-calendar-alt"></i>
                        </span>
                     </div>
                     <div id="dojcp-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="tecups" class="required-field">Basic Pay Scale</label>
                     <select id="tecups" name="tecups" required>
                        <option value="" selected disabled>Select Basic Pay Scale</option>
                        <?php
                           $query = "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()) {
                               $selected = (isset($formData['tecups']) && $formData['tecups'] == $row['bps_id']) ? 'selected' : '';
                               echo '<option value="' . htmlspecialchars($row['bps_id']) . '" ' . $selected . '>' 
                                    . htmlspecialchars($row['bps_name'] . ' - ' . $row['bps_label']) 
                                    . '</option>';
                             }
                           } else {
                             echo '<option value="">No pay scales found</option>';
                           }
                           ?>
                     </select>
                     <div id="tecups-error" class="error-message"></div>
                  </div>
                  <div class="form-col">
                     <label for="current_time_scale" class="optional-field">Current Time Scale</label>
                     <select id="current_time_scale" name="current_time_scale" class="form-control">
                        <option value="" selected>Select Time Scale</option>
                        <?php
                           $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()) {
                               $selected = (isset($formData['current_time_scale']) && $formData['current_time_scale'] == $row['ts_id']) ? 'selected' : '';
                               echo '<option value="' . htmlspecialchars($row['ts_id']) . '" ' . $selected . '>' 
                                    . htmlspecialchars($row['ts_name'] . ' - ' . $row['ts_label']) 
                                    . '</option>';
                             }
                           } else {
                             echo '<option value="">No time scales found</option>';
                           }
                           ?>
                     </select>
                     <div id="current_time_scale-error" class="error-message"></div>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="tetimes" class="optional-field">Date of Current Time Scale</label>
                     <div class="date-input-container">
                        <input id="tetimes" name="tetimes" type="text" class="date-field"
                           placeholder="DD-MM-YYYY" 
                           maxlength="10"
                           pattern="\d{2}-\d{2}-\d{4}"
                           title="Please enter date in DD-MM-YYYY format" 
                           value="<?php echo isset($formData['tetimes']) ? htmlspecialchars($formData['tetimes']) : ''; ?>">
                        <span class="datepicker-trigger" onclick="showDatePicker('tetimes')">
                        <i class="fas fa-calendar-alt"></i>
                        </span>
                     </div>
                     <div id="tetimes-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                  </div>
                  <div class="form-col">
                     <label for="workin" class="required-field">Presently Working Institute EMIS Code</label>
                     <div class="searchable-dropdown">
                        <div class="dropdown-search-container">
                           <input type="text" 
                                  id="emisSearch" 
                                  class="dropdown-search-input" 
                                  placeholder="Type to search EMIS Code or School Name..."
                                  autocomplete="off"
                                  value="<?php echo isset($selectedEMISData) ? htmlspecialchars($selectedEMISData['emis_code'] . ' - ' . $selectedEMISData['school_name']) : ''; ?>">
                           <div class="search-icon">
                              <i class="fas fa-search"></i>
                           </div>
                        </div>
                        <select id="workin" name="workin" class="form-control searchable-select" required style="display: none;">
                           <option value="" selected disabled>Select School EMIS Code</option>
                           <?php
                           $query = "SELECT emis_code, school_name FROM school_emis ORDER BY emis_code ASC";
                           $result = $conn->query($query);
                           
                           while($row = $result->fetch_assoc()) {
                             $selected = (isset($formData['workin']) && $formData['workin'] == $row['emis_code']) ? 'selected' : '';
                             echo '<option value="' . htmlspecialchars($row['emis_code']) . '" ' . $selected . ' 
                                   data-school="' . htmlspecialchars($row['school_name']) . '">'
                                   . htmlspecialchars($row['emis_code'] . ' - ' . $row['school_name']) 
                                   . '</option>';
                           }
                           ?>
                        </select>
                        <div id="searchResults" class="search-results"></div>
                     </div>
                  </div>
               </div>
               <div class="form-row">
                  <div class="form-col">
                     <label for="wtis" class="required-field">Working This Institution Since</label>
                     <div class="date-input-container">
                        <input id="wtis" name="wtis" type="text" class="date-field"
                           placeholder="DD-MM-YYYY" 
                           maxlength="10"
                           pattern="\d{2}-\d{2}-\d{4}"
                           title="Please enter date in DD-MM-YYYY format"
                           required
                           value="<?php echo isset($formData['wtis']) ? htmlspecialchars($formData['wtis']) : ''; ?>">
                        <span class="datepicker-trigger" onclick="showDatePicker('wtis')">
                        <i class="fas fa-calendar-alt"></i>
                        </span>
                     </div>
                     <div id="wtis-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                  </div>
                  <div class="form-col">
                     <label for="workin1">Presently Working Institute (Auto-filled)</label>
                     <input id="workin1" name="workin1" type="text" readonly
                        value="<?php echo isset($formData['workin1']) ? htmlspecialchars($formData['workin1']) : ''; ?>">
                  </div>
               </div>
    
 <div class="form-actions" style="display: flex; justify-content: flex-end;">
                  <button type="submit" class="btn btn-primary">
                  <i class="fas fa-arrow-right"></i> Next
                  </button>
               </div>
            </div>
         </form>
      </div>
      
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
      <script>
// SIMPLE EMIS SEARCH - WORKING VERSION
function initializeEMISSearch() {
    const searchInput = document.getElementById('emisSearch');
    const searchResults = document.getElementById('searchResults');
    const workinSelect = document.getElementById('workin');
    const workin1Input = document.getElementById('workin1');
    
    if (!searchInput || !searchResults || !workinSelect || !workin1Input) {
        console.log("Some elements not found");
        return;
    }
    
    // Get all options
    const allOptions = [];
    for (let option of workinSelect.options) {
        if (option.value) {
            allOptions.push({
                value: option.value,
                text: option.textContent,
                school: option.dataset.school
            });
        }
    }
    
// Function to show search results
function showSearchResults() {
    const searchTerm = searchInput.value.toLowerCase().trim();
    searchResults.innerHTML = '';
    
    // If search is empty, show ALL options
    if (!searchTerm) {
        // Show all options
        allOptions.forEach(option => {
            const div = document.createElement('div');
            div.className = 'search-result-item';
            div.innerHTML = `
                <span class="emis-code">${option.value}</span>
                <span class="school-name">${option.school || ''}</span>
            `;
            
            div.addEventListener('click', function() {
                // Set select value
                workinSelect.value = option.value;
                
                // Update school name field
                workin1Input.value = option.school || '';
                
                // Show only EMIS code
                searchInput.value = option.value;
                
                // Hide results
                searchResults.style.display = 'none';
                
                // Trigger events
                workinSelect.dispatchEvent(new Event('change'));
            });
            
            searchResults.appendChild(div);
        });
        
        // Show "All schools" message if there are many
        if (allOptions.length > 10) {
            const header = document.createElement('div');
            header.className = 'no-results';
            header.innerHTML = `<i class="fas fa-school"></i> Showing all ${allOptions.length} schools`;
            searchResults.insertBefore(header, searchResults.firstChild);
        }
        
        searchResults.style.display = 'block';
        return;
    }
    
    // Filter options if there's a search term
    const filtered = allOptions.filter(option => 
        option.text.toLowerCase().includes(searchTerm) || 
        option.value.toLowerCase().includes(searchTerm) ||
        (option.school && option.school.toLowerCase().includes(searchTerm))
    );
    
    if (filtered.length === 0) {
        searchResults.innerHTML = '<div class="no-results">No matching schools found</div>';
        searchResults.style.display = 'block';
        return;
    }
    
    filtered.forEach(option => {
        const div = document.createElement('div');
        div.className = 'search-result-item';
        div.innerHTML = `
            <span class="emis-code">${option.value}</span>
            <span class="school-name">${option.school || ''}</span>
        `;
        
        div.addEventListener('click', function() {
            // Set select value
            workinSelect.value = option.value;
            
            // Update school name field
            workin1Input.value = option.school || '';
            
            // Show only EMIS code
            searchInput.value = option.value;
            
            // Hide results
            searchResults.style.display = 'none';
            
            // Trigger events
            workinSelect.dispatchEvent(new Event('change'));
        });
        
        searchResults.appendChild(div);
    });
    
    searchResults.style.display = 'block';
}
    
    // Add clear button
    const clearBtn = document.createElement('button');
    clearBtn.type = 'button';
    clearBtn.className = 'clear-search';
    clearBtn.innerHTML = '×';
    clearBtn.title = 'Clear search';
    
    clearBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        searchInput.value = '';
        workinSelect.value = '';
        workin1Input.value = '';
        searchResults.style.display = 'none';
        clearBtn.style.display = 'none';
        searchInput.focus();
    });
    
    const searchContainer = document.querySelector('.dropdown-search-container');
    if (searchContainer) {
        searchContainer.appendChild(clearBtn);
    }
    
    // Event listeners
    searchInput.addEventListener('input', function() {
        showSearchResults();
        clearBtn.style.display = this.value ? 'block' : 'none';
    });
    
    searchInput.addEventListener('focus', showSearchResults);
    
    // Close results when clicking outside
    document.addEventListener('click', function(e) {
        if (!searchInput.contains(e.target) && !searchResults.contains(e.target)) {
            searchResults.style.display = 'none';
        }
    });
    
    // Keyboard support
    searchInput.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            searchResults.style.display = 'none';
        }
    });
    
    // Initialize with existing value - Show only EMIS code
    if (workinSelect.value) {
        const selected = allOptions.find(o => o.value === workinSelect.value);
        if (selected) {
            searchInput.value = selected.value; // Only EMIS code
            workin1Input.value = selected.school || '';
        }
    }
}

// ===== ALL VALIDATION FUNCTIONS FROM CODE 2 =====

// Cache existing personal numbers and CNICs (FROM CODE 2)
let existingNumbersCache = [];
let existingCNICsCache = [];

// Comprehensive validation function for Step 1 (ENHANCED FROM CODE 2)
function validateStep1() {
    // Reset all borders first
    document.querySelectorAll('input, select, textarea').forEach(el => {
        el.style.borderColor = '';
        el.style.boxShadow = '';
    });
    
    // Reset radio group borders
    document.querySelectorAll('.radio-group').forEach(group => {
        group.style.border = 'none';
        group.style.padding = '0';
    });
    
    // Hide all error messages initially
    document.querySelectorAll('.error-message').forEach(error => {
        error.style.display = 'none';
    });
    
    // List of all required field IDs (excluding read-only fields) (FROM CODE 2)
    const requiredFields = [
        'tefname', 'teemq', 'temobno', 'teddono', 'tenok', 'tenokre', 
        'district', 'tehsil', 'constituency', 'unionCouncil', 
        'employmentType', 'grossPay', 'iaa', 'doapp', 'tecudesig', 
        // Removed optional fields: 'dojcp', 'current_time_scale', 'tetimes' (FROM CODE 2)
        'workin', 'wtis'
    ];

    let isValid = true;
    let firstInvalidField = null;

    // Validate required text/select fields (ENHANCED FROM CODE 2)
    requiredFields.forEach(field => {
        const element = document.getElementById(field);
        if (element) {
            const value = element.type === 'file' ? element.files.length : element.value;
            
            if (!value || value.toString().trim() === '') {
                element.style.borderColor = '#e74c3c';
                element.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
                
                // Show specific error message if available
                const errorElement = document.getElementById(field + '-error');
                if (errorElement) {
                    errorElement.textContent = 'This field is required';
                    errorElement.style.display = 'block';
                }
                
                isValid = false;
                
                // Store first invalid field for scrolling
                if (!firstInvalidField) {
                    firstInvalidField = element;
                }
            } else {
                element.style.borderColor = '';
                element.style.boxShadow = '';
            }
        }
    });

    // Validate gender (radio buttons) (FROM CODE 2)
    const genderSelected = document.querySelector('input[name="tege"]:checked');
    if (!genderSelected) {
        document.querySelectorAll('[name="tege"]').forEach(radio => {
            radio.closest('.radio-group').style.border = '2px solid #e74c3c';
            radio.closest('.radio-group').style.borderRadius = '4px';
            radio.closest('.radio-group').style.padding = '8px';
        });
        isValid = false;
        
        if (!firstInvalidField) {
            firstInvalidField = document.querySelector('[name="tege"]').closest('.radio-group');
        }
    }

    // Validate photo upload (ENHANCED FROM CODE 2)
    const photoField = document.getElementById('tchpic');
    if (!photoField.files || photoField.files.length === 0) {
        document.getElementById('photo-error').textContent = 'Photo upload is required';
        document.getElementById('photo-error').style.display = 'block';
        document.querySelector('.file-input-label').style.border = '2px solid #e74c3c';
        isValid = false;
        
        if (!firstInvalidField) {
            firstInvalidField = photoField;
        }
    } else {
        document.getElementById('photo-error').style.display = 'none';
        document.querySelector('.file-input-label').style.border = '';
    }

    // Validate specific format fields (excluding read-only CNIC) (FROM CODE 2)
    const mobileField = document.getElementById('temobno');
    if (mobileField && !/^03\d{9}$/.test(mobileField.value)) {
        mobileField.style.borderColor = '#e74c3c';
        mobileField.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
        isValid = false;
        
        if (!firstInvalidField) {
            firstInvalidField = mobileField;
        }
    }

    // Validate date fields (only if they have values) (FROM CODE 2)
    const dateFields = ['doapp', 'dojcp', 'tetimes', 'wtis'];
    dateFields.forEach(field => {
        const element = document.getElementById(field);
        if (element && element.value) {
            if (!validateDateFormat(element)) {
                isValid = false;
                if (!firstInvalidField) {
                    firstInvalidField = element;
                }
            }
        }
    });

    // Validate date relationships (only if fields have values) (FROM CODE 2)
    if (!validateAllDates()) {
        isValid = false;
    }

    // Validate Basic Pay Scale vs Time Scale (only if time scale is selected) (FROM CODE 2)
    if (!validatePayScaleVsTimeScale()) {
        isValid = false;
        
        // Find first invalid field for scrolling
        if (!firstInvalidField) {
            firstInvalidField = document.getElementById('tecups');
        }
    }
    
    // Validate Working Since date vs Appointment date (FROM CODE 2)
    if (!validateWorkingSinceDate()) {
        isValid = false;
        
        // Find first invalid field for scrolling
        if (!firstInvalidField) {
            firstInvalidField = document.getElementById('wtis');
        }
    }
    
    // Validate retirement date is calculated (read-only) (FROM CODE 2)
    const retirementInput = document.getElementById('teretirement');
    if (retirementInput && !retirementInput.value) {
        // If retirement date is empty but date of birth exists, show error
        const birthInput = document.getElementById('tebirthday');
        if (birthInput && birthInput.value) {
            alert('Please ensure Date of Birth is filled correctly to calculate retirement date.');
            isValid = false;
            
            if (!firstInvalidField) {
                firstInvalidField = birthInput;
            }
        }
    }

    // Scroll to first invalid field if any (ENHANCED FROM CODE 2)
    if (!isValid && firstInvalidField) {
        firstInvalidField.scrollIntoView({ 
            behavior: 'smooth', 
            block: 'center' 
        });
        
        // Add focus to the first invalid field if it's an input/select
        if (firstInvalidField.tagName === 'INPUT' || firstInvalidField.tagName === 'SELECT') {
            firstInvalidField.focus();
        }
        
        alert('Please fill all required fields correctly. Invalid fields are highlighted in red.');
        return false;
    }

    return isValid;
}

// Add real-time validation for better UX (FROM CODE 2)
function addRealTimeValidation() {
    // Add input event listeners to clear red borders when user starts typing
    document.querySelectorAll('input, select, textarea').forEach(element => {
        // Skip read-only fields
        if (element.readOnly) return;
        
        element.addEventListener('input', function() {
            if (this.style.borderColor === 'rgb(231, 76, 60)') {
                this.style.borderColor = '';
                this.style.boxShadow = '';
                
                // Hide error message if it's just a required field error
                const errorElement = document.getElementById(this.id + '-error');
                if (errorElement && errorElement.textContent === 'This field is required') {
                    errorElement.style.display = 'none';
                }
            }
        });
        
        element.addEventListener('change', function() {
            if (this.style.borderColor === 'rgb(231, 76, 60)') {
                this.style.borderColor = '';
                this.style.boxShadow = '';
            }
        });
    });
    
    // Special handling for radio buttons
    document.querySelectorAll('input[type="radio"]').forEach(radio => {
        radio.addEventListener('change', function() {
            const radioGroup = this.closest('.radio-group');
            if (radioGroup && radioGroup.style.borderColor === 'rgb(231, 76, 60)') {
                radioGroup.style.border = 'none';
                radioGroup.style.padding = '0';
            }
        });
    });
}

// ===== DATE VALIDATION FUNCTIONS (FROM CODE 2) =====

function parseDDMMYYYY(dateStr) {
    if (!dateStr || typeof dateStr !== 'string') return null;
    
    const parts = dateStr.split('-');
    if (parts.length !== 3) return null;
    
    const day = parseInt(parts[0], 10);
    const month = parseInt(parts[1], 10) - 1; // Months are 0-indexed in JS
    const year = parseInt(parts[2], 10);
    
    if (isNaN(day) || isNaN(month) || isNaN(year)) return null;
    
    // Create date object (note: month is 0-indexed)
    const date = new Date(year, month, day);
    
    // Check if the date is valid
    if (date.getDate() !== day || date.getMonth() !== month || date.getFullYear() !== year) {
        return null;
    }
    
    return date;
}

function validateFutureDate(inputId) {
    const input = document.getElementById(inputId);
    const errorElement = document.getElementById(inputId + '-error');
    const value = input.value.trim();
    
    if (!value) {
        if (errorElement) errorElement.style.display = 'none';
        input.setCustomValidity('');
        return true;
    }
    
    const date = parseDDMMYYYY(value);
    if (!date) {
        if (errorElement) {
            errorElement.textContent = "Invalid date format (DD-MM-YYYY)";
            errorElement.style.display = 'block';
        }
        input.setCustomValidity('Invalid date format');
        return false;
    }
    
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    if (date > today) {
        if (errorElement) {
            errorElement.textContent = "Date cannot be in the future!";
            errorElement.style.display = 'block';
        }
        input.setCustomValidity('Date cannot be in the future');
        return false;
    }
    
    if (errorElement) errorElement.style.display = 'none';
    input.setCustomValidity('');
    return true;
}

function validateAgeGap() {
    const dobInput = document.getElementById('tebirthday');
    const appointmentInput = document.getElementById('doapp');
    const errorElement = document.getElementById('doapp-error');
    
    if (!dobInput.value || !appointmentInput.value) return true;
    
    const dobDate = parseDDMMYYYY(dobInput.value);
    const appointmentDate = parseDDMMYYYY(appointmentInput.value);
    
    if (!dobDate || !appointmentDate) return true;
    
    // Calculate age at appointment
    let age = appointmentDate.getFullYear() - dobDate.getFullYear();
    const monthDiff = appointmentDate.getMonth() - dobDate.getMonth();
    
    if (monthDiff < 0 || (monthDiff === 0 && appointmentDate.getDate() < dobDate.getDate())) {
        age--;
    }
    
    if (age < 16) {
        if (errorElement) {
            errorElement.textContent = "Employee must be at least 16 years old at appointment!";
            errorElement.style.display = 'block';
        }
        appointmentInput.setCustomValidity('Employee must be at least 16 years old at appointment');
        return false;
    }
    
    if (errorElement) errorElement.style.display = 'none';
    appointmentInput.setCustomValidity('');
    return true;
}

function validatePromotionAfterAppointment() {
    const appointmentInput = document.getElementById('doapp');
    const promotionInput = document.getElementById('dojcp');
    const errorElement = document.getElementById('dojcp-error');
    
    // If promotion date is not provided, return true (it's optional)
    if (!promotionInput.value) return true;
    
    if (!appointmentInput.value) return true;
    
    const appointmentDate = parseDDMMYYYY(appointmentInput.value);
    const promotionDate = parseDDMMYYYY(promotionInput.value);
    
    if (!appointmentDate || !promotionDate) return true;
    
    if (promotionDate < appointmentDate) {
        if (errorElement) {
            errorElement.textContent = "Promotion date must be on or after appointment date!";
            errorElement.style.display = 'block';
        }
        promotionInput.setCustomValidity('Promotion date must be on or after appointment date');
        return false;
    }
    
    if (errorElement) errorElement.style.display = 'none';
    promotionInput.setCustomValidity('');
    return true;
}

function validateTimeScaleAfterAppointment() {
    const appointmentInput = document.getElementById('doapp');
    const timeScaleInput = document.getElementById('tetimes');
    const errorElement = document.getElementById('tetimes-error');
    
    // If time scale date is not provided, return true (it's optional)
    if (!timeScaleInput.value) return true;
    
    if (!appointmentInput.value) return true;
    
    const appointmentDate = parseDDMMYYYY(appointmentInput.value);
    const timeScaleDate = parseDDMMYYYY(timeScaleInput.value);
    
    if (!appointmentDate || !timeScaleDate) return true;
    
    if (timeScaleDate < appointmentDate) {
        if (errorElement) {
            errorElement.textContent = "Time scale date must be on or after appointment date!";
            errorElement.style.display = 'block';
        }
        timeScaleInput.setCustomValidity('Time scale date must be on or after appointment date');
        return false;
    }
    
    if (errorElement) errorElement.style.display = 'none';
    timeScaleInput.setCustomValidity('');
    return true;
}

// Function to validate Working Since date vs Appointment date (FROM CODE 2)
function validateWorkingSinceDate() {
    const appointmentInput = document.getElementById('doapp');
    const workingSinceInput = document.getElementById('wtis');
    const workingSinceError = document.getElementById('wtis-error');

    // Reset error
    if (workingSinceError) {
        workingSinceError.style.display = 'none';
    }
    workingSinceInput.style.borderColor = '';

    // If both dates are provided
    if (appointmentInput.value && workingSinceInput.value) {
        const appointmentDate = parseDDMMYYYY(appointmentInput.value);
        const workingSinceDate = parseDDMMYYYY(workingSinceInput.value);

        if (appointmentDate && workingSinceDate) {
            // Working Since date must be greater than or equal to Appointment date
            if (workingSinceDate < appointmentDate) {
                const errorMessage = "❌ Working Since date cannot be earlier than Appointment date!";
                
                if (workingSinceError) {
                    workingSinceError.textContent = errorMessage;
                    workingSinceError.style.display = 'block';
                }
                workingSinceInput.style.borderColor = '#e74c3c';
                workingSinceInput.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
                workingSinceInput.setCustomValidity('Working Since date cannot be earlier than Appointment date');
                
                return false;
            }
        }
    }

    workingSinceInput.setCustomValidity('');
    return true;
}

function validateAllDates() {
    const dateFields = ['doapp', 'dojcp', 'tetimes', 'wtis'];
    let isValid = true;
    
    // First validate all dates are not in the future (only if provided)
    dateFields.forEach(field => {
        const fieldElement = document.getElementById(field);
        if (fieldElement && fieldElement.value) { // Only validate if value exists
            if (!validateFutureDate(field)) {
                isValid = false;
            }
        }
    });
    
    // Then validate specific date relationships (only if fields have values)
    if (!validateAgeGap()) isValid = false;
    
    // Only validate promotion date if it exists
    const promotionInput = document.getElementById('dojcp');
    if (promotionInput && promotionInput.value) {
        if (!validatePromotionAfterAppointment()) isValid = false;
    }
    
    // Only validate time scale date if it exists
    const timeScaleInput = document.getElementById('tetimes');
    if (timeScaleInput && timeScaleInput.value) {
        if (!validateTimeScaleAfterAppointment()) isValid = false;
    }
    
    if (!validateWorkingSinceDate()) isValid = false;
    
    return isValid;
}

// Enhanced date format validation (FROM CODE 2)
function validateDateFormat(input) {
    if (typeof input === 'string') {
        input = document.getElementById(input);
    }
    
    const errorElement = document.getElementById(input.id + '-error');
    const value = input.value.trim();
    
    // If value is empty (optional field), return true
    if (!value) {
        if (errorElement) errorElement.style.display = 'none';
        input.setCustomValidity('');
        return true;
    }
    
    const datePattern = /^(\d{2})-(\d{2})-(\d{4})$/;
    if (!datePattern.test(value)) {
        if (errorElement) {
            errorElement.textContent = "Invalid date format (DD-MM-YYYY)";
            errorElement.style.display = 'block';
        }
        input.style.borderColor = '#e74c3c';
        input.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
        input.setCustomValidity('Please enter date in DD-MM-YYYY format');
        return false;
    }
    
    const parts = value.split('-');
    const day = parseInt(parts[0], 10);
    const month = parseInt(parts[1], 10) - 1;
    const year = parseInt(parts[2], 10);
    
    const inputDate = new Date(year, month, day);
    if (isNaN(inputDate.getTime()) || 
        inputDate.getDate() !== day || 
        inputDate.getMonth() !== month || 
        inputDate.getFullYear() !== year) {
        if (errorElement) {
            errorElement.textContent = "Invalid date!";
            errorElement.style.display = 'block';
        }
        input.style.borderColor = '#e74c3c';
        input.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
        input.setCustomValidity('Invalid date');
        return false;
    }
    
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    if (inputDate > today) {
        if (errorElement) {
            errorElement.textContent = "Date cannot be in the future!";
            errorElement.style.display = 'block';
        }
        input.style.borderColor = '#e74c3c';
        input.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
        input.setCustomValidity('Date cannot be in the future');
        return false;
    }
    
    if (errorElement) errorElement.style.display = 'none';
    input.style.borderColor = '';
    input.style.boxShadow = '';
    input.setCustomValidity('');
    return true;
}

// Function to validate Basic Pay Scale vs Time Scale (FROM CODE 2)
function validatePayScaleVsTimeScale() {
    const basicPayScale = document.getElementById('tecups');
    const timeScale = document.getElementById('current_time_scale');
    
    // If time scale is not selected (optional), return true
    if (!timeScale.value) {
        return true;
    }
    
    // If time scale is selected but basic pay scale is not, return false
    if (!basicPayScale.value) {
        return false; // basic pay scale is required
    }
    
    const basicPayScaleError = document.getElementById('tecups-error') || createErrorElement(basicPayScale);
    const timeScaleError = document.getElementById('current_time_scale-error') || createErrorElement(timeScale);

    // Reset errors
    basicPayScaleError.style.display = 'none';
    timeScaleError.style.display = 'none';
    basicPayScale.style.borderColor = '';
    timeScale.style.borderColor = '';

    // If both fields are selected
    if (basicPayScale.value && timeScale.value) {
        const basicScaleValue = parseInt(basicPayScale.value);
        const timeScaleValue = parseInt(timeScale.value);

        // Basic Pay Scale must be less than or equal to Time Scale
        if (basicScaleValue > timeScaleValue) {
            const errorMessage = `❌ Basic Pay Scale (BPS-${basicScaleValue}) cannot be greater than Time Scale (BPS-${timeScaleValue})`;
            
            basicPayScaleError.textContent = errorMessage;
            basicPayScaleError.style.display = 'block';
            basicPayScale.style.borderColor = '#e74c3c';
            basicPayScale.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
            
            timeScaleError.textContent = errorMessage;
            timeScaleError.style.display = 'block';
            timeScale.style.borderColor = '#e74c3c';
            timeScale.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';

            return false;
        }
        
        // Additional validation: Time Scale should not be more than 5 scales above Basic Scale
        if (timeScaleValue > basicScaleValue + 5) {
            const errorMessage = `⚠ Time Scale (BPS-${timeScaleValue}) is unusually high compared to Basic Scale (BPS-${basicScaleValue}). Please verify.`;
            
            basicPayScaleError.textContent = errorMessage;
            basicPayScaleError.style.display = 'block';
            basicPayScaleError.style.color = '#ff9800';
            
            timeScaleError.textContent = errorMessage;
            timeScaleError.style.display = 'block';
            timeScaleError.style.color = '#ff9800';
            

            // This is a warning, not an error - return true but show warning
            return true;
        }
    }

    return true;
}

// Helper function to create error element if it doesn't exist (FROM CODE 2)
function createErrorElement(field) {
    const errorElement = document.createElement('div');
    errorElement.className = 'error-message';
    errorElement.id = field.id + '-error';

    errorElement.style.color = '#e74c3c';
    errorElement.style.marginTop = '5px';
    errorElement.style.fontSize = '0.9em';
    errorElement.style.display = 'none';
    
    field.parentNode.appendChild(errorElement);
    return errorElement;
}

// Retirement date calculation (based on date of birth only) (FROM CODE 2)
function calculateRetirementDate() {
    const birthDateInput = document.getElementById('tebirthday');
    const retirementDateInput = document.getElementById('teretirement');
    
    // Clear retirement date if birth date is missing
    if (!birthDateInput.value) {
        retirementDateInput.value = '';
        return;
    }
    
    try {
        // Parse birth date (format: DD-MM-YYYY)
        const birthParts = birthDateInput.value.split('-');
        const birthDay = parseInt(birthParts[0], 10);
        const birthMonth = parseInt(birthParts[1], 10) - 1;
        const birthYear = parseInt(birthParts[2], 10);
        
        // Validate the date
        const birthDate = new Date(birthYear, birthMonth, birthDay);
        if (isNaN(birthDate.getTime())) {
            console.error('Invalid date format');
            return;
        }
        
        // Calculate retirement date: 60 years from birth date
        const retirementDate = new Date(birthDate);
        retirementDate.setFullYear(retirementDate.getFullYear() + 60);
        retirementDate.setDate(retirementDate.getDate() - 1);
        
        // Format the date as DD-MM-YYYY
        const dd = String(retirementDate.getDate()).padStart(2, '0');
        const mm = String(retirementDate.getMonth() + 1).padStart(2, '0');
        const yyyy = retirementDate.getFullYear();
        
        retirementDateInput.value = `${dd}-${mm}-${yyyy}`;
        
    } catch (error) {
        console.error('Error calculating retirement date:', error);
        retirementDateInput.value = '';
    }
}

// Add this function to calculate retirement date from fetched DOB on page load (FROM CODE 2)
function calculateRetirementFromFetchedDOB() {
    const birthDateInput = document.getElementById('tebirthday');
    const retirementDateInput = document.getElementById('teretirement');
    
    // If birth date is already filled from session
    if (birthDateInput.value && !retirementDateInput.value) {
        calculateRetirementDate();
    }
}

// ===== EXISTING FUNCTIONS FROM CODE 1 =====

// Mobile number validation
function isNumberKey(evt) {
    const charCode = (evt.which) ? evt.which : evt.keyCode;
    return !(charCode > 31 && (charCode < 48 || charCode > 57));
}

function handleMobileInput(input) {
    const value = input.value.replace(/\D/g, '');
    if (value.length > 11) {
        input.value = value.substring(0, 11);
    } else {
        input.value = value;
    }
    
    if (value.length === 11) {
        validateCompleteNumber(input);
    } else {
        clearError(input);
    }
    
    // Auto-copy to WhatsApp if WhatsApp is empty
    if (value.length === 11 && value.startsWith('03')) {
        const whatsappInput = document.getElementById('tewano');
        if (!whatsappInput.value || whatsappInput.value === input.dataset.prevValue) {
            whatsappInput.value = value;
            clearError(whatsappInput);
        }
    }
    input.dataset.prevValue = value;
}

function handleWhatsAppInput(input) {
    const value = input.value.replace(/\D/g, '');
    if (value.length > 11) {
        input.value = value.substring(0, 11);
    } else {
        input.value = value;
    }
    
    if (value.length === 11) {
        validateCompleteNumber(input);
    } else {
        clearError(input);
    }
}

function validateCompleteNumber(input) {
    const value = input.value;
    const isValid = value.startsWith('03') && value.length === 11;
    
    if (value.length > 0) {
        showError(input, !isValid);
        input.setCustomValidity(!isValid ? 'Must start with 03 and be exactly 11 digits' : ''); // FROM CODE 2
    } else {
        clearError(input);
    }
    
    return isValid;
}

function showError(input, show) {
    const errorElement = document.getElementById(`${input.id}-error`);
    if (errorElement) {
        errorElement.style.display = show ? 'block' : 'none';
        input.style.borderColor = show ? '#e74c3c' : '';
    }
}

function clearError(input) {
    showError(input, false);
    input.setCustomValidity(''); // FROM CODE 2
}

// DDO code validation
function allowDdoChars(event) {
    const input = event.target;
    const charCode = event.which ? event.which : event.keyCode;
    const currentLength = input.value.length;
    
    if (currentLength < 2) {
        return (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122);
    } else if (currentLength < 6) {
        return charCode >= 48 && charCode <= 57;
    }
    return false;
}

function validateDdoCode(input) {
    const value = input.value;
    const isValid = /^[A-Za-z]{2}\d{4}$/.test(value);
    
    if (value.length <= 2) {
        input.value = value.toUpperCase();
    } else if (value.length > 2) {
        const letters = value.substring(0, 2).toUpperCase();
        const numbers = value.substring(2);
        input.value = letters + numbers;
    }
    
    const errorElement = document.getElementById('teddono-error');
    if (value.length > 0 && !isValid) {
        if (errorElement) {
            errorElement.style.display = 'block';
        }
        input.setCustomValidity('Must have 2 letters followed by 4 digits'); // FROM CODE 2
    } else {
        if (errorElement) {
            errorElement.style.display = 'none';
        }
        input.setCustomValidity(''); // FROM CODE 2
    }
    
    return isValid;
}

// Name field validation
function preventNumbers(e) {
    if ([46, 8, 9, 27, 13, 110].includes(e.keyCode) || 
        (e.keyCode >= 35 && e.keyCode <= 40)) {
        return;
    }
    
    if ((e.keyCode >= 48 && e.keyCode <= 57) || 
        (e.keyCode >= 96 && e.keyCode <= 105)) {
        e.preventDefault();
    }
}

// Apply to name fields
const noNumberFields = ['tefname', 'tebplace', 'tenok', 'tevillage', 'tepo'];
noNumberFields.forEach(fieldId => {
    const field = document.getElementById(fieldId);
    if (field) {
        field.addEventListener('keydown', preventNumbers);
        
        field.addEventListener('paste', (e) => {
            const pasteData = e.clipboardData.getData('text');
            if (/\d/.test(pasteData)) {
                e.preventDefault();
                alert('Numbers are not allowed in this field');
            }
        });
    }
});

// Auto-capitalize names
function autoCapitalize(input) {
    const connectors = ['ul', 'e', 'bin', 'al', 'da', 'de', 'ud'];
    
    input.value = input.value
        .toLowerCase()
        .split(' ')
        .map(word => {
            return word
                .split('-')
                .map((part, index) => {
                    if (connectors.includes(part)) {
                        return part;
                    }
                    return part.charAt(0).toUpperCase() + part.slice(1);
                })
                .join('-');
        })
        .join(' ');
}

const nameFields = ['tefname', 'tebplace', 'tenok', 'tevillage', 'tepo'];
nameFields.forEach(fieldId => {
    const field = document.getElementById(fieldId);
    if (field) {
        field.addEventListener('input', function () {
            autoCapitalize(this);
        });
    }
});

// Image validation
function validateAndPreviewImage(input) {
    const file = input.files[0];
    const fileDisplayArea = document.getElementById('fileDisplayArea');
    const maxSizeMB = 2;

    if (!file) {
        resetPhotoPreview();
        return;
    }

    const validTypes = ['image/jpeg', 'image/png'];
    if (!validTypes.includes(file.type)) {
        alert('Error: Only JPEG or PNG images are allowed.');
        resetFileInput(input);
        return;
    }

    if (file.size > maxSizeMB * 1024 * 1024) {
        alert(`Error: Image exceeds ${maxSizeMB}MB maximum size.`);
        resetFileInput(input);
        return;
    }

    const reader = new FileReader();
    reader.onload = function(e) {
        const img = new Image();
        img.onload = function() {
            fileDisplayArea.innerHTML = `<img src="${e.target.result}" alt="Employee Photo Preview" style="max-width: 100%; max-height: 100%; object-fit: contain;">`;
        };
        img.src = e.target.result;
    };
    reader.readAsDataURL(file);
}

function resetFileInput(input) {
    input.value = '';
    resetPhotoPreview();
}

function resetPhotoPreview() {
    document.getElementById('fileDisplayArea').innerHTML =
        '<i class="fas fa-user-circle" style="font-size: 60px; color: #ccc;"></i>';
}

// ===== INITIALIZATION =====

document.addEventListener('DOMContentLoaded', function() {
    console.log("Page loaded, initializing...");
    
    // Initialize EMIS search (FROM CODE 1)
    initializeEMISSearch();
    
    // Calculate retirement date if needed
    const birthInput = document.getElementById('tebirthday');
    const retirementInput = document.getElementById('teretirement');
    if (birthInput.value && !retirementInput.value) {
        calculateRetirementDate();
    }
    
    // Initialize mobile input tracking
    const mobileInput = document.getElementById('temobno');
    const whatsappInput = document.getElementById('tewano');
    
    if (mobileInput) mobileInput.dataset.prevValue = mobileInput.value;
    if (whatsappInput) whatsappInput.dataset.prevValue = whatsappInput.value;
    
    // Add real-time validation (FROM CODE 2)
    addRealTimeValidation();
    
    // Add event listeners for pay scale validation (FROM CODE 2)
    const basicScale = document.getElementById('tecups');
    const timeScale = document.getElementById('current_time_scale');
    
    if (basicScale) {
        basicScale.addEventListener('change', validatePayScaleVsTimeScale);
    }
    
    if (timeScale) {
        timeScale.addEventListener('change', validatePayScaleVsTimeScale);
    }
    
    // Add event listeners for working since date validation (FROM CODE 2)
    const appointmentInput = document.getElementById('doapp');
    const workingSinceInput = document.getElementById('wtis');
    
    if (appointmentInput) {
        appointmentInput.addEventListener('change', validateWorkingSinceDate);
        appointmentInput.addEventListener('blur', validateWorkingSinceDate);
    }
    
    if (workingSinceInput) {
        workingSinceInput.addEventListener('change', validateWorkingSinceDate);
        workingSinceInput.addEventListener('blur', validateWorkingSinceDate);
    }
    
    // Form validation
    const form = document.getElementById('teacherForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            if (!validateStep1()) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
        });
    }
    
    // Also validate when Next button is clicked (FROM CODE 2)
    const nextButton = document.querySelector('button[type="submit"]');
    if (nextButton) {
        nextButton.addEventListener('click', function(e) {
            if (!validateStep1()) {
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }
    
    // Date validation listeners
    const dateFields = ['doapp', 'dojcp', 'tetimes', 'wtis'];
    dateFields.forEach(fieldId => {
        const field = document.getElementById(fieldId);
        if (field) {
            field.addEventListener('change', function() {
                validateDateFormat(this);
                validateAllDates();
            });
            field.addEventListener('blur', function() {
                validateDateFormat(this);
                validateAllDates();
            });
        }
    });
    
    // Add employment date validation listeners (FROM CODE 2)
    const employmentDateFields = ['tebirthday', 'doapp', 'dojcp', 'tetimes'];
    employmentDateFields.forEach(fieldId => {
        const field = document.getElementById(fieldId);
        if (field) {
            // Skip read-only field (tebirthday)
            if (fieldId === 'tebirthday' && field.readOnly) return;
            
            field.addEventListener('change', validateAllDates);
            field.addEventListener('blur', validateAllDates);
        }
    });
    
    // Enable dependent dropdowns if values are already selected (FROM CODE 2)
    <?php if (isset($formData['district']) && !empty($formData['district'])): ?>
    $('#tehsil').prop('disabled', false);
    <?php endif; ?>
    
    <?php if (isset($formData['tehsil']) && !empty($formData['tehsil'])): ?>
    $('#constituency').prop('disabled', false);
    <?php endif; ?>
    
    <?php if (isset($formData['constituency']) && !empty($formData['constituency'])): ?>
    $('#unionCouncil').prop('disabled', false);
    <?php endif; ?>
    
    // Auto-fill school name when EMIS code is selected
    $('#workin').on('change', function() {
        var schoolName = $(this).find('option:selected').data('school');
        $('#workin1').val(schoolName || '');
    });
    
    // Trigger change event if workin already has a value
    <?php if (isset($formData['workin']) && !empty($formData['workin'])): ?>
    $('#workin').trigger('change');
    <?php endif; ?>
    
    // Force retirement calculation if DOB exists (FROM CODE 2)
    setTimeout(function() {
        if (document.getElementById('tebirthday').value && !document.getElementById('teretirement').value) {
            calculateRetirementDate();
        }
    }, 500);
    
    // Logout button hover effect
    const logoutBtn = document.querySelector('.floating-logout-btn button');
    if (logoutBtn) {
        logoutBtn.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-3px)';
            this.style.boxShadow = '0 6px 20px rgba(220, 53, 69, 0.5)';
        });
        
        logoutBtn.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 4px 15px rgba(220, 53, 69, 0.4)';
        });
    }
    
    // Calculate retirement from fetched DOB (FROM CODE 2)
    calculateRetirementFromFetchedDOB();
    
    // Remove event listeners for read-only fields (FROM CODE 2)
    const readOnlyFields = ['personalno', 'tename', 'tecnic', 'tebirthday', 'teretirement'];
    readOnlyFields.forEach(fieldId => {
        const field = document.getElementById(fieldId);
        if (field && field.readOnly) {
            // Disable any validation events on read-only fields
            field.removeEventListener('input', anyValidationFunction);
            field.removeEventListener('change', anyValidationFunction);
            field.removeEventListener('blur', anyValidationFunction);
            
            // Add visual indication
            field.style.backgroundColor = '#f9f9f9';
            field.style.color = '#666';
        }
    });
});

// ===== LOGOUT FUNCTION =====
function confirmLogout() {
    if (confirm('Are you sure you want to logout?')) {
        window.location.href = 'logout_emp.php';
    }
}

// ===== AJAX FUNCTIONS FOR DROPDOWNS =====
const $district = $('#district');
const $tehsil = $('#tehsil');
const $constituency = $('#constituency');
const $unionCouncil = $('#unionCouncil');

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: function() {
                alert("Error loading data.");
            }
        });
    } else {
        resetAllDependentDropdowns();
    }
}

function loadConstituencies() {
    const tehsil_id = $tehsil.val();
    
    if (tehsil_id) {
        $constituency.html('<option value="">Loading...</option>');
        $.ajax({
            url: 'fetch_constituencies.php',
            method: 'POST',
            data: { tehsil_id: tehsil_id },
            dataType: 'html',
            success: function(response) {
                $constituency.html(response).prop('disabled', false);
                resetDependentDropdowns([$unionCouncil]);
            },
            error: function() {
                alert("Error loading data.");
            }
        });
    } else {
        resetDependentDropdowns([$constituency, $unionCouncil]);
    }
}

function loadUnionCouncils() {
    const cons_id = $constituency.val();
    
    if (cons_id) {
        $unionCouncil.html('<option value="">Loading...</option>');
        $.ajax({
            url: 'fetch_ucs.php',
            method: 'POST',
            data: { cons_id: cons_id },
            dataType: 'html',
            success: function(response) {
                $unionCouncil.html(response).prop('disabled', false);
            },
            error: function() {
                alert("Error loading data.");
            }
        });
    } else {
        resetDependentDropdowns([$unionCouncil]);
    }
}

function resetDependentDropdowns(dropdowns) {
    dropdowns.forEach($dropdown => {
        $dropdown.html('<option value="">Select ' + $dropdown.attr('name').charAt(0).toUpperCase() + 
                      $dropdown.attr('name').slice(1) + '</option>').prop('disabled', true);
    });
}

function resetAllDependentDropdowns() {
    resetDependentDropdowns([$tehsil, $constituency, $unionCouncil]);
}

// ===== DATEPICKER =====
$(document).ready(function() {
    const dateFields = ['doapp', 'dojcp', 'tetimes', 'wtis'];
    
    dateFields.forEach(fieldId => {
        const $field = $('#' + fieldId);
        
        $field.datepicker({
            dateFormat: 'dd-mm-yy',
            changeMonth: true,
            changeYear: true,
            yearRange: '-100:+0',
            maxDate: 0,
            showOtherMonths: true,
            selectOtherMonths: true,
            beforeShowDay: function(date) { // FROM CODE 2
                var today = new Date();
                today.setHours(0, 0, 0, 0);
                return [date <= today, ""];
            },
            onSelect: function(dateText, inst) {
                const errorElement = document.getElementById(this.id + '-error');
                if (errorElement) errorElement.style.display = 'none';
                
                validateAllDates();
            },
            onClose: function(dateText, inst) { // FROM CODE 2
                validateAllDates();
            }
        }).on('keydown', function(e) { // FROM CODE 2
            if (e.keyCode === 13) {
                $(this).datepicker('hide');
                validateAllDates();
                e.preventDefault();
                return false;
            }
        }).on('blur', function() { // FROM CODE 2
            validateAllDates();
        });
    });
    
    // Disable datepicker for read-only fields (FROM CODE 2)
    const readOnlyDateFields = ['tebirthday'];
    readOnlyDateFields.forEach(fieldId => {
        const $field = $('#' + fieldId);
        if ($field.length) {
            $field.datepicker('destroy');
            $field.off('focus click');
            
            // Prevent any calendar popup
            $field.on('focus click', function(e) {
                e.preventDefault();
                this.blur();
                return false;
            });
        }
    });
});

function showDatePicker(fieldId) {
    // Don't show datepicker for read-only fields (FROM CODE 2)
    const field = document.getElementById(fieldId);
    if (field && field.readOnly) return;
    
    $('#' + fieldId).datepicker('show');
}

// Show all results when search box is clicked (even if already focused)
searchInput.addEventListener('click', function(e) {
    // Only show if not already showing
    if (searchResults.style.display !== 'block') {
        showSearchResults();
    }
});
</script>
   </body>
</html>