<!--
**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 third file (school_step3.php):
-->

<?php
// school_step3.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 EXISTING DATA ===================
$existing_building_data = [];
$existing_rooms = [];
// 1. Fetch building data
if (!empty($emis_code)) {
    $stmt = $conn->prepare("SELECT * FROM school_building WHERE emis_code = ?");
    $stmt->bind_param("s", $emis_code);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $existing_building_data = $result->fetch_assoc();
    }
    $stmt->close();
}
// 2. Fetch rooms using building_id
$existing_rooms = [];
$building_id = $existing_building_data['id'] ?? null;
if (!empty($building_id)) {
    $stmt = $conn->prepare("SELECT * FROM building_rooms_details WHERE building_id = ? ORDER BY id");
    $stmt->bind_param("i", $building_id);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $existing_rooms[] = $row;
    }
    $stmt->close();
}
// 3. Fetch room types
$roomTypes = [];
$result = $conn->query("SELECT room_id, room_type FROM building_rooms ORDER BY room_id ASC");
while ($row = $result->fetch_assoc()) {
    $roomTypes[$row['room_id']] = $row['room_type'];
}
// 4. Fetch ownership types
$ownership_types = [];
$result = $conn->query("SELECT owner_id, ownership_type FROM building_ownership ORDER BY owner_id ASC");
while ($row = $result->fetch_assoc()) {
    $ownership_types[$row['owner_id']] = $row['ownership_type'];
}
// 5. Fetch construction materials
$material_types = [];
$result = $conn->query("SELECT material_id, material_name FROM building_material ORDER BY material_id");
while ($row = $result->fetch_assoc()) {
    $material_types[$row['material_id']] = $row['material_name'];
}
// =================== END FETCH DATA ===================
// =================== HELPER FUNCTIONS ===================
function getFormFieldValue($field_name, $default = '') {
    global $existing_building_data, $_POST;
    $field_map = [
        'building_select' => 'building_select',
        'ownershiptype' => 'ownershiptype',
        'rental_payee' => 'rental_payee',
        'construction_year' => 'construction_year',
        'building_condition' => 'building_condition',
        'cons_material' => 'cons_material',
        'boundry_wall' => 'boundry_wall',
        'nobuilding_reason' => 'nobuilding_reason'
    ];
    $db_field = $field_map[$field_name] ?? $field_name;
    if (isset($_POST[$field_name]) && $_POST[$field_name] !== '') {
        return $_POST[$field_name];
    }
    if (isset($_SESSION['form_data'][$field_name]) && $_SESSION['form_data'][$field_name] !== '') {
        return $_SESSION['form_data'][$field_name];
    }
    if (isset($existing_building_data[$db_field]) && $existing_building_data[$db_field] !== '') {
        return $existing_building_data[$db_field];
    }
    return $default;
}
function getRoomFieldValue($field_name, $index = 0, $default = '') {
    global $existing_rooms, $_POST;
    if (isset($_POST[$field_name]) && isset($_POST[$field_name][$index])) {
        return $_POST[$field_name][$index];
    }
    if (isset($_SESSION['form_data'][$field_name]) && isset($_SESSION['form_data'][$field_name][$index])) {
        return $_SESSION['form_data'][$field_name][$index];
    }
    if (isset($existing_rooms[$index])) {
        $field_map = [
            'room_type' => 'room_type',
            'total_rooms' => 'total_rooms',
            'room_condition' => 'room_condition'
        ];
        $db_field = $field_map[$field_name] ?? $field_name;
        if (isset($existing_rooms[$index][$db_field])) {
            return $existing_rooms[$index][$db_field];
        }
    }
    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']);
}
$building_select_state = getFormFieldValue('building_select', 'yes');
$building_available = ($building_select_state === 'yes');
// Prepare room data
$room_data = [];
$room_count = max(
    count($_POST['room_type'] ?? []),
    count($_SESSION['form_data']['room_type'] ?? []),
    count($existing_rooms)
);
for ($i = 0; $i < $room_count; $i++) {
    $room_type = getRoomFieldValue('room_type', $i);
    $total_rooms = getRoomFieldValue('total_rooms', $i);
    $room_condition = getRoomFieldValue('room_condition', $i);
    if (empty($room_type) && empty($total_rooms) && empty($room_condition)) {
        continue;
    }
    $room_data[] = [
        'type' => $room_type,
        'total' => $total_rooms,
        'condition' => $room_condition
    ];
}
if ($building_available && empty($room_data)) {
    $room_data[] = ['type' => '', 'total' => '', 'condition' => ''];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>School Building Registration - Step 3 of 10</title>
    <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: #9b59b6; transform: translateY(-50%); z-index: 2; transition: width 0.3s ease; width: 30%; }
        .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: #9b59b6; 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: #9b59b6; font-weight: 600; }
        .form-container { background: white; border-radius: 10px; border-left: 4px solid #9b59b6; 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: #9b59b6; box-shadow: 0 0 0 3px rgba(155, 89, 182, 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 #9b59b6; display: flex; align-items: center; gap: 10px; }
        .section-title i { color: #9b59b6; }
        .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 #9b59b6; 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; }
        .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: #9b59b6; cursor: pointer; font-size: 16px; padding: 5px; z-index: 2; }
        .year-picker-toggle:hover { color: #8e44ad; }
        .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: #9b59b6; }
        .year-option.selected { background: #9b59b6; color: white; border-color: #8e44ad; }
        .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; }
        .validation-success { border-color: #2ecc71 !important; }
        .validation-error { border-color: #e74c3c !important; }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        .school-info { background: #f8f9fa; padding: 15px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #9b59b6; }
        .school-info h3 { color: #2c3e50; margin-bottom: 10px; font-size: 16px; }
        .school-info p { color: #666; font-size: 14px; }
        .row-validation { font-size: 12px; margin-top: 5px; }
        .incomplete-row { animation: flashRow 1s ease; background-color: #fff5f5 !important; }
        @keyframes flashRow { 0%, 100% { background-color: #fff5f5; } 50% { background-color: #ffeaea; } }
        .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, #9b59b6, #8e44ad); 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(155, 89, 182, 0.3); background: linear-gradient(135deg, #8e44ad, #7d3c98); }
        .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); }
        @media (max-width: 768px) { .form-grid { grid-template-columns: 1fr; gap: 15px; } .progress-container { overflow-x: auto; padding-bottom: 20px; } }
        .validation-error { border-color: #e74c3c !important; }
    </style>
</head>
<body>
<?php include 'floating_logout_school.php'; ?>
<div class="container">
    <div class="header">
        <h1><i class="fas fa-building"></i> School Building Registration - Step 3 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 active" 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> Building Information</h3>
            <p>Fill in all building 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_step3_save.php" id="buildingForm">
            <div class="form-section">
                <h3 class="section-title"><i class="fas fa-check-circle"></i> Building Availability</h3>
                <div class="radio-group">
                    <div class="radio-option">
                        <input type="radio" id="building_yes" name="building_select" value="yes" <?php echo ($building_select_state == 'yes') ? 'checked' : ''; ?> required>
                        <label for="building_yes" class="radio-label">Building Available</label>
                    </div>
                    <div class="radio-option">
                        <input type="radio" id="building_no" name="building_select" value="no" <?php echo ($building_select_state == 'no') ? 'checked' : ''; ?> required>
                        <label for="building_no" class="radio-label">No Building</label>
                    </div>
                </div>
            </div>
            <div id="formBuildingYes" class="conditional-section" style="<?php echo ($building_select_state == 'yes') ? 'display: block;' : 'display: none;'; ?>">
                <h3 class="section-title"><i class="fas fa-home"></i> Building Information</h3>
                <div class="form-grid">
                    <div class="form-group">
                        <label for="ownershiptype" class="required">Ownership Status</label>
                        <select id="ownershiptype" name="ownershiptype" required>
                            <option value="">Select Ownership Status...</option>
                            <?php foreach ($ownership_types as $id => $type): ?>
                                <option value="<?php echo htmlspecialchars($id); ?>" <?php echo (getFormFieldValue('ownershiptype') == $id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($type); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="rental_payee">If Rental - Who Pays?</label>
                        <input id="rental_payee" name="rental_payee" type="text" placeholder="Enter who pays the rent" value="<?php echo htmlspecialchars(getFormFieldValue('rental_payee')); ?>">
                    </div>
                    <div class="form-group">
                        <label for="construction_year" class="required">Construction Year</label>
                        <div class="year-input-wrapper">
                            <input id="construction_year" name="construction_year" type="text" class="year-input-field" maxlength="4" autocomplete="off" placeholder="Type or click calendar icon" value="<?php echo htmlspecialchars(getFormFieldValue('construction_year')); ?>" required>
                            <button type="button" class="year-picker-toggle" data-target="construction_year"><i class="fas fa-calendar-alt"></i></button>
                            <div id="year-picker-construction_year" class="compact-year-picker"></div>
                            <div class="year-validation-error" id="construction_year_error"></div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="building_condition" class="required">Building Condition</label>
                        <select id="building_condition" name="building_condition" required>
                            <option value="">Select Condition...</option>
                            <option value="Satisfactory" <?php echo (getFormFieldValue('building_condition') == 'Satisfactory') ? 'selected' : ''; ?>>Satisfactory</option>
                            <option value="Need Repair" <?php echo (getFormFieldValue('building_condition') == 'Need Repair') ? 'selected' : ''; ?>>Need Repair</option>
                            <option value="Need Construction" <?php echo (getFormFieldValue('building_condition') == 'Need Construction') ? 'selected' : ''; ?>>Need Construction</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="cons_material" class="required">Construction Material</label>
                        <select id="cons_material" name="cons_material" required>
                            <option value="">Select Construction Material...</option>
                            <?php foreach ($material_types as $id => $material): ?>
                                <option value="<?php echo htmlspecialchars($id); ?>" <?php echo (getFormFieldValue('cons_material') == $id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($material); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="boundry_wall" class="required">Boundary Wall Present</label>
                        <select id="boundry_wall" name="boundry_wall" required>
                            <option value="">Select Option...</option>
                            <option value="yes" <?php echo (getFormFieldValue('boundry_wall') == 'yes') ? 'selected' : ''; ?>>Yes</option>
                            <option value="no" <?php echo (getFormFieldValue('boundry_wall') == 'no') ? 'selected' : ''; ?>>No</option>
                        </select>
                    </div>
                </div>
                <h3 class="section-title"><i class="fas fa-door-closed"></i> Rooms Details</h3>
                <div class="rooms-table-container">
                    <table class="rooms-table" id="roomsTable">
                        <thead>
                            <tr>
                                <th width="40%">Room Type</th>
                                <th width="20%">Total Rooms</th>
                                <th width="25%">Condition</th>
                                <th width="15%">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="roomsTableBody">
                            <?php foreach ($room_data as $index => $room):
                                $rowId = 'room-row-' . ($index + 1);
                            ?>
                            <tr id="<?php echo $rowId; ?>">
                                <td>
                                    <select name="room_type[]" class="room-type-select" required>
                                        <option value="">Select Room Type...</option>
                                        <?php foreach ($roomTypes as $id => $name): ?>
                                            <option value="<?php echo htmlspecialchars($id); ?>" <?php echo ($room['type'] == $id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($name); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td>
                                    <input type="number" name="total_rooms[]" min="0" value="<?php echo htmlspecialchars($room['total']); ?>" required>
                                </td>
                                <td>
                                    <select name="room_condition[]" required>
                                        <option value="">Select Condition...</option>
                                        <option value="Good" <?php if ($room['condition'] == 'Good') echo 'selected'; ?>>Good</option>
                                        <option value="Satisfactory" <?php if ($room['condition'] == 'Satisfactory') echo 'selected'; ?>>Satisfactory</option>
                                        <option value="Needs Repair" <?php if ($room['condition'] == 'Needs Repair') echo 'selected'; ?>>Needs Repair</option>
                                    </select>
                                </td>
                                <td>
                                    <button type="button" class="remove-btn" title="Remove this room">
                                        <i class="fas fa-trash"></i> Remove
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="action-buttons">
                    <button type="button" class="add-btn" id="addRoomBtn">
                        <i class="fas fa-plus"></i> Add Room
                    </button>
                </div>
            </div>
            <div id="formBuildingNo" class="conditional-section" style="<?php echo ($building_select_state == 'no') ? 'display: block;' : 'display: none;'; ?>">
                <h3 class="section-title"><i class="fas fa-exclamation-triangle"></i> No Building - Reason</h3>
                <div class="form-group full-width">
                    <label for="nobuilding_reason" class="required">Explain Reason for No Building</label>
                    <textarea id="nobuilding_reason" name="nobuilding_reason" placeholder="Provide detailed reason why there is no building for the school..." rows="4" required><?php echo htmlspecialchars(getFormFieldValue('nobuilding_reason')); ?></textarea>
                    <p class="helper-text">Please provide a comprehensive explanation for the absence of school building</p>
                </div>
            </div>
            <div class="navigation-buttons">
                <button type="button" class="nav-btn back" onclick="window.location.href='school_step2.php'">
                    <i class="fas fa-arrow-left"></i> Back
                </button>
                <button type="submit" class="nav-btn" id="submitBtn" style="margin-left: auto;" name="school_building_submit">
                    <i class="fas fa-save"></i> Save & Continue
                </button>
            </div>
        </form>
    </div>
</div>
<script>
    let roomCounter = $('#roomsTableBody tr').length;
    let isAddingNewRow = false;
    const roomTypes = <?php echo json_encode($roomTypes); ?>;

    function addRoomDetailRow(roomType = '', totalRooms = '', roomCondition = '') {
        roomCounter = $('#roomsTableBody tr').length + 1;
        const rowId = 'room-row-' + roomCounter;
        let roomOptions = '<option value="">Select room type...</option>';
        for (const [id, name] of Object.entries(roomTypes)) {
            const selected = (roomType == id) ? 'selected' : '';
            roomOptions += `<option value="${id}" ${selected}>${name}</option>`;
        }
        // FIX: Removed inline onchange/oninput/onblur handlers
        const newRow = `
        <tr id="${rowId}">
        <td>
            <select name="room_type[]" class="room-type-select" required>
            ${roomOptions}
            </select>
        </td>
        <td>
            <input name="total_rooms[]" type="number" min="0" placeholder="Total"
            value="${totalRooms}" required>
        </td>
        <td>
            <select name="room_condition[]" required>
            <option value="">Select condition...</option>
            <option value="Good" ${roomCondition === 'Good' ? 'selected' : ''}>Good</option>
            <option value="Satisfactory" ${roomCondition === 'Satisfactory' ? 'selected' : ''}>Satisfactory</option>
            <option value="Needs Repair" ${roomCondition === 'Needs Repair' ? 'selected' : ''}>Needs Repair</option>
            </select>
        </td>
        <td align="center">
            <button type="button" class="remove-btn" title="Remove this room">
            <i class="fas fa-trash"></i> Remove
            </button>
            <div class="row-validation" id="validation-${rowId}" style="display: none; margin-top: 5px;">
            <small style="color: #e74c3c; font-weight: bold;">
                <i class="fas fa-exclamation-circle"></i> Complete all fields before adding new row
            </small>
            </div>
        </td>
        </tr>
        `;
        $('#roomsTableBody').append(newRow);
        setTimeout(() => { $('#' + rowId + ' select[name="room_type[]"]').focus(); }, 100);
        isAddingNewRow = false;
        updateRoomTypeOptions();
        updateAddButtonState();
        return rowId;
    }

    function validateRow(rowId) {
        const $row = $('#' + rowId);
        const roomType = $row.find('select[name="room_type[]"]').val();
        const totalRooms = $row.find('input[name="total_rooms[]"]').val();
        const roomCondition = $row.find('select[name="room_condition[]"]').val();
        const isRoomTypeValid = roomType && roomType !== '';
        const isTotalRoomsValid = totalRooms !== '' && parseInt(totalRooms) >= 0;
        const isRoomConditionValid = roomCondition && roomCondition !== '';
        const $validationMsg = $('#validation-' + rowId);
        if (!isRoomTypeValid || !isTotalRoomsValid || !isRoomConditionValid) {
            $validationMsg.show();
            $row.find('select[name="room_type[]"]').css('border-color', isRoomTypeValid ? '#e0e0e0' : '#e74c3c');
            $row.find('input[name="total_rooms[]"]').css('border-color', isTotalRoomsValid ? '#e0e0e0' : '#e74c3c');
            $row.find('select[name="room_condition[]"]').css('border-color', isRoomConditionValid ? '#e0e0e0' : '#e74c3c');
        } else {
            $validationMsg.hide();
            $row.find('select[name="room_type[]"], input[name="total_rooms[]"], select[name="room_condition[]"]').css('border-color', '#e0e0e0');
        }
        updateAddButtonState();
        updateRoomTypeOptions();
        return isRoomTypeValid && isTotalRoomsValid && isRoomConditionValid;
    }

    function updateAddButtonState() {
        const $addButton = $('#addRoomBtn');
        const $rows = $('#roomsTableBody tr');
        if ($rows.length === 0) {
            $addButton.prop('disabled', false).css('opacity', '1').html('<i class="fas fa-plus"></i> Add Room');
            return;
        }
        let allRowsComplete = true;
        $rows.each(function () {
            const roomType = $(this).find('select[name="room_type[]"]').val();
            const totalRooms = $(this).find('input[name="total_rooms[]"]').val();
            const condition = $(this).find('select[name="room_condition[]"]').val();
            if (!roomType || totalRooms === '' || !condition) {
                allRowsComplete = false;
                return false;
            }
        });
        if (allRowsComplete) {
            $addButton.prop('disabled', false).css('opacity', '1').html('<i class="fas fa-plus"></i> Add Room');
        } else {
            $addButton.prop('disabled', true).css('opacity', '0.6').html('<i class="fas fa-lock"></i> Complete current row first');
        }
    }

    function updateRoomTypeOptions() {
        const selectedTypes = [];
        $('#roomsTableBody select.room-type-select').each(function () {
            const val = $(this).val();
            if (val) selectedTypes.push(val);
        });
        $('#roomsTableBody select.room-type-select').each(function () {
            const currentVal = $(this).val();
            $(this).find('option').each(function () {
                if ($(this).val() === '' || $(this).val() === currentVal) {
                    $(this).prop('disabled', false);
                } else if (selectedTypes.includes($(this).val())) {
                    $(this).prop('disabled', true);
                } else {
                    $(this).prop('disabled', false);
                }
            });
        });
    }

    function handleAddRoomClick() {
        if (isAddingNewRow) return;
        const $rows = $('#roomsTableBody tr');
        let canAddNewRow = true;
        $rows.each(function() {
            const rowId = $(this).attr('id');
            if (rowId && rowId.startsWith('room-row-')) {
                if (!validateRow(rowId)) {
                    canAddNewRow = false;
                    $('#' + rowId).addClass('incomplete-row');
                    setTimeout(() => $('#' + rowId).removeClass('incomplete-row'), 1000);
                    alert('Please complete all fields in the current row before adding a new one.');
                    return false;
                }
            }
        });
        if (canAddNewRow) {
            isAddingNewRow = true;
            addRoomDetailRow();
        }
    }

    $(document).on('click', '.remove-btn', function(e) {
        e.preventDefault();
        const $btn = $(this);
        const $row = $btn.closest('tr');
        if ($row.attr('id') && $row.attr('id').startsWith('room-row-')) {
            if (!confirm('Are you sure you want to remove this room? Changes will be saved when you click "Save & Continue".')) {
                return;
            }
        }
        $row.fadeOut(200, function() {
            $(this).remove();
            updateAddButtonState();
            updateRoomTypeOptions();
            if ($('#building_yes').is(':checked') && $('#roomsTableBody tr').length === 0) {
                setTimeout(() => addRoomDetailRow(), 150);
            }
        });
    });

    $(document).ready(function () {
        // FIX: Added Event Delegation for Validation
        // This ensures both PHP-rendered rows and JS-added rows trigger validation
        $(document).on('change', 'select[name="room_type[]"], select[name="room_condition[]"]', function() {
            const rowId = $(this).closest('tr').attr('id');
            if (rowId) validateRow(rowId);
        });

        $(document).on('input blur', 'input[name="total_rooms[]"]', function() {
            const rowId = $(this).closest('tr').attr('id');
            if (rowId) validateRow(rowId);
        });

        updateRoomTypeOptions();
        updateAddButtonState();
        $('#addRoomBtn').click(handleAddRoomClick);
        
        // Initialize required attributes based on selected radio
        function initRequiredAttributes() {
            const buildingSelect = $('input[name="building_select"]:checked').val();
            if (buildingSelect === 'yes') {
                $('#ownershiptype, #construction_year, #building_condition, #cons_material, #boundry_wall').attr('required', true);
                $('#nobuilding_reason').removeAttr('required');
                // Make room fields required
                $('#roomsTableBody select[name="room_type[]"], #roomsTableBody input[name="total_rooms[]"], #roomsTableBody select[name="room_condition[]"]').attr('required', true);
            } else if (buildingSelect === 'no') {
                $('#ownershiptype, #construction_year, #building_condition, #cons_material, #boundry_wall').removeAttr('required');
                $('#nobuilding_reason').attr('required', true);
                // Remove required from room fields
                $('#roomsTableBody select[name="room_type[]"], #roomsTableBody input[name="total_rooms[]"], #roomsTableBody select[name="room_condition[]"]').removeAttr('required');
            }
        }
        $('input[name="building_select"]').change(function () {
            const value = $(this).val();
            if (value === 'yes') {
                $('#formBuildingYes').slideDown();
                $('#formBuildingNo').slideUp();
                if ($('#roomsTableBody tr').length === 0) addRoomDetailRow();
                // Set required attributes
                $('#ownershiptype, #construction_year, #building_condition, #cons_material, #boundry_wall').attr('required', true);
                $('#roomsTableBody select[name="room_type[]"], #roomsTableBody input[name="total_rooms[]"], #roomsTableBody select[name="room_condition[]"]').attr('required', true);
                $('#nobuilding_reason').removeAttr('required');
                // Clear validation styles
                $('#nobuilding_reason').removeClass('validation-error');
            } else {
                $('#formBuildingYes').slideUp();
                $('#formBuildingNo').slideDown();
                // Remove required attributes
                $('#ownershiptype, #construction_year, #building_condition, #cons_material, #boundry_wall').removeAttr('required');
                $('#roomsTableBody select[name="room_type[]"], #roomsTableBody input[name="total_rooms[]"], #roomsTableBody select[name="room_condition[]"]').removeAttr('required');
                $('#nobuilding_reason').attr('required', true);
                // Clear validation styles
                $('#ownershiptype, #construction_year, #building_condition, #cons_material, #boundry_wall').removeClass('validation-error');
            }
        });
        $(document).on('change', 'select.room-type-select', function () {
            updateRoomTypeOptions();
        });
        // Remove novalidate to enable HTML5 validation
        $('#buildingForm').removeAttr('novalidate');
        $('#buildingForm').on('submit', function(e) {
            // Remove previous validation errors
            $('.validation-error').removeClass('validation-error');
            let isValid = true;
            const errors = [];
            const buildingSelect = $('input[name="building_select"]:checked').val();
            if (!buildingSelect) {
                errors.push('Please select building availability');
                isValid = false;
            }
            if (buildingSelect === 'yes') {
                // Validate building fields
                if (!$('#ownershiptype').val()) {
                    errors.push('Ownership Status is required');
                    $('#ownershiptype').addClass('validation-error');
                    isValid = false;
                }
                if (!$('#construction_year').val()) {
                    errors.push('Construction Year is required');
                    $('#construction_year').addClass('validation-error');
                    isValid = false;
                }
                if (!$('#building_condition').val()) {
                    errors.push('Building Condition is required');
                    $('#building_condition').addClass('validation-error');
                    isValid = false;
                }
                if (!$('#cons_material').val()) {
                    errors.push('Construction Material is required');
                    $('#cons_material').addClass('validation-error');
                    isValid = false;
                }
                if (!$('#boundry_wall').val()) {
                    errors.push('Boundary Wall information is required');
                    $('#boundry_wall').addClass('validation-error');
                    isValid = false;
                }
                // Validate rooms
                const $rows = $('#roomsTableBody tr');
                if ($rows.length === 0) {
                    errors.push('At least one room detail is required');
                    isValid = false;
                } else {
                    $rows.each(function(index) {
                        const roomType = $(this).find('select[name="room_type[]"]').val();
                        const totalRooms = $(this).find('input[name="total_rooms[]"]').val();
                        const condition = $(this).find('select[name="room_condition[]"]').val();
                        if (!roomType) {
                            errors.push('Room type is required for row ' + (index + 1));
                            $(this).find('select[name="room_type[]"]').addClass('validation-error');
                            isValid = false;
                        }
                        if (totalRooms === '' || totalRooms === null) {
                            errors.push('Total rooms is required for row ' + (index + 1));
                            $(this).find('input[name="total_rooms[]"]').addClass('validation-error');
                            isValid = false;
                        }
                        if (!condition) {
                            errors.push('Room condition is required for row ' + (index + 1));
                            $(this).find('select[name="room_condition[]"]').addClass('validation-error');
                            isValid = false;
                        }
                    });
                }
            } else if (buildingSelect === 'no') {
                // Validate no building reason
                const reason = $('#nobuilding_reason').val();
                if (!reason || reason.trim() === '') {
                    errors.push('Reason for no building is required');
                    $('#nobuilding_reason').addClass('validation-error');
                    isValid = false;
                } else if (reason.trim().length < 50) {
                    errors.push('Reason must be at least 50 characters long');
                    $('#nobuilding_reason').addClass('validation-error');
                    isValid = false;
                }
            }
            if (!isValid) {
                e.preventDefault();
                e.stopPropagation();
                alert('Please fix the following errors:\n' + errors.join('\n'));
                return false;
            }
            return true;
        });
        // Initialize required attributes on page load
        initRequiredAttributes();
    });

    $(window).on('pageshow', function(event) {
        if (event.originalEvent.persisted) {
            roomCounter = $('#roomsTableBody tr').length;
            updateRoomTypeOptions();
            updateAddButtonState();
        }
    });
</script>
<script>
    $(document).ready(function() {
        const currentYear = new Date().getFullYear();
        let activeYearPicker = null;
        function validateYear(year, fieldId) {
            const errorElement = $('#' + fieldId + '_error');
            if (!year) {
                errorElement.hide();
                return true;
            }
            if (!/^\d{4}$/.test(year)) {
                errorElement.text('Please enter a valid 4-digit year').show();
                return false;
            }
            const yearNum = parseInt(year);
            if (yearNum < 1901) {
                errorElement.text('Year cannot be before 1901').show();
                return false;
            }
            if (yearNum > currentYear) {
                errorElement.text('Future years are not allowed').show();
                return false;
            }
            errorElement.hide();
            return true;
        }
        function initializeYearPickers() {
            $('.year-input-field').each(function() {
                const fieldId = $(this).attr('id');
                const pickerId = 'year-picker-' + fieldId;
                const picker = $('#' + pickerId);
                if (picker.length === 0) return;
                generateYearGrid(picker, currentYear);
                if ($(this).val()) {
                    updateYearSelection(picker, $(this).val());
                }
            });
        }
        function generateYearGrid(picker, centerYear) {
            const year = parseInt(centerYear) || currentYear;
            const startYear = Math.max(1901, 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"><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"><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});
            picker.find('.year-option').off('click').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);
                inputField.val(selectedYear).trigger('change');
                updateYearSelection(picker, selectedYear);
                validateYear(selectedYear, inputId);
                picker.removeClass('active');
                activeYearPicker = null;
            });
            picker.find('.prev-decade').off('click').on('click', function(e) {
                e.stopPropagation();
                const range = picker.data('current-range');
                const newCenterYear = Math.max(1901, range.start - 8);
                generateYearGrid(picker, newCenterYear);
            });
            picker.find('.next-decade').off('click').on('click', function(e) {
                e.stopPropagation();
                const range = picker.data('current-range');
                const newCenterYear = Math.min(currentYear, range.end + 8);
                generateYearGrid(picker, newCenterYear);
            });
        }
        function updateYearSelection(picker, year) {
            picker.find('.year-option').removeClass('selected');
            picker.find(`.year-option[data-year="${year}"]`).addClass('selected');
            picker.data('selected-year', year);
        }
        $(document).on('click', '.year-picker-toggle', function(e) {
            e.stopPropagation();
            const targetId = $(this).data('target');
            const picker = $('#year-picker-' + targetId);
            $('.compact-year-picker').not(picker).removeClass('active');
            picker.toggleClass('active');
            activeYearPicker = picker.hasClass('active') ? picker : null;
        });
        $(document).on('click', function(e) {
            if (activeYearPicker && !$(e.target).closest('.compact-year-picker, .year-picker-toggle').length) {
                activeYearPicker.removeClass('active');
                activeYearPicker = null;
            }
        });
        $('.year-input-field').on('input', function() {
            const value = $(this).val();
            const fieldId = $(this).attr('id');
            const picker = $('#year-picker-' + fieldId);
            if (value === '') {
                updateYearSelection(picker, null);
            } else if (/^\d{4}$/.test(value)) {
                const year = parseInt(value, 10);
                if (year >= 1901 && year <= currentYear) {
                    updateYearSelection(picker, year);
                }
            }
            validateYear(value, fieldId);
        });
        $('.year-input-field').on('blur', function() {
            const value = $(this).val();
            const fieldId = $(this).attr('id');
            validateYear(value, fieldId);
            if (value === '') {
                $(this).removeClass('validation-error validation-success');
            } else if (!/^\d{4}$/.test(value)) {
                $(this).addClass('validation-error');
            } else {
                const year = parseInt(value, 10);
                if (year < 1901 || year > currentYear) {
                    $(this).addClass('validation-error');
                } else {
                    $(this).removeClass('validation-error').addClass('validation-success');
                }
            }
        });
        $('.year-input-field').on('keypress', function(e) {
            const charCode = e.which ? e.which : e.keyCode;
            if ($(this).val().length === 0 && charCode === 48) return false;
            if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;
            if ($(this).val().length >= 4) return false;
            return true;
        });
        $('.year-input-field').on('paste', function(e) {
            const pasteData = e.originalEvent.clipboardData.getData('text');
            if (!/^\d+$/.test(pasteData)) e.preventDefault();
            if ($(this).val().length + pasteData.length > 4) e.preventDefault();
        });
        initializeYearPickers();
    });
</script>
</body>
</html>