<!-- 
  **File Structure:**
  - school_step1.php (School Profile)
  - school_step2.php (School Land)
  - school_step3.php (School Building)
  - school_step4.php (School Facilities)
  - school_step5.php (School Posts)
  - school_step6.php (School Students)
  - school_step7.php (School Board Results)
  - school_step8.php (School Budget)
  - school_step9.php (School SMC)
  - school_step10.php (School Location and View)
  
  Here's the first file (school_step1.php):
    -->
	
<?php
//session started
require_once 'session_config_school.php';

// Validate school session
if (!validateSchoolSession()) {
    header("Location: login.php");
    exit;
}

// School Profile Completion Check
require_once 'school_profile_completion_check.php';

// Database connection
include_once 'connect.php';

// Initialize variables
$success_message = '';
$error_message = '';


// =================== NEW CODE: Fetch registration data ===================
$registration_data = [];
if (isset($_SESSION['emis_code'])) {
    $emis_code = $_SESSION['emis_code'];
    $sql = "SELECT 
        r.emis_code, 
        r.school_name, 
        r.cate_id as school_type_id,
        r.level_id as school_level_id,
		r.school_email as email,
        c.school_type, 
        l.level_name as school_level_name
    FROM registrations r
    JOIN school_cate c ON r.cate_id = c.cate_id
    JOIN school_level l ON r.level_id = l.level_id
    WHERE r.emis_code = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $emis_code);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $registration_data = $result->fetch_assoc();
    }
    $stmt->close();
}
// =================== END NEW CODE ===================

// If we have a emis_code in session, we're editing, so fetch existing data
$existing_data = [];
if (isset($_SESSION['emis_code'])) {
    $emis_code = $_SESSION['emis_code'];
    $sql = "SELECT * FROM school_profile WHERE emis_code = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $emis_code);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $existing_data = $result->fetch_assoc();
    }
    $stmt->close();
}

// Function to get field value with priority: registration data > existing data > POST data > empty
function getFieldValue($field_name, $default = '') {
    global $registration_data, $existing_data;
    
    // First priority: Registration data (if available)
    if (isset($registration_data[$field_name])) {
        return $registration_data[$field_name];
    }
    
    // Second priority: POST data
    if (isset($_POST[$field_name])) {
        return $_POST[$field_name];
    }
    
    // Third priority: Existing data from school_profile
    if (isset($existing_data[$field_name])) {
        return $existing_data[$field_name];
    }
    
    // Default value
    return $default;
}

// Function to get field ID value specifically for select fields
function getFieldIdValue($field_name, $default = '') {
    global $registration_data, $existing_data;
    
    // Map field names to their ID counterparts
    $id_field_map = [
        'school_type' => 'school_type_id',
        'school_level' => 'school_level_id',
        'school_gender' => 'school_gender_id',
        'education_mode' => 'education_mode_id',
        'school_shift' => 'school_shift_id',
        'school_status' => 'school_status_id'
    ];
    
    // First priority: Check if we have an ID field in registration data
    if (isset($id_field_map[$field_name]) && isset($registration_data[$id_field_map[$field_name]])) {
        return $registration_data[$id_field_map[$field_name]];
    }
    
    // Second priority: POST data (should already be ID)
    if (isset($_POST[$field_name])) {
        return $_POST[$field_name];
    }
    
    // Third priority: Existing data from school_profile
    if (isset($existing_data[$field_name])) {
        return $existing_data[$field_name];
    }
    
    // Default value
    return $default;
}

// Additional function to check if field should be disabled
function shouldDisableField($field_name) {
    global $registration_data;
    $disabled_fields = ['emis_code', 'school_name', 'school_type', 'school_level', 'email'];
    
    if (in_array($field_name, $disabled_fields) && !empty($registration_data)) {
        // Handle special cases where registration key differs from field name
        if ($field_name === 'school_level' && !empty($registration_data['school_level_id'])) {
            return true;
        }
        if ($field_name === 'school_type' && !empty($registration_data['school_type_id'])) {
            return true;
        }
        if (!empty($registration_data[$field_name])) {
            return true;
        }
    }
    return false;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>School Profile Registration - Step 1</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.3/themes/base/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.3/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
      * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      }
      body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background-color: #f5f7fa;
      color: #333;
      line-height: 1.6;
      }
      .container {
      max-width: 1200px; /* Increased from 1000px to 1200px for 10 steps */
      margin: 0 auto;
      padding: 20px;
      }
      .header {
      text-align: center;
      margin-bottom: 20px;
      padding: 25px;
      background: linear-gradient(135deg, #2c3e50, #4a6491);
      color: white;
      border-radius: 10px;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
      }
      .header h1 {
      font-size: 28px;
      margin-bottom: 10px;
      }
      .header p {
      opacity: 0.9;
      font-size: 16px;
      }
      
      /* Style for disabled fields */
        input:disabled, select:disabled {
            background-color: #f5f5f5;
            color: #666;
            cursor: not-allowed;
            border-color: #ddd;
        }
        
        /* Style for disabled field labels */
        .disabled-label {
            color: #7f8c8d;
        }
        
        /* Progress Container Styles - MOVED TO PROPER POSITION */
      .progress-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;
      position: relative;
      max-width: 100%;
      }
      
      .progress-container::before {
      content: "";
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 4px;
      background-color: #e0e0e0;
      transform: translateY(-50%);
      z-index: 1;
      }
      
      .progress-bar {
      position: absolute;
      top: 50%;
      left: 0;
      height: 4px;
      background-color: #3498db;
      transform: translateY(-50%);
      z-index: 2;
      transition: width 0.3s ease;
      width: 10%; /* Step 1: 10% complete */
      }
      
      .step {
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      z-index: 3;
      width: 100px;
      }
      
      .step span:first-child {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: #e0e0e0;
      color: #666;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
      margin-bottom: 8px;
      border: 3px solid white;
      transition: all 0.3s ease;
      }
      
      .step.completed span:first-child {
      background-color: #2ecc71;
      color: white;
      }
      
      .step.active span:first-child {
      background-color: #3498db;
      color: white;
      transform: scale(1.1);
      }
      
      .step-label {
      font-size: 12px;
      text-align: center;
      color: #666;
      font-weight: 500;
      max-width: 100px;
      word-wrap: break-word;
      }
      
      .step.completed .step-label {
      color: #2ecc71;
      }
      
      .step.active .step-label {
      color: #3498db;
      font-weight: 600;
      }
      
      /* Navigation Buttons */
      .navigation-buttons {
      display: flex;
      justify-content: space-between;
      margin-top: 40px;
      margin-bottom: 0;
      padding-top: 20px;
      border-top: 1px solid #eee;
      }
      
      .nav-btn {
      padding: 12px 10px;
      background: linear-gradient(135deg, #3498db, #2980b9);
      color: white;
      border: none;
      border-radius: 6px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      gap: 10px;
      width: auto;
      }
      
      .nav-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 15px rgba(52, 152, 219, 0.3);
      background: linear-gradient(135deg, #2980b9, #1f6399);
      }
      
      .nav-btn:active {
      transform: translateY(0);
      }
      
      .nav-btn:disabled {
      background: #95a5a6;
      cursor: not-allowed;
      transform: none;
      box-shadow: none;
      }
      
      .nav-btn.back {
      background: linear-gradient(135deg, #7f8c8d, #95a5a6);
      }
      
      .nav-btn.back:hover {
      background: linear-gradient(135deg, #95a5a6, #7f8c8d);
      box-shadow: 0 6px 15px rgba(127, 140, 141, 0.3);
      }
      
      .form-container {
      background: white;
      border-radius: 10px;
      border-left: 4px solid #3498db;
      padding: 30px 30px 0px 30px;
      box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
      margin-bottom: 0px;
      position: relative;
      min-height: auto;
      }
      
      /* MODIFIED: Form grid for exactly 2 columns */
      .form-grid {
      display: grid;
      grid-template-columns: 1fr 1fr; /* Exactly 2 columns */
      gap: 20px;
      margin-bottom: 20px;
      }
      
      .form-group {
      display: flex;
      flex-direction: column;
      }
      
      .form-group.full-width {
      grid-column: 1 / -1; /* Span across both columns */
      }
      
      label {
      margin-bottom: 8px;
      font-weight: 600;
      color: #2c3e50;
      font-size: 14px;
      }
      
      input[type="text"],
      input[type="email"],
      input[type="number"],
      select {
      padding: 12px 15px;
      border: 2px solid #e0e0e0;
      border-radius: 6px;
      font-size: 15px;
      transition: all 0.3s ease;
      background-color: white;
      width: 100%;
      }
      
      input[type="text"]:focus,
      input[type="email"]:focus,
      input[type="number"]:focus,
      select:focus {
      outline: none;
      border-color: #3498db;
      box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
      }
      
      select {
      cursor: pointer;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%23333' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14L2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
      background-repeat: no-repeat;
      background-position: right 15px center;
      background-size: 12px;
      padding-right: 40px;
      appearance: none;
      }
      
      .required::after {
      content: " *";
      color: #e74c3c;
      }
      
      .form-section {
      margin-bottom: 30px;
      padding-bottom: 25px;
      border-bottom: 1px solid #eee;
      }
      
      .form-section:last-child {
      border-bottom: none;
      }
      
      .section-title {
      font-size: 18px;
      color: #2c3e50;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 2px solid #3498db;
      display: flex;
      align-items: center;
      gap: 10px;
      }
      
      .section-title i {
      color: #3498db;
      }
      
      .submit-btn {
      display: block;
      width: 200px;
      margin: 30px auto 0;
      padding: 15px 30px;
      background: linear-gradient(135deg, #3498db, #2980b9);
      color: white;
      border: none;
      border-radius: 6px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      text-align: center;
      }
      
      .submit-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 15px rgba(52, 152, 219, 0.3);

      background: linear-gradient(135deg, #2980b9, #1f6399);
      }
      
      .submit-btn:active {
      transform: translateY(0);
      }
      
      .loading-spinner {
      display: inline-block;
      width: 20px;
      height: 20px;
      border: 3px solid rgba(255,255,255,.3);
      border-radius: 50%;
      border-top-color: #fff;
      animation: spin 1s ease-in-out infinite;
      margin-right: 10px;
      vertical-align: middle;
      }
      
      @keyframes spin {
      to { transform: rotate(360deg); }
      }
      
      .helper-text {
      font-size: 12px;
      color: #7f8c8d;
      margin-top: 5px;
      }
      
      .alert {
      padding: 15px;
      border-radius: 6px;
      margin-bottom: 20px;
      text-align: center;
      font-weight: 500;
      }
      
      .alert-success {
      background-color: #d4edda;
      color: #155724;
      border: 1px solid #c3e6cb;
      }
      
      .alert-error {
      background-color: #f8d7da;
      color: #721c24;
      border: 1px solid #f5c6cb;
      }
      
      .dropdown-container {
      position: relative;
      }
      
      .degradation-section {
      background-color: #fff8f8;
      padding: 20px;
      border-radius: 8px;
      border-left: 4px solid #e74c3c;
      margin-top: 20px;
      }
      
      .degradation-section .section-title {
      color: #c0392b;
      border-bottom-color: #e74c3c;
      }
      
      .school-info {
      background: #f8f9fa;
      padding: 15px;
      border-radius: 6px;
      margin-bottom: 20px;
      border-left: 4px solid #3498db;
      }
      
      .school-info h3 {
      color: #2c3e50;
      margin-bottom: 10px;
      font-size: 16px;
      }
      
      .school-info p {
      color: #666;
      font-size: 14px;
      }
      
      .validation-success {
      border-color: #2ecc71 !important;
      }
      
      .validation-error {
      border-color: #e74c3c !important;
      }
      
      /* Year input specific styles */
      .year-input-wrapper {
      position: relative;
      width: 100%;
      }
      
      .year-input-field {
      padding-right: 40px !important;
      cursor: pointer;
      }
      
      .year-picker-toggle {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      background: none;
      border: none;
      color: #3498db;
      cursor: pointer;
      font-size: 16px;
      padding: 5px;
      z-index: 2;
      }
      
      .year-picker-toggle:hover {
      color: #2980b9;
      }
      
      /* Compact year picker */
      .compact-year-picker {
      display: none;
      position: absolute;
      top: 100%;
      left: 0;
      width: 250px;
      background: white;
      border: 1px solid #ddd;
      border-radius: 8px;
      box-shadow: 0 5px 20px rgba(0,0,0,0.15);
      z-index: 1000;
      margin-top: 5px;
      padding: 10px;
      }
      
      .compact-year-picker.active {
      display: block;
      }
      
      .year-picker-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
      }
      
      .year-nav-btn {
      background: #f8f9fa;
      border: 1px solid #ddd;
      border-radius: 4px;
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      font-size: 14px;
      }
      
      .year-nav-btn:hover {
      background: #e9ecef;
      }
      
      .year-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 5px;
      max-height: 200px;
      overflow-y: auto;
      }
      
      .year-option {
      padding: 8px 5px;
      border: 1px solid #e9ecef;
      background: white;
      border-radius: 4px;
      text-align: center;
      cursor: pointer;
      font-size: 13px;
      transition: all 0.2s;
      }
      
      .year-option:hover {
      background: #f8f9fa;
      border-color: #3498db;
      }
      
      .year-option.selected {
      background: #3498db;
      color: white;
      border-color: #2980b9;
      }
      
      .current-year {
      border-color: #2ecc71 !important;
      font-weight: bold;
      }
      
      .future-year {
      opacity: 0.6;
      cursor: not-allowed !important;
      background-color: #f5f5f5;
      }
      
      .future-year:hover {
      background-color: #f5f5f5 !important;
      border-color: #e9ecef !important;
      }
      
      .year-range-display {
      font-weight: 600;
      color: #2c3e50;
      font-size: 14px;
      }
      
      .year-validation-error {
      color: #e74c3c;
      font-size: 12px;
      margin-top: 5px;
      display: none;
      }
      
      /* DDO Code Validation Styles */
      .error-message {
          font-size: 12px;
          color: #e74c3c;
          margin-top: 5px;
          display: none;
      }
      
      .required-field::after {
          content: " *";
          color: #e74c3c;
      }
      
      .format-indicator {
          font-size: 12px;
          margin-top: 5px;
          font-weight: normal;
      }
      
      .valid-format {
          color: #2ecc71;
      }
      
      .invalid-format {
          color: #e74c3c;
      }
      
      /* Responsive styles */
      @media (max-width: 768px) {
      .form-grid {
      grid-template-columns: 1fr; /* Stack on mobile */
      gap: 15px;
      }
      
      .form-container {
      padding: 20px;
      }
      
      .header h1 {
      font-size: 24px;
      }
      
      input[type="text"],
      input[type="email"],
      input[type="number"],
      select {
      padding: 10px 12px;
      font-size: 14px;
      }
      
      .submit-btn {
      width: 100%;
      max-width: 300px;
      }
      
      .compact-year-picker {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 90%;
      max-width: 300px;
      }
      
      /* Progress bar responsive */
      .progress-container {
      overflow-x: auto;
      padding-bottom: 20px;
      }
      
      .step {
      min-width: 80px;
      }
      
      .step-label {
      font-size: 10px;
      }
      
      .nav-btn {
      padding: 10px 20px;
      font-size: 14px;
      }
      }
      
      @media (max-width: 480px) {
      .container {
      padding: 10px;
      }
      
      .form-container {
      padding: 15px;
      }
      
      .header {
      padding: 15px;
      }
      }
      
      /* Debug styles */
      .debug-outline {
          border: 1px solid red !important;
      }
    </style>
</head>
<body>

<!-- Floating Logout Button -->
<?php include 'floating_logout_school.php'; ?>

<div class="container">
    <div class="header">
        <h1><i class="fas fa-school"></i> School Profile Registration - Step 1 of 10</h1>
        <p>Complete all 10 steps to register a new school in Districts Schools Management System</p>
    </div>
    
    <!-- Progress Container -->
    <div class="progress-container">
        <div class="progress-bar" id="progressBar"></div>
        <div class="step active" id="step1">
            <span>1</span>
            <span class="step-label">School Profile</span>
        </div>
        <div class="step" id="step2">
            <span>2</span>
            <span class="step-label">School Land</span>
        </div>
        <div class="step" id="step3">
            <span>3</span>
            <span class="step-label">School Building</span>
        </div>
        <div class="step" id="step4">
            <span>4</span>
            <span class="step-label">School Facilities</span>
        </div>
        <div class="step" id="step5">
            <span>5</span>
            <span class="step-label">School Posts</span>
        </div>
        <div class="step" id="step6">
            <span>6</span>
            <span class="step-label">Students</span>
        </div>
        <div class="step" id="step7">
            <span>7</span>
            <span class="step-label">Board Results</span>
        </div>
        <div class="step" id="step8">
            <span>8</span>
            <span class="step-label">Budget</span>
        </div>
        <div class="step" id="step9">
            <span>9</span>
            <span class="step-label">SMC</span>
        </div>
        <div class="step" id="step10">
            <span>10</span>
            <span class="step-label">Location & View</span>
        </div>
    </div>
    
    <?php if (!empty($registration_data)): ?>
<div class="school-info" style="background-color: #e8f4fd; border-left-color: #3498db;">
    <h3><i class="fas fa-info-circle"></i> Information Note</h3>
    <p style="color: red;">The <strong>School Name</strong>, <strong>School Type</strong>, <strong>School Level</strong>, <strong>EMIS Code</strong> and <strong>E.Male Address</strong>  fields are pre-filled from your registration data and cannot be modified. If you need to change these details, please contact the system administrator.</p>
</div>
<?php endif; ?>

    <div class="form-container">
        <form method="POST" action="" id="schoolForm">
            <div class="school-info">
                <h3><i class="fas fa-info-circle"></i> School Information</h3>
                <p>Fill in all fields to register the school profile. All fields marked with <span style="color: #e74c3c; font-weight: bold;">*</span> are necessary.</p>
            </div>
            
            
            <!-- Section 1: Basic School Information -->
            <div class="form-section">
                <h3 class="section-title"><i class="fas fa-info-circle"></i> Basic School Information</h3>
                <div class="form-grid">
                    <!-- School Name - Full width -->
                    <div class="form-group full-width">
                        <label for="school_name" class="required">School Name</label>
                        <input id="school_name" name="school_name" type="text" required
                               placeholder="Enter official school name" 
                               value="<?php echo htmlspecialchars(getFieldValue('school_name')); ?>"
                               <?php echo shouldDisableField('school_name') ? 'disabled' : ''; ?>>
                        <?php if (shouldDisableField('school_name')): ?>
                            <input type="hidden" name="school_name" value="<?php echo htmlspecialchars(getFieldValue('school_name')); ?>">
                        <?php endif; ?>
                    </div>
                    
                    <!-- Row 1: 2 columns -->
                    <div class="form-group">
                        <label for="school_type" class="required">School Type</label>
                        <select id="school_type" name="school_type" required 
                                <?php echo shouldDisableField('school_type') ? 'disabled' : ''; ?>>
                            <option value="">Select Type...</option>
                            <?php
                            $query = "SELECT cate_id, school_type FROM school_cate ORDER BY cate_id ASC";
                            $result = $conn->query($query);
                            
                            if ($result && $result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    // Use getFieldIdValue to get the ID
                                    $selected = (getFieldIdValue('school_type') == $row['cate_id']) ? 'selected' : '';
                                    echo '<option value="' . htmlspecialchars($row['cate_id']) . '" ' . $selected . '>'
                                        . htmlspecialchars($row['school_type']) .
                                        '</option>';
                                }
                            }
                            ?>
                        </select>
                        <?php if (shouldDisableField('school_type')): ?>
                            <?php $school_type_id = getFieldIdValue('school_type'); ?>
                            <input type="hidden" name="school_type" value="<?php echo htmlspecialchars($school_type_id); ?>">
                        <?php endif; ?>
                    </div>
                    
                <div class="form-group">
    <label for="level" class="required">School Level</label>
    <select id="level" name="school_level" required 
            <?php echo shouldDisableField('school_level') ? 'disabled' : ''; ?>>
        <option value="">Select Level...</option>
        <?php
        $query = "SELECT level_id, level_name FROM school_level ORDER BY level_id ASC";
        $result = $conn->query($query);
        
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                // Use getFieldIdValue to get the ID
                $selected = (getFieldIdValue('school_level') == $row['level_id']) ? 'selected' : '';
                echo '<option value="' . htmlspecialchars($row['level_id']) . '" ' . $selected . '>'
                    . htmlspecialchars($row['level_name']) .
                    '</option>';
            }
        }
        ?>
    </select>
    <?php if (shouldDisableField('school_level')): ?>
        <?php $school_level_id = getFieldIdValue('school_level'); ?>
        <input type="hidden" name="school_level" value="<?php echo htmlspecialchars($school_level_id); ?>">
    <?php endif; ?>
</div>
                    
                    <!-- Row 2: 2 columns -->
<div class="form-group">
    <label for="school_gender" class="required">Gender</label>
    <select id="school_gender" name="school_gender" required>
        <option value="">Select Gender...</option>
        <?php
        $query = "SELECT gender_id, gender_name FROM school_gender WHERE status = 1 ORDER BY gender_id ASC";
        $result = $conn->query($query);
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                // Use getFieldIdValue to get the ID
                $selected = (getFieldIdValue('school_gender') == $row['gender_id']) ? 'selected' : '';
                echo '<option value="' . htmlspecialchars($row['gender_id']) . '" ' . $selected . '>' . htmlspecialchars($row['gender_name']) . '</option>';
            }
        }
        ?>
    </select>
</div>
                    
<div class="form-group">
    <label for="education_mode" class="required">Education Mode</label>
    <select id="education_mode" name="education_mode" required>
        <option value="">Select Education Mode...</option>
        <?php
        $query = "SELECT mode_id, mode_name FROM education_mode WHERE status = 1 ORDER BY mode_id ASC";
        $result = $conn->query($query);
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                // Use getFieldIdValue to get the ID
                $selected = (getFieldIdValue('education_mode') == $row['mode_id']) ? 'selected' : '';
                echo '<option value="' . htmlspecialchars($row['mode_id']) . '" ' . $selected . '>' . htmlspecialchars($row['mode_name']) . '</option>';
            }
        }
        ?>
    </select>
</div>
                    
                    <!-- Row 3: 2 columns -->
<div class="form-group">
    <label for="school_shift" class="required">Shift</label>
    <select id="school_shift" name="school_shift" required>
        <option value="">Select Shift...</option>
        <?php
        $query = "SELECT shift_id, shift_name, short_description FROM school_shift WHERE status = 1 ORDER BY shift_id ASC";
        $result = $conn->query($query);
        
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                // Use getFieldIdValue to get the ID
                $selected = (getFieldIdValue('school_shift') == $row['shift_id']) ? 'selected' : '';
                echo '<option value="' . htmlspecialchars($row['shift_id']) . '" ' . $selected . '>' . htmlspecialchars($row['shift_name']) . ' - ' . htmlspecialchars($row['short_description']) . '</option>';
            }
        }
        ?>
    </select>
</div>
                    
                    <div class="form-group">
                        <!-- Empty div to maintain 2-column layout -->
                    </div>
                </div>
            </div>
            
            <!-- Section 2: Official Codes -->
            <div class="form-section">
                <h3 class="section-title"><i class="fas fa-id-card"></i> Official Codes</h3>
                <div class="form-grid">
                    <!-- Row 1: 2 columns -->
                <div class="form-group">
                    <label for="emis_code" class="required">EMIS Code</label>
                    <input id="emis_code" name="emis_code" type="text" required
                           placeholder="Enter EMIS Code" pattern="[A-Za-z0-9]{6,12}"
                           value="<?php echo htmlspecialchars(getFieldValue('emis_code')); ?>"
                           <?php echo shouldDisableField('emis_code') ? 'disabled' : ''; ?>>
                    <?php if (shouldDisableField('emis_code')): ?>
                        <input type="hidden" name="emis_code" value="<?php echo htmlspecialchars(getFieldValue('emis_code')); ?>">
                    <?php endif; ?>
                </div>
                    
<div class="form-group">
    <label for="ddo_code" class="required-field">DDO Code</label>
    <input id="ddo_code" name="ddo_code" type="text"
           maxlength="6"
           pattern="[A-Za-z]{2}\d{4}"
           title="First 2 letters followed by 4 digits (e.g., KJ0123)"
           placeholder="Enter DDO Code Like KJ0123"
           onkeypress="return allowDdoChars(event)"
           oninput="validateDdoCode(this)"
           onpaste="handleDdoPaste(event)"
           onblur="validateDdoCode(this)"
           required
           value="<?php echo htmlspecialchars(getFieldValue('ddo_code')); ?>">
    
    <div class="error-message" id="ddo_code-error">
        ❌ Must have exactly 2 letters followed by 4 digits (e.g., KJ0123)
    </div>
</div>


                    
                    <!-- Row 2: 2 columns -->
                    <div class="form-group">
                        <label for="school_branch" class="">School Branch</label>
                        <select id="school_branch" name="school_branch">
                            <option value="">Select Option...</option>
                            <option value="yes" <?php echo getFieldValue('school_branch') == 'yes' ? 'selected' : ''; ?>>Yes</option>
                            <option value="No" <?php echo getFieldValue('school_branch') == 'No' ? 'selected' : ''; ?>>No</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="school_bisp" class="">BISP Program</label>
                        <select id="school_bisp" name="school_bisp">
                            <option value="">Select BISP Option...</option>
                            <option value="Yes" <?php echo getFieldValue('school_bisp') == 'Yes' ? 'selected' : ''; ?>>Yes</option>
                            <option value="No" <?php echo getFieldValue('school_bisp') == 'No' ? 'selected' : ''; ?>>No</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <!-- Section 3: Establishment & Upgrade Years -->
            <div class="form-section">
                <h3 class="section-title"><i class="fas fa-calendar-alt"></i> Establishment & Upgradation History</h3>
                <div class="form-grid">
                    <!-- Row 1: 2 columns -->
                    <div class="form-group">
                        <label for="est_year" class="required">Establishment Year</label>
                        <div class="year-input-wrapper">
                            <input
                                id="est_year"
                                name="est_year"
                                type="text"
                                class="year-input-field"
                                placeholder="Type or click calendar icon"
                                autocomplete="off"
                                maxlength="4"
                                value="<?php echo htmlspecialchars(getFieldValue('est_year')); ?>"
                                required>
                            <button type="button" class="year-picker-toggle" data-target="est_year">
                                <i class="fas fa-calendar-alt"></i>
                            </button>
                            <div id="year-picker-est_year" class="compact-year-picker"></div>
                            <div class="year-validation-error" id="est_year_error"></div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="established_as" class="required">Established As</label>
                        <select id="established_as" name="established_as" required>
                            <option value="">Select Establishment Level...</option>
                            <?php
                            $query = "SELECT * FROM school_level ORDER BY level_id ASC";
                            $result = $conn->query($query);
                            
                            if ($result && $result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    $selected = getFieldValue('established_as') == $row['level_id'] ? 'selected' : '';
                                    echo '<option value="' . htmlspecialchars($row['level_id']) . '" ' . $selected . '>'
                                        . htmlspecialchars($row['level_name']) .
                                        '</option>';
                                }
                            }
                            ?>
                        </select>
                    </div>
                    
                    <!-- Row 2: 2 columns -->
                    <div class="form-group">
                        <label for="first_upgrade_year">1st Time Upgradation Year</label>
                        <div class="year-input-wrapper">
                            <input
                                id="first_upgrade_year"
                                name="first_upgrade_year"
                                type="text"
                                class="year-input-field"
                                placeholder="Type or click calendar icon"
                                autocomplete="off"
                                maxlength="4"
                                value="<?php echo htmlspecialchars(getFieldValue('first_upgrade_year')); ?>">
                            <button type="button" class="year-picker-toggle" data-target="first_upgrade_year">
                                <i class="fas fa-calendar-alt"></i>
                            </button>
                            <div id="year-picker-first_upgrade_year" class="compact-year-picker"></div>
                            <div class="year-validation-error" id="first_upgrade_year_error"></div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="first_upgrade_as">1st Time Upgradation As</label>
                        <select id="first_upgrade_as" name="first_upgrade_as">
                            <option value="">Select 1st Time Upgradation...</option>
                            <?php
                            $query = "SELECT * FROM school_level ORDER BY level_id ASC";
                            $result = $conn->query($query);
                            
                            if ($result && $result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    $selected = getFieldValue('first_upgrade_as') == $row['level_id'] ? 'selected' : '';
                                    echo '<option value="' . htmlspecialchars($row['level_id']) . '" ' . $selected . '>'
                                        . htmlspecialchars($row['level_name']) .
                                        '</option>';
                                }
                            }
                            ?>
                        </select>
                    </div>
                    
                    <!-- Row 3: 2 columns -->
                    <div class="form-group">
                        <label for="second_upgrade_year">2nd Time Upgradation Year</label>
                        <div class="year-input-wrapper">
                            <input
                                id="second_upgrade_year"
                                name="second_upgrade_year"
                                type="text"
                                class="year-input-field"
                                placeholder="Type or click calendar icon"
                                autocomplete="off"
                                maxlength="4"
                                value="<?php echo htmlspecialchars(getFieldValue('second_upgrade_year')); ?>">
                            <button type="button" class="year-picker-toggle" data-target="second_upgrade_year">
                                <i class="fas fa-calendar-alt"></i>
                            </button>
                            <div id="year-picker-second_upgrade_year" class="compact-year-picker"></div>
                            <div class="year-validation-error" id="second_upgrade_year_error"></div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="second_upgrade_as">2nd Time Upgradation As</label>
                        <select id="second_upgrade_as" name="second_upgrade_as">
                            <option value="">Select 2nd Time Upgradation...</option>
                            <?php
                            $query = "SELECT * FROM school_level ORDER BY level_id ASC";
                            $result = $conn->query($query);
                            
                            if ($result && $result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    $selected = getFieldValue('second_upgrade_as') == $row['level_id'] ? 'selected' : '';
                                    echo '<option value="' . htmlspecialchars($row['level_id']) . '" ' . $selected . '>'
                                        . htmlspecialchars($row['level_name']) .
                                        '</option>';
                                }
                            }
                            ?>
                        </select>
                    </div>
                    
                    <!-- Row 4: 2 columns -->
                    <div class="form-group">
                        <label for="third_upgrade_year">3rd Time Upgradation Year</label>
                        <div class="year-input-wrapper">
                            <input
                                id="third_upgrade_year"
                                name="third_upgrade_year"
                                type="text"
                                class="year-input-field"
                                placeholder="Type or click calendar icon"
                                autocomplete="off"
                                maxlength="4"
                                value="<?php echo htmlspecialchars(getFieldValue('third_upgrade_year')); ?>">
                            <button type="button" class="year-picker-toggle" data-target="third_upgrade_year">
                                <i class="fas fa-calendar-alt"></i>
                            </button>
                            <div id="year-picker-third_upgrade_year" class="compact-year-picker"></div>
                            <div class="year-validation-error" id="third_upgrade_year_error"></div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="third_upgrade_as">3rd Time Upgradation As</label>
                        <select id="third_upgrade_as" name="third_upgrade_as">
                            <option value="">Select 3rd Time Upgradation...</option>
                            <?php
                            $query = "SELECT * FROM school_level ORDER BY level_id ASC";
                            $result = $conn->query($query);
                            
                            if ($result && $result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    $selected = getFieldValue('third_upgrade_as') == $row['level_id'] ? 'selected' : '';
                                    echo '<option value="' . htmlspecialchars($row['level_id']) . '" ' . $selected . '>'
                                        . htmlspecialchars($row['level_name']) .
                                        '</option>';
                                }
                            }
                            ?>
                        </select>
                    </div>
                </div>
            </div>
            
            <!-- Section 4: Degradation Years -->
            <div class="form-section degradation-section">
                <h3 class="section-title"><i class="fas fa-exclamation-triangle"></i> Degradation History (If Applicable)</h3>
                <div class="form-grid">
                    <!-- Row 1: 2 columns -->
                    <div class="form-group">
                        <label for="first_degrade_year">1st Time Degradation Year</label>
                        <div class="year-input-wrapper">
                            <input
                                id="first_degrade_year"
                                name="first_degrade_year"
                                type="text"
                                class="year-input-field"
                                placeholder="Type or click calendar icon"
                                autocomplete="off"
                                maxlength="4"
                                value="<?php echo htmlspecialchars(getFieldValue('first_degrade_year')); ?>">
                            <button type="button" class="year-picker-toggle" data-target="first_degrade_year">
                                <i class="fas fa-calendar-alt"></i>
                            </button>
                            <div id="year-picker-first_degrade_year" class="compact-year-picker"></div>
                            <div class="year-validation-error" id="first_degrade_year_error"></div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="first_degrade_as">1st Time Degradation As</label>
                        <select id="first_degrade_as" name="first_degrade_as">
                            <option value="">Select 1st Time Degradation...</option>
                            <?php
                            $query = "SELECT * FROM school_level ORDER BY level_id ASC";
                            $result = $conn->query($query);
                            
                            if ($result && $result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    $selected = getFieldValue('first_degrade_as') == $row['level_id'] ? 'selected' : '';
                                    echo '<option value="' . htmlspecialchars($row['level_id']) . '" ' . $selected . '>'
                                        . htmlspecialchars($row['level_name']) .
                                        '</option>';
                                }
                            }
                            ?>
                        </select>
                    </div>
                    
                    <!-- Row 2: 2 columns -->
                    <div class="form-group">
                        <label for="second_degrade_year">2nd Time Degradation Year</label>
                        <div class="year-input-wrapper">
                            <input
                                id="second_degrade_year"
                                name="second_degrade_year"
                                type="text"
                                class="year-input-field"
                                placeholder="Type or click calendar icon"
                                autocomplete="off"
                                maxlength="4"
                                value="<?php echo htmlspecialchars(getFieldValue('second_degrade_year')); ?>">
                            <button type="button" class="year-picker-toggle" data-target="second_degrade_year">
                                <i class="fas fa-calendar-alt"></i>
                            </button>
                            <div id="year-picker-second_degrade_year" class="compact-year-picker"></div>
                            <div class="year-validation-error" id="second_degrade_year_error"></div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="second_degrade_as">2nd Time Degradation As</label>
                        <select id="second_degrade_as" name="second_degrade_as">
                            <option value="">Select 2nd Time Degradation...</option>
                            <?php
                            $query = "SELECT * FROM school_level ORDER BY level_id ASC";
                            $result = $conn->query($query);
                            
                            if ($result && $result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    $selected = getFieldValue('second_degrade_as') == $row['level_id'] ? 'selected' : '';
                                    echo '<option value="' . htmlspecialchars($row['level_id']) . '" ' . $selected . '>'
                                        . htmlspecialchars($row['level_name']) .
                                        '</option>';
                                }
                            }
                            ?>
                        </select>
                    </div>
                </div>
            </div>
            
            <!-- Section 5: Administrative Location -->
            <div class="form-section">
                <h3 class="section-title"><i class="fas fa-globe"></i> Administrative Location</h3>
                <div class="form-grid">
                    <!-- Row 1: 2 columns -->
                    <div class="form-group">
                        <label for="district" class="required">District</label>
                        <div class="dropdown-container">
                            <select id="district" name="district_id" required>
                                <option value="">Select District...</option>
                                <?php
                                $query = "SELECT * FROM districts WHERE status = 1 AND district_id BETWEEN 1 AND 10 ORDER BY district_name ASC";
                                $result = $conn->query($query);
                                if ($result && $result->num_rows > 0) {
                                    while ($row = $result->fetch_assoc()) {
                                        $selected = getFieldValue('district_id') == $row['district_id'] ? 'selected' : '';
                                        echo '<option value="' . $row['district_id'] . '" ' . $selected . '>' . htmlspecialchars($row['district_name']) . '</option>';
                                    }
                                } else {
                                    echo '<option value="">District Not Available</option>';
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="tehsil" class="required">Tehsil</label>
                        <div class="dropdown-container">
                            <select id="tehsil" name="tehsil_id" required>
                                <option value="">Select District First...</option>
                            </select>
                        </div>
                    </div>
                    
                    <!-- Row 2: 2 columns -->
                    <div class="form-group">
                        <label for="constituency" class="required">Constituency</label>
                        <div class="dropdown-container">
                            <select id="constituency" name="constituency_id" required>
                                <option value="">Select Tehsil First...</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="union_councils" class="required">Union Council</label>
                        <div class="dropdown-container">
                            <select id="union_councils" name="union_council_id" required>
                                <option value="">Select Constituency First...</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Section 6: Local Location Information -->
            <div class="form-section">
                <h3 class="section-title"><i class="fas fa-map-marker-alt"></i> Local Location Information</h3>
                <div class="form-grid">
                    <!-- Row 1: 2 columns -->
                    <div class="form-group">
                        <label for="village" class="required">Village/Town</label>
                        <input id="village" name="village" type="text" required
                               placeholder="Enter village/town name"
                               value="<?php echo htmlspecialchars(getFieldValue('village')); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="post_office" class="required">Post Office</label>
                        <input id="post_office" name="post_office" type="text" required
                               placeholder="Enter post office"
                               value="<?php echo htmlspecialchars(getFieldValue('post_office')); ?>">
                    </div>
                    
                    <!-- Row 2: 2 columns -->
                    <div class="form-group">
                        <label for="locality" class="required">Locality</label>
                        <select id="locality" name="locality" required>
                            <option value="">Select Locality...</option>
                            <option value="Rural" <?php echo getFieldValue('locality') == 'Rural' ? 'selected' : ''; ?>>Rural</option>
                            <option value="Urban" <?php echo getFieldValue('locality') == 'Urban' ? 'selected' : ''; ?>>Urban</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="zone" class="required">Station Type</label>
                        <select id="zone" name="zone" required>
                            <option value="">Select Station Type...</option>
                            <option value="Winter Station" <?php echo getFieldValue('zone') == 'Winter Station' ? 'selected' : ''; ?>>Winter Station</option>
                            <option value="Summer Station" <?php echo getFieldValue('zone') == 'Summer Station' ? 'selected' : ''; ?>>Summer Station</option>
                        </select>
                    </div>
                    
                    <!-- Row 3: 2 columns -->
                    <div class="form-group">
                        <label for="school_loc">School on LOC</label>
                        <select id="school_loc" name="school_loc">
                            <option value="">Select Option...</option>
                            <option value="Yes" <?php echo getFieldValue('school_loc') == 'Yes' ? 'selected' : ''; ?>>Yes</option>
                            <option value="No" <?php echo getFieldValue('school_loc') == 'No' ? 'selected' : ''; ?>>No</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="distance">Distance from Main Road (KM)</label>
                        <input
                            id="distance"
                            name="distance_from_road"
                            type="text"
                            inputmode="decimal"
                            pattern="^\d*\.?\d*$"
                            placeholder="Enter distance in kilometers"
                            oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
                            value="<?php echo htmlspecialchars(getFieldValue('distance_from_road')); ?>"
                        >
                    </div>
                </div>
            </div>
            
            <!-- Section 7: Status Information -->
            <div class="form-section">
                <h3 class="section-title"><i class="fas fa-cog"></i> Status Information</h3>
                <div class="form-grid">
                    <!-- Row 1: 2 columns -->
                    <div class="form-group">
                        <label for="status" class="required">School Status</label>
                        <select id="status" name="school_status" required>
                            <option value="">Select Status...</option>
                            <?php
                            $query = "SELECT status_id, status_name, status_urdu FROM school_status ORDER BY status_id ASC";
                            $result = $conn->query($query);
                            
                            if ($result && $result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    // Use getFieldIdValue to get the ID
                                    $selected = (getFieldIdValue('school_status') == $row['status_id']) ? 'selected' : '';
                                    echo '<option value="' . htmlspecialchars($row['status_id']) . '" ' . $selected . '>'
                                        . htmlspecialchars($row['status_name']) . ' - ' . htmlspecialchars($row['status_urdu']) 
                                        . '</option>';
                                }
                            }
                            ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <!-- Empty div to maintain 2-column layout -->
                    </div>
                </div>
            </div>
            
            <!-- Section 8: Contact Information -->
            <div class="form-section">
                <h3 class="section-title"><i class="fas fa-address-book"></i> Contact Information</h3>
                <div class="form-grid">
                    <!-- Row 1: 2 columns -->
                    <div class="form-group">
                        <label for="contact_no" class="required">Contact Number</label>
                        <input id="contact_no" name="contact_no" type="text" required
                               placeholder="Enter school phone number"
                               value="<?php echo htmlspecialchars(getFieldValue('contact_no', '03')); ?>" maxlength="11">
                    </div>
                    
                    <div class="form-group">
                        <label for="whatsApp_no" class="required">WhatsApp No (You can edit it if WhatsApp is on another number)</label>
                        <input id="whatsApp_no" name="whatsapp_no" type="text" required
                               placeholder="Enter WhatsApp number"
                               value="<?php echo htmlspecialchars(getFieldValue('whatsapp_no', getFieldValue('contact_no', '03'))); ?>">
                    </div>
                    
                    <!-- Row 2: 2 columns -->
					<div class="form-group">
                        <label for="email" class="">Email Address</label>
                        <input id="email" name="email" type="email"
                            placeholder="Enter school email address"
                            value="<?php echo htmlspecialchars(getFieldValue('email')); ?>"
                            <?php echo shouldDisableField('email') ? 'disabled' : ''; ?>>
                        <?php if (shouldDisableField('email')): ?>
                            <input type="hidden" name="email" value="<?php echo htmlspecialchars(getFieldValue('email')); ?>">
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group">
                        <!-- Empty div to maintain 2-column layout -->
                    </div>
                </div>

                <!-- Navigation Buttons -->
                <div class="navigation-buttons">
                    <button type="submit" class="nav-btn" id="submitBtn" style="margin-left: auto;">
                        <span id="btnText">Save & Continue</span>
                        <span id="btnLoading" style="display: none;">
                            <span class="loading-spinner"></span> Processing...
                        </span>
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>  

<script>
// =================== DDO CODE VALIDATION FUNCTIONS ===================

// Function to restrict input to DDO format: first 2 letters, next 4 digits
function allowDdoChars(event) {
    const charCode = event.which ? event.which : event.keyCode;
    const input = event.target;
    const currentValue = input.value;
    const position = input.selectionStart;
    
    // Allow backspace, delete, tab, arrows
    if (charCode === 8 || charCode === 46 || charCode === 9 || 
        charCode === 37 || charCode === 39) {
        return true;
    }
    
    // First 2 positions: only allow letters
    if (position < 2) {
        // Check if it's a letter (A-Z or a-z)
        if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
            return true;
        }
        return false;
    }
    
    // Positions 2-5: only allow digits
    if (position >= 2 && position <= 5) {
        // Check if it's a digit (0-9)
        if (charCode >= 48 && charCode <= 57) {
            // Don't allow more than 6 characters total
            if (currentValue.length >= 6) {
                return false;
            }
            return true;
        }
        return false;
    }
    
    // Don't allow typing beyond 6 characters
    if (currentValue.length >= 6) {
        return false;
    }
    
    return false;
}

// Function to validate DDO code format
function validateDdoCode(input) {
    let value = input.value;
    const errorElement = document.getElementById('ddo_code-error');
    
    // Auto uppercase first two letters
    if (value.length <= 2) {
        value = value.toUpperCase();
        input.value = value;
    } else if (value.length > 2) {
        const letters = value.substring(0, 2).toUpperCase();
        const numbers = value.substring(2).replace(/\D/g, ''); // Remove non-digits
        // Ensure we only take first 4 digits
        const digits = numbers.substring(0, 4);
        value = letters + digits;
        input.value = value;
    }
    
    // Check validation
    const isValid = /^[A-Z]{2}\d{4}$/.test(value);
    

    if (value.length > 0 && !isValid) {
        errorElement.style.display = 'block';
        errorElement.innerHTML = '❌ Must have exactly 2 letters followed by 4 digits (e.g., KJ0123)';
        input.style.borderColor = '#e74c3c';
        input.setCustomValidity('Invalid DDO code format');
    } else {
        errorElement.style.display = 'none';
        input.style.borderColor = isValid ? '#2ecc71' : '#e0e0e0';
        input.setCustomValidity('');
    }
    
    return isValid;
}

// Function to handle paste events for DDO code
function handleDdoPaste(event) {
    event.preventDefault();
    const pasteData = event.clipboardData.getData('text');
    let cleanedData = '';
    
    // First extract letters (max 2)
    let letters = pasteData.match(/[A-Za-z]/g);
    if (letters) {
        letters = letters.slice(0, 2).join('').toUpperCase();
        cleanedData += letters;
    }
    
    // Then extract digits (max 4)
    let digits = pasteData.match(/\d/g);
    if (digits) {
        digits = digits.slice(0, 4).join('');
        cleanedData += digits;
    }
    
    // Trim to 6 characters max
    cleanedData = cleanedData.substring(0, 6);
    
    // Insert at cursor position
    const input = event.target;
    const startPos = input.selectionStart;
    const endPos = input.selectionEnd;
    
    // Replace selected text with cleaned data
    const currentValue = input.value;
    const newValue = currentValue.substring(0, startPos) + 
                    cleanedData + 
                    currentValue.substring(endPos);
    
    // Apply formatting rules
    input.value = newValue.substring(0, 6);
    
    // Auto-uppercase first 2 characters if they are letters
    if (input.value.length > 0) {
        let formattedValue = input.value;
        if (formattedValue.length >= 2) {
            const firstTwo = formattedValue.substring(0, 2);
            const rest = formattedValue.substring(2);
            formattedValue = firstTwo.toUpperCase() + rest;
        } else {
            formattedValue = formattedValue.toUpperCase();
        }
        input.value = formattedValue;
    }
    
    // Trigger validation
    validateDdoCode(input);
}

// Function to add visual format helper
function addDdoFormatHelper() {
    const ddoInput = document.getElementById('ddo_code');
    
    // Create format indicator element
    const indicator = document.createElement('div');
    indicator.id = 'ddo-format-indicator';
    indicator.className = 'format-indicator';
    indicator.style.fontSize = '12px';
    indicator.style.marginTop = '5px';
    indicator.style.fontWeight = 'normal';
    
    // Insert indicator after input
    ddoInput.parentNode.insertBefore(indicator, ddoInput.nextSibling.nextSibling);
    
    ddoInput.addEventListener('focus', function() {
        if (this.value === '') {
            //this.placeholder = 'LLNNNN (2 letters, 4 digits)';
        }
    });
    
    ddoInput.addEventListener('blur', function() {
        this.placeholder = 'Enter DDO Code Like KJ0123';
    });
    
    // Show format indicator
    ddoInput.addEventListener('input', function() {
        const formatIndicator = document.getElementById('ddo-format-indicator');
        
        if (this.value.length === 0) {
            formatIndicator.textContent = 'Format: KJ0123';
            formatIndicator.style.color = '#7f8c8d';
        } else if (/^[A-Za-z]{2}\d{4}$/.test(this.value)) {
            //formatIndicator.textContent = '✓ Valid format';
            formatIndicator.style.color = '#2ecc71';
        } else {
            //formatIndicator.textContent = 'Format: 2 letters + 4 digits';
            formatIndicator.style.color = '#e74c3c';
        }
    });
}

// Initialize DDO format helper when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    addDdoFormatHelper();
});

// =================== END DDO CODE VALIDATION FUNCTIONS ===================

$(document).ready(function() {
    console.log('Document ready, initializing components...');
    
    // Check if jQuery UI is loaded
    if (!$.ui) {
        console.error('jQuery UI not loaded! Check your network connection.');
    } else {
        console.log('jQuery UI version:', $.ui.version);
    }
    
    // Initialize components
    initializeComponents();
    
    // Test year picker functionality
    setTimeout(testYearPicker, 500);
    
    // Initialize DDO validation on existing value
    if ($('#ddo_code').val()) {
        validateDdoCode(document.getElementById('ddo_code'));
    }
});

function initializeComponents() {
    const currentYear = new Date().getFullYear();
    let activeYearPicker = null;
    let whatsappManuallyEdited = false;
    
    // Initialize WhatsApp edit flag based on current values
    if ($('#contact_no').val() !== $('#whatsApp_no').val()) {
        whatsappManuallyEdited = true;
    }
    
    // Function to validate year
    function validateYear(year, fieldId) {
        const errorElement = $('#' + fieldId + '_error');
        
        if (!year) {
            errorElement.hide();
            return true; // Empty is allowed for optional fields
        }
        
        if (!/^\d{4}$/.test(year)) {
            errorElement.text('Please enter a valid 4-digit year').show();
            return false;
        }
        
        const yearNum = parseInt(year);
        
        if (yearNum < 1900) {
            errorElement.text('Year cannot be before 1900').show();
            return false;
        }
        
        if (yearNum > currentYear) {
            errorElement.text('Future years are not allowed').show();
            return false;
        }
        
        errorElement.hide();
        return true;
    }
    
    // Initialize year pickers for all year input fields
    function initializeYearPickers() {
        console.log('Initializing year pickers...');
        
        $('.year-input-field').each(function() {
            const fieldId = $(this).attr('id');
            const pickerId = 'year-picker-' + fieldId;
            const picker = $('#' + pickerId);
            const input = $(this);
            
            console.log('Creating year picker for:', fieldId, 'picker element:', picker.length);
            
            if (picker.length === 0) {
                console.error('Year picker element not found:', pickerId);
                return;
            }
            
            // Generate initial year grid centered on current year
            generateYearGrid(picker, currentYear);
            
            // Update selection if field has value
            if (input.val()) {
                updateYearSelection(picker, input.val());
                validateYear(input.val(), fieldId);
            }
        });
        
        console.log('Year pickers initialized:', $('.year-input-field').length);
    }
    
    // Generate year grid for a specific picker
    function generateYearGrid(picker, centerYear) {
        const year = parseInt(centerYear) || currentYear;
        const startYear = Math.max(1900, year - 12);
        const endYear = Math.min(currentYear, year + 3);
        
        let html = `
            <div class="year-picker-header">
                <button type="button" class="year-nav-btn prev-decade" title="Previous decade">
                    <i class="fas fa-chevron-left"></i>
                </button>
                <span class="year-range-display">${startYear} - ${endYear}</span>
                <button type="button" class="year-nav-btn next-decade" title="Next decade">
                    <i class="fas fa-chevron-right"></i>
                </button>
            </div>
            <div class="year-grid">
        `;
        
        for (let y = startYear; y <= endYear; y++) {
            const isCurrent = y === currentYear;
            const isSelected = parseInt(picker.data('selected-year')) === y;
            const isFuture = y > currentYear;
            const currentClass = isCurrent ? 'current-year' : '';
            const selectedClass = isSelected ? 'selected' : '';
            const futureClass = isFuture ? 'future-year' : '';
            
            html += `
                <div class="year-option ${currentClass} ${selectedClass} ${futureClass}" 
                     data-year="${y}" 
                     ${isFuture ? 'title="Future years are not allowed"' : ''}>
                    ${y}
                </div>
            `;
        }
        
        html += '</div>';
        picker.html(html);
        picker.data('current-range', {start: startYear, end: endYear});
        
        // Add event listeners to year options
        picker.find('.year-option').on('click', function() {
            if ($(this).hasClass('future-year')) {
                return;
            }
            
            const selectedYear = $(this).data('year');
            const inputId = picker.attr('id').replace('year-picker-', '');
            const inputField = $('#' + inputId);
            
            // Update input field
            inputField.val(selectedYear).trigger('change');
            
            // Update selection visual
            updateYearSelection(picker, selectedYear);
            
            // Validate the selected year
            validateYear(selectedYear, inputId);
            
            // Close picker
            picker.removeClass('active');
            activeYearPicker = null;
            
            console.log('Year selected:', selectedYear, 'for field:', inputId);
        });
        
        // Add event listeners to navigation buttons
        picker.find('.prev-decade').on('click', function(e) {
            e.stopPropagation();
            const range = picker.data('current-range');
            const newCenterYear = Math.max(1900, range.start - 8);
            generateYearGrid(picker, newCenterYear);
        });
        
        picker.find('.next-decade').on('click', function(e) {
            e.stopPropagation();
            const range = picker.data('current-range');
            const newCenterYear = Math.min(currentYear, range.end + 8);
            generateYearGrid(picker, newCenterYear);
        });
    }
    
    // Update year selection in picker
    function updateYearSelection(picker, year) {
        picker.find('.year-option').removeClass('selected');
        picker.find(`.year-option[data-year="${year}"]`).addClass('selected');
        picker.data('selected-year', year);
    }
    
    // Toggle year picker - using event delegation
    $(document).on('click', '.year-picker-toggle', function(e) {
        e.stopPropagation();
        const targetId = $(this).data('target');
        const picker = $('#year-picker-' + targetId);
        
        console.log('Year picker toggle clicked for:', targetId, 'picker found:', picker.length);
        
        if (picker.length === 0) {
            console.error('Year picker not found for:', targetId);
            return;
        }
        
        // Close other open pickers
        $('.compact-year-picker').not(picker).removeClass('active');
        
        // Toggle current picker
        picker.toggleClass('active');
        
        // Update active picker reference
        if (picker.hasClass('active')) {
            activeYearPicker = picker;
            console.log('Year picker opened for:', targetId);
        } else {
            activeYearPicker = null;
            console.log('Year picker closed for:', targetId);
        }
    });
    
    // Close picker when clicking outside
    $(document).on('click', function(e) {
        if (activeYearPicker && !$(e.target).closest('.compact-year-picker, .year-picker-toggle').length) {
            activeYearPicker.removeClass('active');
            activeYearPicker = null;
            console.log('Year picker closed (clicked outside)');
        }
    });
    
    // Handle typing in year input fields
    $('.year-input-field').on('input', function() {
        const value = $(this).val();
        const fieldId = $(this).attr('id');
        const picker = $('#year-picker-' + fieldId);
        
        // Only update if it's a valid year
        if (value === '') {
            // Empty is valid → represents NULL
            updateYearSelection(picker, null);
        } else if (/^\d{4}$/.test(value)) {
            const year = parseInt(value, 10);
            if (year >= 1900 && year <= currentYear) {
                updateYearSelection(picker, year);
            }
        }
        
        // Validate on input
        validateYear(value, fieldId);
    });
    
    // Validate year input on blur
    $('.year-input-field').on('blur', function() {
        const value = $(this).val();
        const fieldId = $(this).attr('id');
        
        validateYear(value, fieldId);
        
        if (value === '') {
            // NULL is valid
            $(this).removeClass('validation-error validation-success');
        } else if (!/^\d{4}$/.test(value)) {
            $(this).addClass('validation-error');
        } else {
            const year = parseInt(value, 10);
            if (year < 1900 || year > currentYear) {
                $(this).addClass('validation-error');
            } else {
                $(this).removeClass('validation-error').addClass('validation-success');
            }
        }
    });
    
    // Only allow numbers in year fields
    $('.year-input-field').on('keypress', function(e) {
        const charCode = e.which ? e.which : e.keyCode;
    
        // Prevent leading zero (0000)
        if ($(this).val().length === 0 && charCode === 48) {
            return false;
        }
    
        // Only allow digits
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        
        // Limit to 4 digits
        if ($(this).val().length >= 4) {
            return false;
        }
        
        return true;
    });

    
    // Prevent pasting non-numeric values
    $('.year-input-field').on('paste', function(e) {
        const pasteData = e.originalEvent.clipboardData.getData('text');
        if (!/^\d+$/.test(pasteData)) {
            e.preventDefault();
        }
        
        // Check if paste will exceed 4 characters
        if ($(this).val().length + pasteData.length > 4) {
            e.preventDefault();
        }
    });
    
    // Initialize all year pickers
    initializeYearPickers();
    
    // Helper function to show alerts
    function showAlert(message, type) {
        // Remove existing alerts
        $('.alert').remove();
        
        const alertClass = type === 'success' ? 'alert-success' : 'alert-error';
        const icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
        
        const alertHtml = `
            <div class="alert ${alertClass}">
                <i class="fas ${icon}"></i> ${message}
            </div>
        `;
        
        // Insert after header
        $('.header').after(alertHtml);
        
        // Auto-hide success alerts after 5 seconds
        if (type === 'success') {
            setTimeout(function() {
                $('.alert-success').fadeOut(300, function() {
                    $(this).remove();
                });
            }, 5000);
        }
    }
    
    /* ===== CONTACT NUMBER ===== */
    $('#contact_no').on('input', function () {
        let value = $(this).val().toString(); // Force string
        
        // Remove any non-digit characters
        value = value.replace(/\D/g, '');
        
        // Ensure it starts with 03
        if (!value.startsWith('03')) {
            value = '03' + value.replace(/^03/, '');
        }
        
        // Limit to 11 digits
        if (value.length > 11) {
            value = value.substring(0, 11);
        }
        
        $(this).val(value);
        
        // Auto-copy to WhatsApp ONLY if user hasn't edited WhatsApp
        if (!whatsappManuallyEdited) {
            $('#whatsApp_no').val(value.toString()); // Force string
        }
    });
    
    /* ===== WHATSAPP NUMBER ===== */
    $('#whatsApp_no').on('input', function () {
        whatsappManuallyEdited = true;
        
        let value = $(this).val().toString(); // Force string
        
        // Remove any non-digit characters
        value = value.replace(/\D/g, '');
        
        // Ensure it starts with 03
        if (!value.startsWith('03')) {
            value = '03' + value.replace(/^03/, '');
        }
        
        // Limit to 11 digits
        if (value.length > 11) {
            value = value.substring(0, 11);
        }
        
        $(this).val(value);
    });

    // Prevent deleting 03 in both fields
    $('#contact_no, #whatsApp_no').on('keydown', function (e) {
        if (this.selectionStart <= 2 && (e.key === 'Backspace' || e.key === 'Delete')) {
            e.preventDefault();
        }
    });
    
    // Form validation and AJAX submission - FIXED VERSION
    $('#schoolForm').on('submit', function(e) {
        e.preventDefault();
        console.log('Form submit triggered');
        
        // IMPORTANT FIX: Enable all disabled fields before form submission
        $(this).find('select:disabled, input:disabled').each(function() {
            $(this).prop('disabled', false);
        });
        
        let isValid = true;
        const yearFields = $('.year-input-field');
        
        // Clear previous error styling
        $('input[required], select[required]').css('border-color', '#e0e0e0');
        $('.year-validation-error').hide();
        
        // Validate DDO code
        const ddoCode = $('#ddo_code').val();
        const ddoRegex = /^[A-Za-z]{2}\d{4}$/;
        if (!ddoRegex.test(ddoCode)) {
            isValid = false;
            $('#ddo_code').css('border-color', '#e74c3c');
            $('#ddo_code-error').show();
            console.log('Invalid DDO code:', ddoCode);
        }
        
        // Basic validation for required fields
        $('input[required], select[required]').each(function() {
            if (!$(this).val()) {
                isValid = false;
                $(this).css('border-color', '#e74c3c');
                console.log('Missing required field:', $(this).attr('name'));
            }
        });
        
        // Validate year fields
        yearFields.each(function() {
            const value = $(this).val();
            const fieldId = $(this).attr('id');
            
            // For required year fields (est_year)
            if ($(this).is('[required]') && !value) {
                isValid = false;
                $(this).css('border-color', '#e74c3c');
                $('#' + fieldId + '_error').text('This field is required').show();
            }
            
            // Validate year format and range
            if (value && !validateYear(value, fieldId)) {
                isValid = false;
                $(this).css('border-color', '#e74c3c');
            }
        });
        
        // Validate contact numbers
        const contactNo = $('#contact_no').val();
        const whatsappNo = $('#whatsApp_no').val();
        
        // Simple validation for phone numbers (must start with 03 and have 11 digits)
        if (contactNo && (!contactNo.startsWith('03') || contactNo.length !== 11)) {
            isValid = false;
            $('#contact_no').css('border-color', '#e74c3c');
        }
        
        if (whatsappNo && (!whatsappNo.startsWith('03') || whatsappNo.length !== 11)) {
            isValid = false;
            $('#whatsApp_no').css('border-color', '#e74c3c');
        }
        
        // Email validation
        const email = $('#email').val();
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (email && !emailRegex.test(email)) {
            isValid = false;
            $('#email').css('border-color', '#e74c3c');
        }
        
        if (!isValid) {
            showAlert('Please fill all required fields correctly. Future years are not allowed.', 'error');
            // Re-disable fields if validation failed
            $('select[data-was-disabled], input[data-was-disabled]').prop('disabled', true);
            return false;
        }
        
        // Show loading state
        $('#btnText').hide();
        $('#btnLoading').show();
        $('#submitBtn').prop('disabled', true);
        console.log('Form is valid, preparing to submit...');
        
        // Collect form data
        const formData = new FormData(this);
        console.log('FormData collected, sending AJAX request...');
        
        // Send AJAX request to save handler
        $.ajax({
            url: 'school_step1_save.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                console.log('AJAX response:', response);
                
                if (response.success) {
                    showAlert(response.message, 'success');
                    
                    // Redirect after 1 seconds
                    if (response.redirect) {
                        setTimeout(function() {
                            window.location.href = response.redirect;
                        }, 1000);
                    } else {
                        // Enable button again if no redirect
                        $('#btnText').show();
                        $('#btnLoading').hide();
                        $('#submitBtn').prop('disabled', false);
                    }
                } else {
                    showAlert(response.message, 'error');
                    $('#btnText').show();
                    $('#btnLoading').hide();
                    $('#submitBtn').prop('disabled', false);
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', error, 'Status:', status);
                showAlert('An error occurred while saving. Please try again. Error: ' + error, 'error');
                $('#btnText').show();
                $('#btnLoading').hide();
                $('#submitBtn').prop('disabled', false);
            }
        });
    });
    
    // District change handler
    $('#district').on('change', function() {
        var districtID = $(this).val();
        console.log('District changed to:', districtID);
        
        if (districtID) {
            $.ajax({
                type: 'POST',
                url: 'ajaxData.php',
                data: {district_id: districtID},
                success: function(html) {
                    console.log('Tehsils loaded:', html);
                    $('#tehsil').html(html);
                    $('#constituency').html('<option value="">Select Tehsil First...</option>');
                    $('#union_councils').html('<option value="">Select Constituency First...</option>');
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error loading tehsils:', error);
                    $('#tehsil').html('<option value="">Error loading tehsils: ' + error + '</option>');
                }
            });
        } else {
            $('#tehsil').html('<option value="">Select District First...</option>');
            $('#constituency').html('<option value="">Select Tehsil First...</option>');
            $('#union_councils').html('<option value="">Select Constituency First...</option>');
        }
    });
    
    // Tehsil change handler
    $('#tehsil').on('change', function() {
        var tehsilID = $(this).val();
        console.log('Tehsil changed to:', tehsilID);
        
        if (tehsilID) {
            $.ajax({
                type: 'POST',
                url: 'ajaxData.php',
                data: {tehsil_id: tehsilID},
                success: function(html) {
                    console.log('Constituencies loaded:', html);
                    $('#constituency').html(html);
                    $('#union_councils').html('<option value="">Select Constituency First...</option>');
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error loading constituencies:', error);
                    $('#constituency').html('<option value="">Error loading constituencies: ' + error + '</option>');
                }
            });
        } else {
            $('#constituency').html('<option value="">Select Tehsil First...</option>');
            $('#union_councils').html('<option value="">Select Constituency First...</option>');
        }
    });
    
    // Constituency change handler
    $('#constituency').on('change', function() {
        var consID = $(this).val();
        console.log('Constituency changed to:', consID);
        
        if (consID) {
            $.ajax({
                type: 'POST',
                url: 'ajaxData.php',
                data: {cons_id: consID},
                success: function(html) {
                    console.log('Union councils loaded:', html);
                    $('#union_councils').html(html);
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error loading union councils:', error);
                    $('#union_councils').html('<option value="">Error loading union councils: ' + error + '</option>');
                }
            });
        } else {
            $('#union_councils').html('<option value="">Select Constituency First...</option>');
        }
    });
    
    // Real-time validation feedback
    $('input[pattern]').on('input', function() {
        const pattern = new RegExp($(this).attr('pattern'));
        const value = $(this).val();
        
        if (value === '') {
            $(this).css('border-color', '#e0e0e0');
        } else if (pattern.test(value)) {
            $(this).css('border-color', '#2ecc71');
        } else {
            $(this).css('border-color', '#e74c3c');
        }
    });
    
    // Required fields validation on blur
    $('input[required], select[required]').on('blur', function() {
        if (!$(this).val()) {
            $(this).css('border-color', '#e74c3c');
        } else {
            $(this).css('border-color', '#e0e0e0');
        }
    });
    
    // Populate tehsil, constituency, union council if editing existing data
    <?php if (isset($existing_data['district_id'])): ?>
        console.log('Pre-populating location data...');
        // Trigger district change to load tehsils
        $('#district').val('<?php echo $existing_data["district_id"]; ?>').trigger('change');
        
        // After a delay, set tehsil value
        setTimeout(function() {
            $('#tehsil').val('<?php echo $existing_data["tehsil_id"]; ?>').trigger('change');
            
            // After another delay, set constituency value
            setTimeout(function() {
                $('#constituency').val('<?php echo $existing_data["constituency_id"]; ?>').trigger('change');
                
                // After another delay, set union council value
                setTimeout(function() {
                    $('#union_councils').val('<?php echo $existing_data["union_council_id"]; ?>');
                    console.log('Location data populated successfully');
                }, 500);
            }, 500);
        }, 500);
    <?php endif; ?>
}

// Test function for debugging
function testYearPicker() {
    console.log('Testing year picker functionality...');
    console.log('Year picker toggles found:', $('.year-picker-toggle').length);
    console.log('Year input fields found:', $('.year-input-field').length);
    console.log('Year picker containers found:', $('.compact-year-picker').length);
    
    // Test if click event works
    if ($('.year-picker-toggle').length > 0) {
        console.log('Year picker functionality appears to be set up correctly');
    } else {
        console.error('No year picker toggle buttons found!');
    }
}

// Debug function to check all components
$(window).on('load', function() {
    console.log('Window loaded, checking all components...');
    
    // Check for common issues
    if ($('.year-input-wrapper').length === 0) {
        console.error('No year input wrappers found - check HTML structure');
    }
    
    if ($('.compact-year-picker').length === 0) {
        console.error('No year picker containers found - check HTML structure');
    }
    
    console.log('All components checked');
});
</script>
</body>
</html>