<!-- 
  **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 second file (school_step2.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 = '';

// Retrieve session variables
$school_name = $_SESSION['school_name'] ?? '';
$emis_code = $_SESSION['emis_code'] ?? '';
$cate_id = $_SESSION['cate_id'] ?? '';
$level_id = $_SESSION['level_id'] ?? '';

// =================== FETCH DATA FROM MULTIPLE SOURCES ===================
// 1. Registration data (if available)
$registration_data = [];
if (!empty($emis_code)) {
    $stmt = $conn->prepare("SELECT emis_code, school_name FROM registrations WHERE emis_code = ?");
    $stmt->bind_param("s", $emis_code);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $registration_data = $result->fetch_assoc();
    }
    $stmt->close();
}

// 2. Existing school_land data
$existing_data = [];
if (!empty($emis_code)) {
    $stmt = $conn->prepare("SELECT * FROM school_land WHERE emis_code = ?");
    $stmt->bind_param("s", $emis_code);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $existing_data = $result->fetch_assoc();
    }
    $stmt->close();
}
// =================== END FETCH DATA ===================

// Helper function to get field value with proper mapping
function getFormFieldValue($field_name, $default = '') {
    global $existing_data;
    
    // Handle special field mappings
    $field_map = [
        'land' => 'land_available',
        'landtype' => 'land_type',
        'ownershipstatus' => 'ownership_status',
        'landdocument' => 'land_document',
        'noland' => 'no_land_reason'
    ];
    
    $db_field = $field_map[$field_name] ?? $field_name;
    
    // Priority: POST > session form data > existing data
    if (isset($_POST[$field_name])) {
        return $_POST[$field_name];
    }
    
    // Check session form data (from failed submission)
    if (isset($_SESSION['form_data'][$field_name])) {
        $value = $_SESSION['form_data'][$field_name];
        return $value;
    }
    
    if (isset($existing_data[$db_field])) {
        // Special conversion for land availability
        if ($field_name === 'land') {
            // Convert from database 'Yes'/'No' to form values 'landyes'/'landno'
            if ($existing_data[$db_field] === 'Yes') {
                return 'landyes';
            } elseif ($existing_data[$db_field] === 'No') {
                return 'landno';
            }
        }
        // Return other fields as-is
        return $existing_data[$db_field];
    }
    
    return $default;
}

// Determine initial states for conditional sections
$land_state = getFormFieldValue('land', 'landyes');
$land_under_school = getFormFieldValue('land_under_school', 'Yes');
$legal_issues_state = getFormFieldValue('legal_issues', 'No');

// Display messages from session
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}
if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>School Land Registration - Step 2 of 10</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;
        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;
    }
    
    .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: #27ae60;
        transform: translateY(-50%);
        z-index: 2;
        transition: width 0.3s ease;
        width: 20%;
    }
    
    .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: #27ae60;
        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: #27ae60;
        font-weight: 600;
    }
    
    .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, #27ae60, #219653);
        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(39, 174, 96, 0.3);
        background: linear-gradient(135deg, #219653, #1e8449);
    }
    
    .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 #27ae60;
        padding: 30px;
        box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        margin-bottom: 0px;
        position: relative;
        min-height: auto;
    }
    
    .form-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
        margin-bottom: 20px;
    }
    
    .form-group {
        display: flex;
        flex-direction: column;
    }
    .form-group.full-width {
        grid-column: 1 / -1;
    }
    label {
        margin-bottom: 8px;
        font-weight: 600;
        color: #2c3e50;
        font-size: 14px;
    }
    input[type="text"],
    input[type="email"],
    input[type="number"],
    select,
    textarea {
        padding: 12px 15px;
        border: 2px solid #e0e0e0;
        border-radius: 6px;
        font-size: 15px;
        transition: all 0.3s ease;
        background-color: white;
        width: 100%;
    }
    textarea {
        min-height: 100px;
        resize: vertical;
    }
    input[type="text"]:focus,
    input[type="email"]:focus,
    input[type="number"]:focus,
    select:focus,
    textarea:focus {
        outline: none;
        border-color: #27ae60;
        box-shadow: 0 0 0 3px rgba(39, 174, 96, 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 #27ae60;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .section-title i {
        color: #27ae60;
    }
    
    .submit-btn {
        display: block;
        width: 200px;
        margin: 30px auto 0;
        padding: 15px 30px;
        background: linear-gradient(135deg, #27ae60, #219653);
        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(39, 174, 96, 0.3);
        background: linear-gradient(135deg, #219653, #1e8449);
    }
    .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;
    }
    .radio-group {
        display: flex;
        gap: 30px;
        margin-bottom: 20px;
    }
    .radio-option {
        display: flex;
        align-items: center;
        gap: 8px;
        cursor: pointer;
    }
    .radio-option input[type="radio"] {
        width: 18px;
        height: 18px;
        cursor: pointer;
    }
    .radio-label {
        font-weight: 600;
        color: #2c3e50;
        cursor: pointer;
    }
    .conditional-section {
        background-color: #f8f9fa;
        padding: 25px;
        border-radius: 8px;
        border-left: 4px solid #27ae60;
        margin-top: 20px;
        display: none;
        animation: fadeIn 0.3s ease;
    }
    .conditional-section.active {
        display: block;
    }
    .checkbox-group {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 15px;
    }
    .checkbox-group input[type="checkbox"] {
        width: 18px;
        height: 18px;
        cursor: pointer;
    }
    .sub-section {
        background-color: #f1f8ff;
        padding: 20px;
        border-radius: 6px;
        margin-top: 15px;
        border-left: 3px solid #27ae60;
        display: none;
        animation: slideDown 0.3s ease;
    }
    .sub-section.active {
        display: block;
    }
    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    @keyframes slideDown {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .land-availability-section {
        text-align: center;
        padding: 20px;
        background-color: #f8f9fa;
        border-radius: 8px;
        margin-bottom: 30px;
    }
    .validation-success {
        border-color: #2ecc71 !important;
    }
    .validation-error {
        border-color: #e74c3c !important;
    }
    .school-info {
        background: #f8f9fa;
        padding: 15px;
        border-radius: 6px;
        margin-bottom: 20px;
        border-left: 4px solid #27ae60;
    }
    .school-info h3 {
        color: #2c3e50;
        margin-bottom: 10px;
        font-size: 16px;
    }
    .school-info p {
        color: #666;
        font-size: 14px;
    }
    
    .conditional-sections-wrapper {
        display: none;
    }
    .conditional-sections-wrapper.visible {
        display: block;
        animation: fadeIn 0.3s ease;
    }
    
    @media (max-width: 768px) {
        .form-grid {
            grid-template-columns: 1fr;
            gap: 15px;
        }
        .form-container {
            padding: 20px;
        }
        .header h1 {
            font-size: 24px;
        }
        .radio-group {
            flex-direction: column;
            gap: 15px;
        }
        input[type="text"],
        input[type="email"],
        input[type="number"],
        select,
        textarea {
            padding: 10px 12px;
            font-size: 14px;
        }
        .submit-btn {
            width: 100%;
            max-width: 300px;
        }
        
        .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;
        }
    }
</style>
</head>
<body>
<!-- Floating Logout Button -->
<?php include 'floating_logout_school.php'; ?>
<div class="container">
    <div class="header">
        <h1><i class="fas fa-landmark"></i> School Land Registration - Step 2 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" style="width: 20%;"></div>
        <div class="step completed" id="step1"><span>1</span><span class="step-label">School Profile</span></div>
        <div class="step active" 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($success_message)): ?>
    <div class="alert alert-success">
        <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
    </div>
    <?php endif; ?>
    <?php if(!empty($error_message)): ?>
    <div class="alert alert-error">
        <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error_message); ?>
    </div>
    <?php endif; ?>

    <div class="form-container">
        <div class="school-info">
            <h3><i class="fas fa-info-circle"></i> School Land Information</h3>
            <p>Fill in all land details for <strong><?php echo htmlspecialchars($school_name); ?></strong> (EMIS: <strong><?php echo htmlspecialchars($emis_code); ?></strong>). All fields marked with <span style="color: #e74c3c; font-weight: bold;">*</span> are required.</p>
        </div>

        <form method="POST" action="school_step2_save.php" id="landForm">
            <!-- Section 1: Land Availability -->
            <div class="form-section">
                <h3 class="section-title"><i class="fas fa-check-circle"></i> Land Availability</h3>
                <div class="land-availability-section">
                    <div class="radio-group">
                        <div class="radio-option">
                            <input type="radio" id="land_yes" name="land" value="landyes" <?php echo ($land_state === 'landyes') ? 'checked' : ''; ?> required>
                            <label for="land_yes" class="radio-label">Land Available</label>
                        </div>
                        <div class="radio-option">
                            <input type="radio" id="land_no" name="land" value="landno" <?php echo ($land_state === 'landno') ? 'checked' : ''; ?>>
                            <label for="land_no" class="radio-label">No Land</label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Conditional Section: Land Available Form -->
            <div id="formYes" class="conditional-section" style="<?php echo ($land_state === 'landyes') ? 'display: block;' : 'display: none;'; ?>">
                <h3 class="section-title"><i class="fas fa-map-marked-alt"></i> Available Total Land Information</h3>
                <div class="form-grid">
                    <div class="form-group">
                        <label for="kanal" class="required">Kanal</label>
                        <input id="kanal" name="kanal" type="number" min="0" step="1" placeholder="Enter Kanal" value="<?php echo htmlspecialchars(getFormFieldValue('kanal')); ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="marla">Marla</label>
                        <input id="marla" name="marla" type="number" min="0" max="19" step="1" placeholder="Enter Marla (0-19)" value="<?php echo htmlspecialchars(getFormFieldValue('marla')); ?>">
                    </div>
                    <div class="form-group">
                        <label for="landtype" class="required">Land Type</label>
                        <select id="landtype" name="landtype" required>
                            <option value="">Select Land Type...</option>
                            <option value="Hilly" <?php echo getFormFieldValue('landtype') == 'Hilly' ? 'selected' : ''; ?>>Hilly</option>
                            <option value="Plan" <?php echo getFormFieldValue('landtype') == 'Plan' ? 'selected' : ''; ?>>Plan</option>
                            <option value="Mixed" <?php echo getFormFieldValue('landtype') == 'Mixed' ? 'selected' : ''; ?>>Mixed</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="ownershipstatus" class="required">Ownership Status</label>
                        <select id="ownershipstatus" name="ownershipstatus" required>
                            <option value="">Select Ownership Status...</option>
                            <?php
                            $query = "SELECT * FROM schoolland_ownership WHERE status = 1 ORDER BY ownership_id ASC";
                            $result = $conn->query($query);
                            if ($result && $result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    $selected = (getFormFieldValue('ownershipstatus') == $row['ownership_id']) ? 'selected' : '';
                                    echo '<option value="' . htmlspecialchars($row['ownership_id']) . '" ' . $selected . '>' . htmlspecialchars($row['name_en']) . ' (' . htmlspecialchars($row['name_ur']) . ')</option>';
                                }
                            }
                            ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="landdocument" class="required">Land Document Available</label>
                        <select id="landdocument" name="landdocument" required>
                            <option value="">Select Document Availability...</option>
                            <option value="Yes" <?php echo getFormFieldValue('landdocument') == 'Yes' ? 'selected' : ''; ?>>Yes</option>
                            <option value="No" <?php echo getFormFieldValue('landdocument') == 'No' ? 'selected' : ''; ?>>No</option>
                        </select>
                    </div>
                </div>

                <!-- Land Under School Control -->
                <div class="form-group full-width">
                    <label class="required">Is all the Land under School Control?</label>
                    <div class="radio-group" style="margin-bottom: 15px;">
                        <div class="radio-option">
                            <input type="radio" id="land_control_yes" name="land_under_school" value="Yes" <?php echo ($land_under_school === 'Yes') ? 'checked' : ''; ?> required>
                            <label for="land_control_yes" class="radio-label">Yes</label>
                        </div>
                        <div class="radio-option">
                            <input type="radio" id="land_control_no" name="land_under_school" value="No" <?php echo ($land_under_school === 'No') ? 'checked' : ''; ?>>
                            <label for="land_control_no" class="radio-label">No</label>
                        </div>
                    </div>

                    <!-- Land Not Under Control Details -->
                    <div id="landNotUnderControlDetails" class="sub-section" style="<?php echo ($land_under_school === 'No') ? 'display: block;' : 'display: none;'; ?>">
                        <div class="form-grid">
                            <div class="form-group">
                                <label for="not_under_kanal">Kanal that Does Not Under School Control</label>
                                <input id="not_under_kanal" name="not_under_kanal" type="number" min="0" step="1" placeholder="Enter Kanal" value="<?php echo htmlspecialchars(getFormFieldValue('not_under_kanal')); ?>">
                            </div>
                            <div class="form-group">
                                <label for="not_under_marla">Marla that Does Not Under School Control</label>
                                <input id="not_under_marla" name="not_under_marla" type="number" min="0" max="19" step="1" placeholder="Enter Marla (0-19)" value="<?php echo htmlspecialchars(getFormFieldValue('not_under_marla')); ?>">
                            </div>
                            <div class="form-group full-width">
                                <label for="reason_not_under_control">Reason for Not Being Under Control</label>
                                <textarea id="reason_not_under_control" name="reason_not_under_control" placeholder="Explain why this land is not under school control..." rows="3"><?php echo htmlspecialchars(getFormFieldValue('reason_not_under_control')); ?></textarea>
                            </div>
                        </div>
                        <div class="form-group full-width">
                            <label for="encroachment_details">Encroachment Details (if any)</label>
                            <textarea id="encroachment_details" name="encroachment_details" placeholder="Provide details of any encroachment..." rows="3"><?php echo htmlspecialchars(getFormFieldValue('encroachment_details')); ?></textarea>
                        </div>
                    </div>
                </div>

                <!-- Conditional Sections Wrapper - Shows when "No" is selected -->
                <div id="conditionalSectionsWrapper" class="conditional-sections-wrapper" style="<?php echo ($land_under_school === 'No') ? 'display: block;' : 'display: none;'; ?>">
                    <br>
                    <!-- Legal Issues -->
                    <div class="form-section">
                        <h4 style="margin-bottom: 15px; color: #2c3e50;">Legal Issues with the Land</h4>
                        <div class="radio-group" style="margin-bottom: 15px;">
                            <div class="radio-option">
                                <input type="radio" id="legal_issues_yes" name="legal_issues" value="Yes" <?php echo ($legal_issues_state === 'Yes') ? 'checked' : ''; ?>>
                                <label for="legal_issues_yes" class="radio-label">Yes, there are legal issues</label>
                            </div>
                            <div class="radio-option">
                                <input type="radio" id="legal_issues_no" name="legal_issues" value="No" <?php echo ($legal_issues_state === 'No') ? 'checked' : ''; ?>>
                                <label for="legal_issues_no" class="radio-label">No legal issues</label>
                            </div>
                        </div>
                        <div id="legalIssuesDetails" class="sub-section" style="<?php echo ($legal_issues_state === 'Yes') ? 'display: block;' : 'display: none;'; ?>">
                            <h4 style="margin-bottom: 15px; color: #2c3e50;">Legal Issues Details</h4>
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="legal_issue_type">Type of Legal Issue</label>
                                    <select id="legal_issue_type" name="legal_issue_type">
                                        <option value="">Select Issue Type...</option>
                                        <option value="Dispute" <?php echo getFormFieldValue('legal_issue_type') == 'Dispute' ? 'selected' : ''; ?>>Dispute</option>
                                        <option value="Court Case" <?php echo getFormFieldValue('legal_issue_type') == 'Court Case' ? 'selected' : ''; ?>>Court Case</option>
                                        <option value="Other" <?php echo getFormFieldValue('legal_issue_type') == 'Other' ? 'selected' : ''; ?>>Other</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="court_case_number">Court Case Number</label>
                                    <input id="court_case_number" name="court_case_number" type="text" placeholder="Enter court case number" value="<?php echo htmlspecialchars(getFormFieldValue('court_case_number')); ?>">
                                </div>
                                <div class="form-group">
                                    <label for="court_name">Court Name</label>
                                    <input id="court_name" name="court_name" type="text" placeholder="Enter court name" value="<?php echo htmlspecialchars(getFormFieldValue('court_name')); ?>">
                                </div>
                                <div class="form-group">
                                    <label for="legal_status">Current Legal Status</label>
                                    <select id="legal_status" name="legal_status">
                                        <option value="">Select Status...</option>
                                        <option value="Pending" <?php echo getFormFieldValue('legal_status') == 'Pending' ? 'selected' : ''; ?>>Pending</option>
                                        <option value="Resolved" <?php echo getFormFieldValue('legal_status') == 'Resolved' ? 'selected' : ''; ?>>Resolved</option>
                                        <option value="Ongoing" <?php echo getFormFieldValue('legal_status') == 'Ongoing' ? 'selected' : ''; ?>>Ongoing</option>
                                    </select>
                                </div>
                                <div class="form-group full-width">
                                    <label for="legal_issue_details">Legal Issue Details</label>
                                    <textarea id="legal_issue_details" name="legal_issue_details" placeholder="Provide detailed information about legal issues..." rows="4"><?php echo htmlspecialchars(getFormFieldValue('legal_issue_details')); ?></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Conditional Section: No Land Form -->
            <div id="formNo" class="conditional-section" style="<?php echo ($land_state === 'landno') ? 'display: block;' : 'display: none;'; ?>">
                <h3 class="section-title"><i class="fas fa-exclamation-triangle"></i> No Land - Reason</h3>
                <div class="form-group full-width">
                    <label for="noland" class="required">Explain Reason for No Land</label>
                    <textarea id="noland" name="noland" required placeholder="Provide detailed reason why there is no land for the school..." rows="4"><?php echo htmlspecialchars(getFormFieldValue('noland')); ?></textarea>
                    <p class="helper-text">Please provide a comprehensive explanation for the absence of school land</p>
                </div>
            </div>

            <!-- Navigation Buttons -->
            <div class="navigation-buttons">
                <a href="school_step1.php" class="nav-btn back">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <button type="submit" class="nav-btn" id="submitBtn">
                    <span id="btnText">Save & Continue</span>
                    <span id="btnLoading" style="display: none;">
                        <span class="loading-spinner"></span> Processing...
                    </span>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize conditional sections based on current state
    function updateConditionalSections() {
        const landYes = $('#land_yes').is(':checked');
        const landNo = $('#land_no').is(':checked');
        const controlNo = $('#land_control_no').is(':checked');
        const legalYes = $('#legal_issues_yes').is(':checked');
        
        // Toggle main land sections
        if (landYes) {
            $('#formYes').show();
            $('#formNo').hide();
            // Make land fields required
            $('#kanal, #landtype, #ownershipstatus, #landdocument').prop('required', true);
            $('#noland').prop('required', false);
        } else if (landNo) {
            $('#formNo').show();
            $('#formYes').hide();
            $('#noland').prop('required', true);
            $('#kanal, #landtype, #ownershipstatus, #landdocument').prop('required', false);
        }
        
        // Toggle land control sections
        if (controlNo) {
            $('#landNotUnderControlDetails').show();
            $('#conditionalSectionsWrapper').show();
        } else {
            $('#landNotUnderControlDetails').hide();
            $('#conditionalSectionsWrapper').hide();
            // Reset legal issues when control is "Yes"
            $('#legal_issues_no').prop('checked', true).trigger('change');
        }
        
        // Toggle legal issues details
        if (legalYes) {
            $('#legalIssuesDetails').show();
        } else {
            $('#legalIssuesDetails').hide();
        }
    }
    
    // Initialize on page load
    updateConditionalSections();
    
    // Event listeners
    $('input[name="land"]').on('change', updateConditionalSections);
    $('input[name="land_under_school"]').on('change', updateConditionalSections);
    $('input[name="legal_issues"]').on('change', updateConditionalSections);
    
    // Marla validation (0-19)
    $('#marla, #not_under_marla').on('blur', function() {
        const value = parseInt($(this).val());
        if (!isNaN(value) && (value < 0 || value > 19)) {
            alert('Marla must be between 0 and 19');
            $(this).val('');
        }
    });
    
    // Kanal validation for not under control
    $('#not_under_kanal, #kanal').on('blur', function() {
        const notUnderKanal = parseInt($('#not_under_kanal').val()) || 0;
        const totalKanal = parseInt($('#kanal').val()) || 0;
        if (notUnderKanal > totalKanal && totalKanal > 0) {
            alert('Kanal not under control cannot be greater than total kanal');
            $('#not_under_kanal').val('');
        }
    });
    
			// Real-time validation for "No Land" reason field
		$('#noland').on('blur', function() {
			if ($('#land_no').is(':checked')) {
				const reason = $(this).val().trim();
				$(this).toggleClass('validation-error', reason.length > 0 && reason.length < 10);
			} else {
				$(this).removeClass('validation-error');
			}
		}).on('input', function() {
			if ($(this).hasClass('validation-error')) {
				const reason = $(this).val().trim();
				if (reason.length >= 10 || reason.length === 0) {
					$(this).removeClass('validation-error');
				}
			}
		});

    // Form validation before submission
    $('#landForm').on('submit', function(e) {
        // Remove previous validation errors
        $('.validation-error').removeClass('validation-error');
        
        let isValid = true;
        const errors = [];
        
        if ($('#land_yes').is(':checked')) {
            // Validate required land fields
            if (!$('#kanal').val().trim()) {
                errors.push('Kanal is required');
                $('#kanal').addClass('validation-error');
                isValid = false;
            }
            
            if (!$('#landtype').val()) {
                errors.push('Land Type is required');
                $('#landtype').addClass('validation-error');
                isValid = false;
            }
            
            if (!$('#ownershipstatus').val()) {
                errors.push('Ownership Status is required');
                $('#ownershipstatus').addClass('validation-error');
                isValid = false;
            }
            
            if (!$('#landdocument').val()) {
                errors.push('Land Document availability is required');
                $('#landdocument').addClass('validation-error');
                isValid = false;
            }
            
            if (!$('input[name="land_under_school"]:checked').length) {
                errors.push('Please select if all land is under school control');
                isValid = false;
            }
            
            // Additional validation when land not fully under control
            if ($('#land_control_no').is(':checked')) {
                if (!$('input[name="legal_issues"]:checked').length) {
                    errors.push('Please specify if there are legal issues with the land');
                    isValid = false;
                }
                
                // Validate not-under-control values
                const totalKanal = parseInt($('#kanal').val()) || 0;
                const totalMarla = parseInt($('#marla').val()) || 0;
                const notUnderKanal = parseInt($('#not_under_kanal').val()) || 0;
                const notUnderMarla = parseInt($('#not_under_marla').val()) || 0;
                
                if (notUnderKanal > totalKanal) {
                    errors.push('Kanal not under control cannot be greater than total kanal');
                    isValid = false;
                }
                
                if (notUnderMarla > totalMarla) {
                    errors.push('Marla not under control cannot be greater than total marla');
                    isValid = false;
                }
            }
		} else if ($('#land_no').is(':checked')) {
			const noLandReason = $('#noland').val().trim();
			if (!noLandReason) {
				errors.push('Reason for no land is required');
				$('#noland').addClass('validation-error');
				isValid = false;
			} else if (noLandReason.length < 50) {
				errors.push('Reason for no land must be at least 50 characters long');
				$('#noland').addClass('validation-error');
				isValid = false;
			}
		}		
		else {
            errors.push('Please select land availability');
            isValid = false;
        }
        
        if (!isValid) {
            e.preventDefault();
            alert('Please fix the following errors:\n' + errors.join('\n'));
            return false;
        }
        
        // Show loading state
        $('#btnText').hide();
        $('#btnLoading').show();
        $('#submitBtn').prop('disabled', true);
    });
});
</script>
</body>
</html>

<?php
// Clear session form data at the end
if (isset($_SESSION['form_data'])) {
    unset($_SESSION['form_data']);
}
?>