<!-- 
  **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 fourth file (school_step4.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'] ?? '';

// 🔒 SECURITY: Generate CSRF token if not exists
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

// =================== FETCH EXISTING DATA ===================
$existing_facilities = null;
$existing_labs = [];

// 1. Fetch facilities data
if (!empty($emis_code)) {
    $stmt = $conn->prepare("SELECT * FROM school_facilities WHERE emis_code = ?");
    $stmt->bind_param("s", $emis_code);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $existing_facilities = $result->fetch_assoc();
    }
    $stmt->close();
}

// 2. Fetch existing labs
$existing_labs = [];
$facility_id = $existing_facilities['id'] ?? null;
if (!empty($facility_id)) {
    $stmt = $conn->prepare("SELECT * FROM school_labs WHERE facility_id = ? ORDER BY id");
    $stmt->bind_param("i", $facility_id);
    $stmt->execute();
    $lab_result = $stmt->get_result();
    while ($row = $lab_result->fetch_assoc()) {
        $existing_labs[$row['lab_type']] = $row;
    }
    $stmt->close();
}

// 3. Define valid lab types (for validation)
$valid_lab_types = [
    'computer' => 'Computer Lab',
    'physics' => 'Physics Lab',
    'combined' => 'Combined Lab',
    'zoology' => 'Zoology Lab',
    'botany' => 'Botany Lab',
    'home_economics' => 'Home Economics Lab',
    'technical' => 'Technical Workshop',
    'smart' => 'Smart Classroom',
    'ece' => 'ECE Classroom',
    'sports' => 'Sports Stock',
    'language' => 'Language Lab',
    'math' => 'Mathematics Lab',
    'art_craft' => 'Art & Craft Room',
    'music' => 'Music Room',
    'library' => 'Library / Reading Room',
    'chemistry' => 'Chemistry Lab',
    'biology' => 'Biology Lab',
    'env_science' => 'Environmental Science Lab'
];
// =================== END FETCH DATA ===================

// =================== HELPER FUNCTIONS ===================
/**
 * Get form field value with priority: POST > Session > Database > Default
 */
function getFormFieldValue($field_name, $default = '') {
    global $existing_facilities, $_POST, $_SESSION;
    
    // Field name mapping (form field => database column)
    $field_map = [
        'electricity' => 'electricity',
        'water' => 'water',
        'internet' => 'internet',
        'road' => 'road',
        'assembly' => 'assembly_ground',
        'ground' => 'play_ground',
        'medical' => 'medical_facility',
        'gas' => 'gas_supply',
        'ptransport' => 'public_transport',
        'schair' => 'staff_chairs',
        'stable' => 'staff_tables',
        'desk' => 'student_desks',
        'cupboard' => 'cupboards',
        'board' => 'writing_boards',
        'dice' => 'podiums'
    ];
    
    $db_field = $field_map[$field_name] ?? $field_name;
    
    // Priority 1: POST data (form submission)
    if (isset($_POST[$field_name]) && $_POST[$field_name] !== '') {
        return $_POST[$field_name];
    }
    
    // Priority 2: Session data (form repopulation after error)
    if (isset($_SESSION['form_data'][$field_name]) && $_SESSION['form_data'][$field_name] !== '') {
        return $_SESSION['form_data'][$field_name];
    }
    
    // Priority 3: Existing database data
    if (isset($existing_facilities[$db_field]) && $existing_facilities[$db_field] !== '') {
        return $existing_facilities[$db_field];
    }
    
    return $default;
}

/**
 * Get lab field value with priority: POST > Session > Database > Default
 */
function getLabFieldValue($lab_type, $field_name, $default = '') {
    global $existing_labs, $_POST, $_SESSION;
    
    // Priority 1: POST data
    if ($field_name === 'equipment_available') {
        if (isset($_POST['equip_' . $lab_type]) && $_POST['equip_' . $lab_type] !== '') {
            return $_POST['equip_' . $lab_type];
        }
    } elseif ($field_name === 'requirements') {
        if (isset($_POST['req_' . $lab_type]) && $_POST['req_' . $lab_type] !== '') {
            return $_POST['req_' . $lab_type];
        }
    }
    
    // Priority 2: Session data
    $session_key = ($field_name === 'equipment_available') ? 'equip_' . $lab_type : 'req_' . $lab_type;
    if (isset($_SESSION['form_data'][$session_key]) && $_SESSION['form_data'][$session_key] !== '') {
        return $_SESSION['form_data'][$session_key];
    }
    
    // Priority 3: Existing database data
    if (isset($existing_labs[$lab_type])) {
        if ($field_name === 'equipment_available') {
            return $existing_labs[$lab_type]['equipment_available'] ?? $default;
        } elseif ($field_name === 'requirements') {
            return $existing_labs[$lab_type]['requirements'] ?? $default;
        }
    }
    
    return $default;
}
// =================== END HELPER FUNCTIONS ===================

// Display messages
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']);
}
if (isset($_SESSION['form_data'])) {
    unset($_SESSION['form_data']);
}

// Prepare lab data for pre-population
$lab_data = [];
foreach ($valid_lab_types as $lab_type => $lab_name) {
    $equip_value = getLabFieldValue($lab_type, 'equipment_available');
    $req_value = getLabFieldValue($lab_type, 'requirements');
    
    // Only include labs that have data
    if ($equip_value !== '' || $req_value !== '') {
        $lab_data[$lab_type] = [
            'equipment_available' => $equip_value,
            'requirements' => $req_value
        ];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>School Facilities Registration - Step 4 of 10</title>
<!-- 🔧 FIXED: Removed trailing spaces from CDN URLs -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.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: 30px; 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: #e67e22; transform: translateY(-50%); z-index: 2; transition: width 0.3s ease; width: 40%; }
.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: #e67e22; 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: #e67e22; font-weight: 600; }
.form-container { background: white; border-radius: 10px; border-left: 4px solid #e67e22; padding: 30px; box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08); margin-bottom: 30px; }
.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: #e67e22; box-shadow: 0 0 0 3px rgba(230, 126, 34, 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 #e67e22; display: flex; align-items: center; gap: 10px; }
.section-title i { color: #e67e22; }
.submit-btn { display: block; width: 200px; margin: 30px auto 0; padding: 15px 30px; background: linear-gradient(135deg, #e67e22, #d35400); 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(230, 126, 34, 0.3); background: linear-gradient(135deg, #d35400, #ba4a00); }
.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; justify-content: center; }
.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 #e67e22; margin-top: 20px; display: none; animation: fadeIn 0.3s ease; }
.conditional-section.active { display: block; }
.rooms-table-container { overflow-x: auto; margin-top: 20px; }
.rooms-table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
.rooms-table th { background-color: #f8f9fa; padding: 12px 15px; text-align: left; font-weight: 600; color: #2c3e50; border-bottom: 2px solid #dee2e6; }
.rooms-table td { padding: 12px 15px; border-bottom: 1px solid #dee2e6; }
.rooms-table tr:hover { background-color: #f8f9fa; }
.action-buttons { display: flex; gap: 10px; justify-content: center; }
.add-btn { background-color: #3498db; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; display: flex; align-items: center; gap: 8px; font-weight: 600; transition: all 0.3s ease; }
.add-btn:hover:not(:disabled) { background-color: #2980b9; transform: translateY(-2px); }
.add-btn:disabled { opacity: 0.6; cursor: not-allowed; }
.remove-btn { background-color: #e74c3c; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; transition: all 0.3s ease; display: flex; align-items: center; gap: 5px; }
.remove-btn:hover { background-color: #c0392b; transform: scale(1.05); }
.remove-btn i { margin-right: 3px; }
.facilities-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; margin-bottom: 20px; }
.facility-item { background: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 3px solid #e67e22; }
.lab-block { background-color: #fff; border: 2px solid #e0e0e0; border-radius: 8px; padding: 20px; margin-bottom: 15px; position: relative; transition: all 0.3s ease; }
.lab-block:hover { border-color: #e67e22; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
.lab-block h4 { margin: 0 0 15px 0; color: #2c3e50; font-size: 16px; display: flex; justify-content: space-between; align-items: center; }
.add-lab-container { display: flex; gap: 10px; align-items: center; margin-top: 20px; 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 #e67e22; }
.school-info h3 { color: #2c3e50; margin-bottom: 10px; font-size: 16px; }
.school-info p { color: #666; font-size: 14px; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes slideDown { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
.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 30px; background: linear-gradient(135deg, #e67e22, #d35400); 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(230, 126, 34, 0.3); background: linear-gradient(135deg, #d35400, #ba4a00); }
.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); }

/* New styles for disabled dropdown options */
#labDropdown option:disabled {
    color: #999;
    background-color: #f5f5f5;
    font-style: italic;
}

/* Responsive styles */
@media (max-width: 768px) { 
    .form-grid, .facilities-grid { grid-template-columns: 1fr; gap: 15px; } 
    .progress-container { overflow-x: auto; padding-bottom: 20px; } 
    .radio-group { flex-direction: column; gap: 10px; }
    .add-lab-container { flex-direction: column; }
    .add-lab-container select, .add-btn { width: 100%; }
}
@media (max-width: 480px) {
    .container { padding: 10px; }
    .form-container { padding: 15px; }
    .header { padding: 15px; }
    .lab-block h4 { flex-direction: column; align-items: flex-start; gap: 10px; }
    .remove-btn { align-self: flex-end; }
    .nav-btn { padding: 10px 20px; font-size: 14px; }
}
</style>
</head>
<body>
<?php include 'floating_logout_school.php'; ?>
<div class="container">
<div class="header">
<h1><i class="fas fa-tools"></i> School Facilities Registration - Step 4 of 10</h1>
<p>Complete all 10 steps to register a new school in Districts Schools Management System</p>
</div>
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
<div class="step completed" id="step1"><span>1</span><span class="step-label">School Profile</span></div>
<div class="step completed" id="step2"><span>2</span><span class="step-label">School Land</span></div>
<div class="step completed" id="step3"><span>3</span><span class="step-label">School Building</span></div>
<div class="step active" 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> Facilities Information</h3>
<p>Fill in all facilities 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>
<!-- 🔒 SECURITY: Added CSRF token -->
<form method="POST" action="school_step4_save.php" id="facilitiesForm">
<input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
<!-- Section 1: Basic Facilities -->
<div class="form-section">
<h3 class="section-title"><i class="fas fa-bolt"></i> Basic Facilities</h3>
<div class="facilities-grid">
<div class="facility-item">
<label class="required">Electricity Available</label>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="electricity_yes" name="electricity" value="YES" <?php echo getFormFieldValue('electricity') == 'YES' ? 'checked' : ''; ?> required>
<label for="electricity_yes" class="radio-label">Yes</label>
</div>
<div class="radio-option">
<input type="radio" id="electricity_no" name="electricity" value="NO" <?php echo getFormFieldValue('electricity') == 'NO' ? 'checked' : ''; ?>>
<label for="electricity_no" class="radio-label">No</label>
</div>
</div>
</div>
<div class="facility-item">
<label class="required">Drinking Water Available</label>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="water_yes" name="water" value="YES" <?php echo getFormFieldValue('water') == 'YES' ? 'checked' : ''; ?> required>
<label for="water_yes" class="radio-label">Yes</label>
</div>
<div class="radio-option">
<input type="radio" id="water_no" name="water" value="NO" <?php echo getFormFieldValue('water') == 'NO' ? 'checked' : ''; ?>>
<label for="water_no" class="radio-label">No</label>
</div>
</div>
</div>
<div class="facility-item">
<label class="required">Internet Available</label>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="internet_yes" name="internet" value="YES" <?php echo getFormFieldValue('internet') == 'YES' ? 'checked' : ''; ?> required>
<label for="internet_yes" class="radio-label">Yes</label>
</div>
<div class="radio-option">
<input type="radio" id="internet_no" name="internet" value="NO" <?php echo getFormFieldValue('internet') == 'NO' ? 'checked' : ''; ?>>
<label for="internet_no" class="radio-label">No</label>
</div>
</div>
</div>
<div class="facility-item">
<label class="required">Road Access</label>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="road_yes" name="road" value="YES" <?php echo getFormFieldValue('road') == 'YES' ? 'checked' : ''; ?> required>
<label for="road_yes" class="radio-label">Yes</label>
</div>
<div class="radio-option">
<input type="radio" id="road_no" name="road" value="NO" <?php echo getFormFieldValue('road') == 'NO' ? 'checked' : ''; ?>>
<label for="road_no" class="radio-label">No</label>
</div>
</div>
</div>
<div class="facility-item">
<label class="required">Assembly Ground</label>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="assembly_yes" name="assembly" value="YES" <?php echo getFormFieldValue('assembly') == 'YES' ? 'checked' : ''; ?> required>
<label for="assembly_yes" class="radio-label">Yes</label>
</div>
<div class="radio-option">
<input type="radio" id="assembly_no" name="assembly" value="NO" <?php echo getFormFieldValue('assembly') == 'NO' ? 'checked' : ''; ?>>
<label for="assembly_no" class="radio-label">No</label>
</div>
</div>
</div>
<div class="facility-item">
<label class="required">Play Ground</label>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="ground_yes" name="ground" value="YES" <?php echo getFormFieldValue('ground') == 'YES' ? 'checked' : ''; ?> required>
<label for="ground_yes" class="radio-label">Yes</label>
</div>
<div class="radio-option">
<input type="radio" id="ground_no" name="ground" value="NO" <?php echo getFormFieldValue('ground') == 'NO' ? 'checked' : ''; ?>>
<label for="ground_no" class="radio-label">No</label>
</div>
</div>
</div>
<div class="facility-item">
<label class="required">Medical Facility</label>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="medical_yes" name="medical" value="YES" <?php echo getFormFieldValue('medical') == 'YES' ? 'checked' : ''; ?> required>
<label for="medical_yes" class="radio-label">Yes</label>
</div>
<div class="radio-option">
<input type="radio" id="medical_no" name="medical" value="NO" <?php echo getFormFieldValue('medical') == 'NO' ? 'checked' : ''; ?>>
<label for="medical_no" class="radio-label">No</label>
</div>
</div>
</div>
<div class="facility-item">
<label class="required">Gas Supply</label>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="gas_yes" name="gas" value="YES" <?php echo getFormFieldValue('gas') == 'YES' ? 'checked' : ''; ?> required>
<label for="gas_yes" class="radio-label">Yes</label>
</div>
<div class="radio-option">
<input type="radio" id="gas_no" name="gas" value="NO" <?php echo getFormFieldValue('gas') == 'NO' ? 'checked' : ''; ?>>
<label for="gas_no" class="radio-label">No</label>
</div>
</div>
</div>
<div class="facility-item">
<label class="required">Public Transport Access</label>
<div class="radio-group">
<div class="radio-option">
<input type="radio" id="ptransport_yes" name="ptransport" value="YES" <?php echo getFormFieldValue('ptransport') == 'YES' ? 'checked' : ''; ?> required>
<label for="ptransport_yes" class="radio-label">Yes</label>
</div>
<div class="radio-option">
<input type="radio" id="ptransport_no" name="ptransport" value="NO" <?php echo getFormFieldValue('ptransport') == 'NO' ? 'checked' : ''; ?>>
<label for="ptransport_no" class="radio-label">No</label>
</div>
</div>
</div>
</div>
</div>
<!-- Section 2: Furniture Facilities -->
<div class="form-section">
<h3 class="section-title"><i class="fas fa-chair"></i> Furniture Facilities</h3>
<div class="form-grid">
<div class="form-group">
<label for="schair" class="required">Chairs for Staff</label>
<input id="schair" name="schair" type="number" min="0" max="1000" placeholder="Enter number of chairs" value="<?php echo htmlspecialchars(getFormFieldValue('schair')); ?>" required>
<p class="helper-text">Number of chairs available for staff (0-1000)</p>
</div>
<div class="form-group">
<label for="stable" class="required">Tables for Staff</label>
<input id="stable" name="stable" type="number" min="0" max="1000" placeholder="Enter number of tables" value="<?php echo htmlspecialchars(getFormFieldValue('stable')); ?>" required>
<p class="helper-text">Number of tables available for staff (0-1000)</p>
</div>
<div class="form-group">
<label for="desk" class="required">Chairs & Desks for Students</label>
<input id="desk" name="desk" type="number" min="0" max="10000" placeholder="Enter number of sets" value="<?php echo htmlspecialchars(getFormFieldValue('desk')); ?>" required>
<p class="helper-text">Number of chair-desk sets for students (0-10,000)</p>
</div>
<div class="form-group">
<label for="cupboard" class="required">Cupboards</label>
<input id="cupboard" name="cupboard" type="number" min="0" max="1000" placeholder="Enter number of cupboards" value="<?php echo htmlspecialchars(getFormFieldValue('cupboard')); ?>" required>
<p class="helper-text">Number of cupboards available (0-1000)</p>
</div>
<div class="form-group">
<label for="board" class="required">White/Black Boards</label>
<input id="board" name="board" type="number" min="0" max="1000" placeholder="Enter number of boards" value="<?php echo htmlspecialchars(getFormFieldValue('board')); ?>" required>
<p class="helper-text">Number of writing boards available (0-1000)</p>
</div>
<div class="form-group">
<label for="dice" class="required">Dice/Podium</label>
<input id="dice" name="dice" type="number" min="0" max="1000" placeholder="Enter number of podiums" value="<?php echo htmlspecialchars(getFormFieldValue('dice')); ?>" required>
<p class="helper-text">Number of dice/podium available (0-1000)</p>
</div>
</div>
</div>
<!-- Section 3: Laboratories -->
<div class="form-section">
<h3 class="section-title"><i class="fas fa-flask"></i> Laboratories</h3>
<div id="labs-container">
<!-- Labs will be dynamically added here -->
</div>
<div class="add-lab-container">
<select id="labDropdown" class="form-control">
<option value="">-- Select Lab to Add --</option>
<?php foreach ($valid_lab_types as $type => $name): ?>
<option value="<?php echo htmlspecialchars($type); ?>"><?php echo htmlspecialchars($name); ?></option>
<?php endforeach; ?>
</select>
<button type="button" class="add-btn" onclick="addLab()">
<i class="fas fa-plus"></i> Add Lab
</button>
</div>
</div>
<div class="navigation-buttons">
<button type="button" class="nav-btn back" onclick="window.location.href='school_step3.php'">
<i class="fas fa-arrow-left"></i> Back
</button>
<button type="submit" class="nav-btn" id="submitBtn" style="margin-left: auto;" name="school_facilities_submit">
<i class="fas fa-save"></i> Save & Continue
</button>
</div>
</form>
</div>
</div>
<script>
$(document).ready(function() {
    // Lab management
    const labData = <?php echo json_encode($valid_lab_types); ?>;
    
    // Form validation
    $('#facilitiesForm').on('submit', function(e) {
        let isValid = true;
        
        // Clear previous error styling
        $('.validation-error').removeClass('validation-error');
        
        // Validate basic facilities (all radio groups)
        const basicFields = ['electricity', 'water', 'internet', 'road', 'assembly', 'ground', 'medical', 'gas', 'ptransport'];
        const errors = [];
        
        basicFields.forEach(function(field) {
            if (!$(`input[name="${field}"]:checked`).length) {
                isValid = false;
                $(`input[name="${field}"]`).closest('.facility-item').find('.radio-group').css('border', '2px solid #e74c3c');
                errors.push(ucfirst(field.replace('_', ' ')) + ' selection is required');
            } else {
                $(`input[name="${field}"]`).closest('.facility-item').find('.radio-group').css('border', '');
            }
        });
        
        // Validate furniture facilities (all numbers)
        const furnitureFields = [
            {name: 'schair', label: 'Staff chairs'},
            {name: 'stable', label: 'Staff tables'},
            {name: 'desk', label: 'Student desks'},
            {name: 'cupboard', label: 'Cupboards'},
            {name: 'board', label: 'Writing boards'},
            {name: 'dice', label: 'Podiums'}
        ];
        
        furnitureFields.forEach(function(field) {
            const val = $(`#${field.name}`).val();
            const min = parseInt($(`#${field.name}`).attr('min'), 10) || 0;
            const max = parseInt($(`#${field.name}`).attr('max'), 10);
            
            if (!val || val === '') {
                isValid = false;
                $(`#${field.name}`).addClass('validation-error');
                errors.push(field.label + ' is required');
            } else {
                const num = parseInt(val, 10);
                if (num < min || num > max) {
                    isValid = false;
                    $(`#${field.name}`).addClass('validation-error');
                    errors.push(`${field.label} must be between ${min} and ${max}`);
                }
            }
        });
        
        // Validate labs
        const $labs = $('#labs-container .lab-block');
        $labs.each(function() {
            const labId = $(this).attr('id').replace('lab_', '');
            const equipVal = $(`input[name='equip_${labId}']:checked`).val();
            
            if (!equipVal) {
                isValid = false;
                $(this).find('.radio-group').css('border', '2px solid #e74c3c');
                errors.push(labData[labId] + ': Equipment availability is required');
            } else {
                $(this).find('.radio-group').css('border', '');
            }
        });
        
        if (!isValid) {
            e.preventDefault();
            alert('Please fix the following errors:\n' + errors.join('\n'));
            return false;
        }
        
        // Show loading state
        $('#submitBtn').html('<span class="loading-spinner"></span> Processing...').prop('disabled', true);
    });

    // Real-time validation feedback
    $('input[required], select[required]').on('blur', function() {
        if (!$(this).val()) {
            $(this).addClass('validation-error');
        } else {
            $(this).removeClass('validation-error');
        }
    });

    // Number validation with range enforcement
    $('input[type="number"]').on('input', function() {
        let value = parseInt($(this).val(), 10);
        const max = parseInt($(this).attr('max'), 10);
        const min = parseInt($(this).attr('min'), 10) || 0;
        
        if (isNaN(value)) {
            $(this).val('');
            return;
        }
        
        if (value < min) value = min;
        if (!isNaN(max) && value > max) value = max;
        
        $(this).val(value);
    });
    
    // Pre-populate form from existing data
    <?php if (!empty($lab_data)): ?>
        <?php foreach ($lab_data as $lab_type => $lab): ?>
            addLab('<?php echo $lab_type; ?>', '<?php echo htmlspecialchars($lab['equipment_available']); ?>', '<?php echo htmlspecialchars($lab['requirements'] ?? ''); ?>');
        <?php endforeach; ?>
    <?php endif; ?>
    
    // Initialize dropdown state
    updateLabDropdown();
    
    // Prevent selection of disabled options
    $('#labDropdown').on('change', function() {
        const selected = $(this).find('option:selected');
        if (selected.prop('disabled')) {
            alert('This lab has already been added.');
            $(this).val('');
        }
    });
    
    // Utility function to capitalize first letter
    function ucfirst(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }
});

// Lab dropdown management - disable added labs
function updateLabDropdown() {
    const dropdown = $('#labDropdown');
    const addedLabs = [];
    
    // Get all currently added labs
    $('#labs-container .lab-block').each(function() {
        const labId = $(this).attr('id').replace('lab_', '');
        addedLabs.push(labId);
    });
    
    // Enable all options first
    dropdown.find('option').prop('disabled', false).css('color', '');
    
    // Disable options for labs that are already added
    addedLabs.forEach(function(labId) {
        dropdown.find(`option[value="${labId}"]`).prop('disabled', true).css('color', '#999');
    });
    
    // If current selection is disabled, clear it
    if (dropdown.find('option:selected').prop('disabled')) {
        dropdown.val('');
    }
}

function addLab(labId = null, equipValue = '', reqValue = '') {
    const dropdown = $('#labDropdown');
    let selectedValue, selectedText;
    
    if (labId) {
        selectedValue = labId;
        selectedText = <?php echo json_encode($valid_lab_types); ?>[labId];
    } else {
        selectedValue = dropdown.val();
        selectedText = dropdown.find('option:selected').text();
    }
    
    if (!selectedValue) {
        alert("Please select a lab to add.");
        return;
    }
    
    // Check if lab already exists
    if ($(`#lab_${selectedValue}`).length) {
        alert("This lab has already been added.");
        dropdown.val('');
        return;
    }

    const labDiv = $(`
        <div class="lab-block" id="lab_${selectedValue}">
            <h4>
                ${selectedText}
                <button type="button" class="remove-btn" onclick="removeLab('${selectedValue}')">
                    <i class="fas fa-trash"></i> Remove
                </button>
            </h4>
            <div class="form-grid">
                <div class="form-group">
                    <label class="required">Equipment Available</label>
                    <div class="radio-group">
                        <div class="radio-option">
                            <input type="radio" id="equip_${selectedValue}_yes" name="equip_${selectedValue}" value="YES" ${equipValue === 'YES' ? 'checked' : ''} required>
                            <label for="equip_${selectedValue}_yes" class="radio-label">Yes</label>
                        </div>
                        <div class="radio-option">
                            <input type="radio" id="equip_${selectedValue}_no" name="equip_${selectedValue}" value="NO" ${equipValue === 'NO' ? 'checked' : ''}>
                            <label for="equip_${selectedValue}_no" class="radio-label">No</label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="req_${selectedValue}">Requirements (if any)</label>
                    <input type="text" id="req_${selectedValue}" name="req_${selectedValue}" 
                        placeholder="List specific requirements..." maxlength="500" value="${reqValue}">
                    <p class="helper-text">Maximum 500 characters</p>
                </div>
            </div>
        </div>
    `);

    $('#labs-container').append(labDiv);
    
    // Update dropdown to disable the newly added lab
    updateLabDropdown();
    
    // Clear dropdown if not pre-populating
    if (!labId) {
        dropdown.val('');
    }
}

function removeLab(id) {
    if (confirm('Are you sure you want to remove this lab?')) {
        $(`#lab_${id}`).fadeOut(200, function() {
            $(this).remove();
            // Re-enable the lab in dropdown after removal
            updateLabDropdown();
        });
    }
}

// Handle BFCache restoration (back/forward navigation)
$(window).on('pageshow', function(event) {
    if (event.originalEvent.persisted) {
        console.log('Page restored from BFCache - reinitializing UI');
        updateLabDropdown();
    }
});
</script>
</body>
</html>