<!-- 
  **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 sixth file (school_step6.php):
    -->
	
	<?php
// school_step6.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'] ?? '';

// Check for success/error messages from save file
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']);
}

// Check for form data in session (for repopulation after error)
$form_data = $_SESSION['form_data'] ?? [];
if ($form_data) {
    unset($_SESSION['form_data']);
}

// Fetch classes from database
$classes = [];
try {
    $query = "SELECT class_id, class_name FROM class ORDER BY class_id";
    $result = $conn->query($query);
    
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $classes[] = $row;
        }
        $result->free();
    } else {
        $error_message = "Error fetching classes: " . $conn->error;
    }
} catch (Exception $e) {
    $error_message = "Error fetching classes: " . $e->getMessage();
}

// Fetch existing data if available (for edit mode)
$existing_data = [];
$school_students_id = null;

if (!empty($emis_code)) {
    try {
        // Get school_students record
        $query = "SELECT id FROM school_students WHERE emis_code = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $emis_code);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $school_students_id = $row['id'];
            
            // Get class summaries
            $summary_query = "
                SELECT sss.*, c.class_name 
                FROM school_students_summary sss
                JOIN class c ON sss.class_id = c.class_id
                WHERE sss.ss_id = ?
                ORDER BY c.class_id
            ";
            $stmt = $conn->prepare($summary_query);
            $stmt->bind_param("i", $school_students_id);
            $stmt->execute();
            $summary_result = $stmt->get_result();
            
            while ($row = $summary_result->fetch_assoc()) {
                $existing_data[] = $row;
            }
        }
    } catch (Exception $e) {
        // Silently fail - just don't load existing data
        error_log("Error loading existing data: " . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>School Students Registration - Step 6 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: #e74c3c; transform: translateY(-50%); z-index: 2; transition: width 0.3s ease; width: 60%; }
.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: #e74c3c; 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: #e74c3c; font-weight: 600; }
.form-container { background: white; border-radius: 10px; border-left: 4px solid #e74c3c; 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: #e74c3c; box-shadow: 0 0 0 3px rgba(231, 76, 60, 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; }
.optional::after { content: ""; color: #7f8c8d; font-weight: normal; font-size: 12px; }
.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 #e74c3c; display: flex; align-items: center; gap: 10px; }
.section-title i { color: #e74c3c; }
.submit-btn { display: block; width: 200px; margin: 30px auto 0; padding: 15px 30px; background: linear-gradient(135deg, #e74c3c, #c0392b); 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(231, 76, 60, 0.3); background: linear-gradient(135deg, #c0392b, #a93226); }
.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; }
.class-container { background-color: #fff; border: 2px solid #e0e0e0; border-radius: 10px; padding: 25px; margin-bottom: 20px; position: relative; transition: all 0.3s ease; }
.class-container:hover { border-color: #e74c3c; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
.class-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 2px solid #f0f0f0; }
.class-number { background-color: #e74c3c; color: white; width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 18px; }
.class-title { font-size: 20px; color: #2c3e50; font-weight: 600; }
.students-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 15px; }
.student-category { background-color: #f8f9fa; padding: 15px; border-radius: 8px; border-left: 3px solid #e74c3c; }
.student-category h4 { color: #2c3e50; margin-bottom: 15px; font-size: 16px; padding-bottom: 8px; border-bottom: 1px solid #e0e0e0; }
.gender-inputs { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
.gender-input { display: flex; flex-direction: column; }
.gender-input label { font-size: 13px; color: #666; margin-bottom: 5px; }
.action-buttons { display: flex; justify-content: center; gap: 15px; margin-top: 30px; margin-bottom: 20px; }
.add-btn { background-color: #2ecc71; color: white; border: none; padding: 12px 25px; border-radius: 6px; cursor: pointer; font-weight: 600; display: flex; align-items: center; gap: 8px; transition: all 0.3s ease; }
.add-btn:hover:not(:disabled) { background-color: #27ae60; transform: translateY(-2px); }
.add-btn:disabled { background-color: #95a5a6; cursor: not-allowed; transform: none; opacity: 0.6; }
.remove-btn { background-color: #e74c3c; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; font-size: 14px; display: flex; align-items: center; gap: 5px; transition: all 0.3s ease; }
.remove-btn:hover { background-color: #c0392b; transform: scale(1.05); }
.remove-btn i { margin-right: 3px; }
.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 #e74c3c; }
.school-info h3 { color: #2c3e50; margin-bottom: 10px; font-size: 16px; }
.school-info p { color: #666; font-size: 14px; }
.total-summary { background-color: #fdeaea; padding: 20px; border-radius: 8px; margin-top: 20px; border-left: 4px solid #e74c3c; }
.total-summary h4 { color: #2c3e50; margin-bottom: 15px; font-size: 18px; }
.summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }
.summary-item { background: white; padding: 15px; border-radius: 6px; text-align: center; border: 1px solid #f0f0f0; }
.summary-item .value { font-size: 24px; font-weight: 700; color: #e74c3c; }
.summary-item .label { font-size: 12px; color: #666; margin-top: 5px; }
.incomplete-class { border-color: #f39c12; background-color: #fff8e1; }
.complete-class { border-color: #27ae60; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.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, #e74c3c, #c0392b); 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(231, 76, 60, 0.3); background: linear-gradient(135deg, #c0392b, #a93226); }
.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); }
select option:disabled { color: #999; background-color: #f5f5f5; }
/* Responsive styles */
@media (max-width: 768px) { 
    .form-grid, .students-grid, .summary-grid { grid-template-columns: 1fr; gap: 15px; } 
    .progress-container { overflow-x: auto; padding-bottom: 20px; } 
    .form-container { padding: 20px; }
    .header h1 { font-size: 24px; }
    input[type="text"], input[type="email"], input[type="number"], select, textarea { padding: 10px 12px; font-size: 14px; }
    .submit-btn { width: 100%; max-width: 300px; }
    .class-container { padding: 15px; }
    .class-header { flex-direction: column; align-items: flex-start; gap: 10px; }
    .action-buttons { flex-direction: column; }
    .add-btn, .remove-btn { width: 100%; justify-content: center; }
    .nav-btn { padding: 10px 20px; font-size: 14px; }
}
@media (max-width: 480px) {
    .container { padding: 10px; }
    .form-container { padding: 15px; }
    .header { padding: 15px; }
    .gender-inputs { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<?php include 'floating_logout_school.php'; ?>
<div class="container">
<div class="header">
<h1><i class="fas fa-user-graduate"></i> School Students Registration - Step 6 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 completed" id="step4"><span>4</span><span class="step-label">School Facilities</span></div>
<div class="step completed" id="step5"><span>5</span><span class="step-label">School Posts</span></div>
<div class="step active" 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> Students Information</h3>
<p>Fill in all students details for <strong><?php echo htmlspecialchars($school_name); ?></strong> (EMIS: <strong><?php echo htmlspecialchars($emis_code); ?></strong>). Complete current class before adding a new one.</p>
<p><small><i class="fas fa-info-circle"></i> <strong>Note:</strong> Only Class Name and at least one student count (Total Male or Total Female) are required to add next class.</small></p>
</div>

<!-- FIXED: Added hidden input and enctype -->
<form method="POST" action="school_step6_save.php" id="studentsForm" enctype="application/x-www-form-urlencoded">
    <input type="hidden" name="school_students_submit" value="1">
    
    <!-- Section: Students Details -->
    <div class="form-section">
        <h3 class="section-title"><i class="fas fa-chalkboard-teacher"></i> Class-wise Students Details</h3>
        <div id="classesContainer">
            <!-- Classes will be dynamically added here -->
        </div>
        <div class="action-buttons">
            <button type="button" class="add-btn" id="addClassBtn" onclick="addClass()" disabled>
                <i class="fas fa-plus"></i> Add Class
            </button>
        </div>
    </div>
    
    <!-- Summary Section -->
    <div class="total-summary">
        <h4><i class="fas fa-chart-pie"></i> Total Students Summary</h4>
        <div class="summary-grid">
            <div class="summary-item">
                <div class="value" id="totalMaleStudents">0</div>
                <div class="label">Total Male Students</div>
            </div>
            <div class="summary-item">
                <div class="value" id="totalFemaleStudents">0</div>
                <div class="label">Total Female Students</div>
            </div>
            <div class="summary-item">
                <div class="value" id="totalStudents">0</div>
                <div class="label">Total Students</div>
            </div>
            <div class="summary-item">
                <div class="value" id="totalOrphans">0</div>
                <div class="label">Total Orphan Students</div>
            </div>
            <div class="summary-item">
                <div class="value" id="totalSpecial">0</div>
                <div class="label">Total Special Students</div>
            </div>
            <div class="summary-item">
                <div class="value" id="totalScholars">0</div>
                <div class="label">Total Scholarship Holders</div>
            </div>
        </div>
    </div>
    
    <div class="navigation-buttons">
        <button type="button" class="nav-btn back" onclick="window.location.href='school_step5.php'">
            <i class="fas fa-arrow-left"></i> Back
        </button>
        <button type="submit" class="nav-btn" id="submitBtn" style="margin-left: auto;">
            <i class="fas fa-save"></i> Save & Continue
        </button>
    </div>
</form>
</div>
</div>

<script>
// Define global functions first
var classCounter = 0;
var classes = <?php echo json_encode($classes); ?>;
var existingData = <?php echo json_encode($existing_data); ?>;

// Function to check if a class is complete
function checkClassComplete(classElement) {
    const className = classElement.find('select[name="Class_name[]"]').val();
    const totalMale = parseInt(classElement.find('input[name="totalMale[]"]').val()) || 0;
    const totalFemale = parseInt(classElement.find('input[name="totalFemale[]"]').val()) || 0;
    
    // Required: Class Name and at least one student count
    const isComplete = className !== '' && (totalMale > 0 || totalFemale > 0);
    
    // Update class styling
    if (isComplete) {
        classElement.removeClass('incomplete-class').addClass('complete-class');
    } else {
        classElement.removeClass('complete-class').addClass('incomplete-class');
    }
    
    return isComplete;
}

// Function to update Add Class button
function updateAddClassButton() {
    const lastClass = $('.class-container:last');
    if (lastClass.length > 0) {
        const lastClassComplete = checkClassComplete(lastClass);
        // FIXED: Always enable button if last class is complete, regardless of existing data
        $('#addClassBtn').prop('disabled', !lastClassComplete);
    } else {
        $('#addClassBtn').prop('disabled', true);
    }
}

// Function to update class dropdowns
function updateClassOptions() {
    const selectedClasses = [];
    $('select[name="Class_name[]"]').each(function() {
        const value = $(this).val();
        if (value) {
            selectedClasses.push(value);
        }
    });
    
    $('select[name="Class_name[]"]').each(function() {
        const currentValue = $(this).val();
        let optionsHtml = '<option value="">Select Class...</option>';
        
        if (classes && classes.length > 0) {
            classes.forEach(function(classItem) {
                const value = classItem.class_name;
                const text = classItem.class_name;
                
                if (value === currentValue) {
                    optionsHtml += `<option value="${value}" selected>${text}</option>`;
                } else if (selectedClasses.includes(value)) {
                    optionsHtml += `<option value="${value}" disabled>${text} (Already Selected)</option>`;
                } else {
                    optionsHtml += `<option value="${value}">${text}</option>`;
                }
            });
        } else {
            optionsHtml += '<option value="" disabled>No classes available</option>';
        }
        
        $(this).html(optionsHtml);
    });
}

// Function to update totals
function updateTotals() {
    let totalMale = 0;
    let totalFemale = 0;
    let totalOrphan = 0;
    let totalSpecial = 0;
    let totalScholar = 0;
    
    $('.class-container').each(function() {
        // Total students
        totalMale += parseInt($(this).find('input[name="totalMale[]"]').val()) || 0;
        totalFemale += parseInt($(this).find('input[name="totalFemale[]"]').val()) || 0;
        
        // Other categories
        totalOrphan += (parseInt($(this).find('input[name="orphanMale[]"]').val()) || 0) + 
                      (parseInt($(this).find('input[name="orphanFemale[]"]').val()) || 0);
        totalSpecial += (parseInt($(this).find('input[name="specialMale[]"]').val()) || 0) + 
                       (parseInt($(this).find('input[name="specialFemale[]"]').val()) || 0);
        totalScholar += (parseInt($(this).find('input[name="scholarMale[]"]').val()) || 0) + 
                       (parseInt($(this).find('input[name="scholarFemale[]"]').val()) || 0);
    });
    
    const totalStudents = totalMale + totalFemale;
    
    $('#totalMaleStudents').text(totalMale);
    $('#totalFemaleStudents').text(totalFemale);
    $('#totalStudents').text(totalStudents);
    $('#totalOrphans').text(totalOrphan);
    $('#totalSpecial').text(totalSpecial);
    $('#totalScholars').text(totalScholar);
}

// Function to add a class
function addClass(classData = null) {
    // Check if last class is complete (only if not loading existing data and not the first class)
    if (classData === null && $('.class-container').length > 0) {
        const lastClass = $('.class-container:last');
        const isComplete = checkClassComplete(lastClass);
        if (!isComplete) {
            alert('Please complete Class Name and add at least one student count (Total Male or Total Female) in the current class before adding a new one.');
            return false;
        }
    }
    
    classCounter++;
    const classId = 'class-' + classCounter;
    
    // Generate options HTML
    let optionsHtml = '<option value="">Select Class...</option>';
    if (classes && classes.length > 0) {
        classes.forEach(function(classItem) {
            optionsHtml += `<option value="${classItem.class_name}">${classItem.class_name}</option>`;
        });
    } else {
        optionsHtml += '<option value="" disabled>No classes available</option>';
    }
    
    // Set values from classData if provided
    const classNameValue = classData ? classData.class_name : '';
    const totalMaleValue = classData ? classData.total_male : '';
    const totalFemaleValue = classData ? classData.total_female : '';
    const repeatingMaleValue = classData ? classData.repeating_male : '0';
    const repeatingFemaleValue = classData ? classData.repeating_female : '0';
    const orphanMaleValue = classData ? classData.orphan_male : '0';
    const orphanFemaleValue = classData ? classData.orphan_female : '0';
    const specialMaleValue = classData ? classData.special_male : '0';
    const specialFemaleValue = classData ? classData.special_female : '0';
    const scholarMaleValue = classData ? classData.scholar_male : '0';
    const scholarFemaleValue = classData ? classData.scholar_female : '0';
    
    const classHtml = `
        <div class="class-container incomplete-class" id="${classId}">
            <div class="class-header">
                <div class="class-number">${classCounter}</div>
                <div class="class-title">Class Information</div>
            </div>
            
            <div class="form-group full-width">
                <label for="className_${classCounter}" class="required">Class Name</label>
                <select id="className_${classCounter}" name="Class_name[]" required>
                    ${optionsHtml}
                </select>
            </div>
            <br>
            <div class="students-grid">
                <!-- Total Students -->
                <div class="student-category">
                    <h4>Total Students *</h4>
                    <div class="gender-inputs">
                        <div class="gender-input">
                            <label for="totalMale_${classCounter}" class="optional">Male Students</label>
                            <input type="number" id="totalMale_${classCounter}" name="totalMale[]" min="0" value="${totalMaleValue}" placeholder="0">
                        </div>
                        <div class="gender-input">
                            <label for="totalFemale_${classCounter}" class="optional">Female Students</label>
                            <input type="number" id="totalFemale_${classCounter}" name="totalFemale[]" min="0" value="${totalFemaleValue}" placeholder="0">
                        </div>
                    </div>
                </div>
                
                <!-- Repeating Students -->
                <div class="student-category">
                    <h4>Repeating Students</h4>
                    <div class="gender-inputs">
                        <div class="gender-input">
                            <label for="repeatingMale_${classCounter}">Male Repeating</label>
                            <input type="number" id="repeatingMale_${classCounter}" name="repeatingMale[]" min="0" value="${repeatingMaleValue}">
                        </div>
                        <div class="gender-input">
                            <label for="repeatingFemale_${classCounter}">Female Repeating</label>
                            <input type="number" id="repeatingFemale_${classCounter}" name="repeatingFemale[]" min="0" value="${repeatingFemaleValue}">
                        </div>
                    </div>
                </div>
                
                <!-- Orphan Students -->
                <div class="student-category">
                    <h4>Orphan Students</h4>
                    <div class="gender-inputs">
                        <div class="gender-input">
                            <label for="orphanMale_${classCounter}">Male Orphans</label>
                            <input type="number" id="orphanMale_${classCounter}" name="orphanMale[]" min="0" value="${orphanMaleValue}">
                        </div>
                        <div class="gender-input">
                            <label for="orphanFemale_${classCounter}">Female Orphans</label>
                            <input type="number" id="orphanFemale_${classCounter}" name="orphanFemale[]" min="0" value="${orphanFemaleValue}">
                        </div>
                    </div>
                </div>
                
                <!-- Special Needs Students -->
                <div class="student-category">
                    <h4>Special Needs Students</h4>
                    <div class="gender-inputs">
                        <div class="gender-input">
                            <label for="specialMale_${classCounter}">Male Special</label>
                            <input type="number" id="specialMale_${classCounter}" name="specialMale[]" min="0" value="${specialMaleValue}">
                        </div>
                        <div class="gender-input">
                            <label for="specialFemale_${classCounter}">Female Special</label>
                            <input type="number" id="specialFemale_${classCounter}" name="specialFemale[]" min="0" value="${specialFemaleValue}">
                        </div>
                    </div>
                </div>
                
                <!-- Scholarship Holders -->
                <div class="student-category">
                    <h4>Scholarship Holders</h4>
                    <div class="gender-inputs">
                        <div class="gender-input">
                            <label for="scholarMale_${classCounter}">Male Scholars</label>
                            <input type="number" id="scholarMale_${classCounter}" name="scholarMale[]" min="0" value="${scholarMaleValue}">
                        </div>
                        <div class="gender-input">
                            <label for="scholarFemale_${classCounter}">Female Scholars</label>
                            <input type="number" id="scholarFemale_${classCounter}" name="scholarFemale[]" min="0" value="${scholarFemaleValue}">
                        </div>
                    </div>
                </div>
            </div>
            
            <div style="text-align: right; margin-top: 20px;">
                <button type="button" class="remove-btn" onclick="removeClass('${classId}')">
                    <i class="fas fa-trash"></i> Remove Class
                </button>
            </div>
        </div>
    `;
    
    $('#classesContainer').append(classHtml);
    
    // Set class name if provided
    if (classNameValue) {
        const newClass = $('#' + classId);
        newClass.find('select[name="Class_name[]"]').val(classNameValue);
    }
    
    updateClassOptions();
    updateTotals();
    
    // FIXED: Always update button state after adding a class
    updateAddClassButton();
    
    // If loading existing data, mark as complete after a short delay
    if (classData !== null) {
        setTimeout(function() {
            const newClass = $('#' + classId);
            checkClassComplete(newClass);
            updateAddClassButton();
        }, 100);
    }
    
    return true;
}

// Function to remove a class
function removeClass(classId) {
    if ($('.class-container').length <= 1) {
        alert('You must have at least one class. If you want to remove this class, please add another class first.');
        return;
    }
    
    $('#' + classId).remove();
    updateClassOptions();
    updateTotals();
    
    // Update class numbers
    $('.class-container').each(function(index) {
        const newNumber = index + 1;
        $(this).find('.class-number').text(newNumber);
        $(this).attr('id', 'class-' + newNumber);
    });
    
    // Update counter
    classCounter = $('.class-container').length;
    
    // FIXED: Update button based on last class
    updateAddClassButton();
}

$(document).ready(function() {
    // Load existing data or add first class
    if (existingData && existingData.length > 0) {
        // Load existing classes
        existingData.forEach(function(classData) {
            addClass(classData);
        });
        
        // FIXED: Force update button state after loading all classes
        setTimeout(function() {
            updateAddClassButton();
        }, 200);
    } else {
        // Add first empty class
        addClass();
    }
    
    // Form submission
    $('#studentsForm').on('submit', function(e) {
        let isValid = true;
        let hasClasses = false;
        let selectedClasses = new Set();
        let hasDuplicates = false;
        
        $('.class-container').each(function() {
            const className = $(this).find('select[name="Class_name[]"]').val();
            const totalMale = parseInt($(this).find('input[name="totalMale[]"]').val()) || 0;
            const totalFemale = parseInt($(this).find('input[name="totalFemale[]"]').val()) || 0;
            
            if (className) {
                hasClasses = true;
                
                // Check duplicates
                if (selectedClasses.has(className)) {
                    hasDuplicates = true;
                    $(this).find('select[name="Class_name[]"]').css('border-color', '#e74c3c');
                } else {
                    selectedClasses.add(className);
                }
                
                // Check required fields
                if (!className || (totalMale === 0 && totalFemale === 0)) {
                    isValid = false;
                    if (!className) {
                        $(this).find('select[name="Class_name[]"]').css('border-color', '#e74c3c');
                    }
                    if (totalMale === 0 && totalFemale === 0) {
                        $(this).find('input[name="totalMale[]"]').css('border-color', '#e74c3c');
                        $(this).find('input[name="totalFemale[]"]').css('border-color', '#e74c3c');
                    }
                }
            }
        });
        
        if (!hasClasses) {
            e.preventDefault();
            alert('Please add at least one class.');
            return false;
        }
        
        if (hasDuplicates) {
            e.preventDefault();
            alert('Duplicate classes detected. Each class can only be selected once.');
            return false;
        }
        
        if (!isValid) {
            e.preventDefault();
            alert('Please complete all required fields (Class Name and at least one student count) in each class.');
            return false;
        }
        
        // Show loading state
        $('#submitBtn').html('<span class="loading-spinner"></span> Processing...').prop('disabled', true);
    });

    // Real-time validation
    $(document).on('blur change', 'select[name="Class_name[]"]', function() {
        if (!$(this).val()) {
            $(this).css('border-color', '#e74c3c');
        } else {
            $(this).css('border-color', '#e0e0e0');
        }
        updateClassOptions();
        updateAddClassButton();
    });

    // Handle number inputs
    $(document).on('input blur', 'input[type="number"]', function() {
        // Validate min value
        const value = parseInt($(this).val()) || 0;
        if (value < 0) {
            $(this).val(0);
        }
        
        // Update totals
        updateTotals();
        
        // Update button state if this is a totalMale or totalFemale field
        if ($(this).attr('name') === 'totalMale[]' || $(this).attr('name') === 'totalFemale[]') {
            const classElement = $(this).closest('.class-container');
            checkClassComplete(classElement);
            updateAddClassButton();
        }
    });

    // Pre-populate from session data (form_data)
    <?php if (!empty($form_data) && isset($form_data['Class_name']) && is_array($form_data['Class_name'])): ?>
        $('#classesContainer').empty();
        classCounter = 0;
        
        <?php 
        foreach ($form_data['Class_name'] as $index => $className): 
            if (!empty($className)):
        ?>
                addClass({
                    class_name: "<?php echo htmlspecialchars($className); ?>",
                    total_male: "<?php echo htmlspecialchars($form_data['totalMale'][$index] ?? '0'); ?>",
                    total_female: "<?php echo htmlspecialchars($form_data['totalFemale'][$index] ?? '0'); ?>",
                    repeating_male: "<?php echo htmlspecialchars($form_data['repeatingMale'][$index] ?? '0'); ?>",
                    repeating_female: "<?php echo htmlspecialchars($form_data['repeatingFemale'][$index] ?? '0'); ?>",
                    orphan_male: "<?php echo htmlspecialchars($form_data['orphanMale'][$index] ?? '0'); ?>",
                    orphan_female: "<?php echo htmlspecialchars($form_data['orphanFemale'][$index] ?? '0'); ?>",
                    special_male: "<?php echo htmlspecialchars($form_data['specialMale'][$index] ?? '0'); ?>",
                    special_female: "<?php echo htmlspecialchars($form_data['specialFemale'][$index] ?? '0'); ?>",
                    scholar_male: "<?php echo htmlspecialchars($form_data['scholarMale'][$index] ?? '0'); ?>",
                    scholar_female: "<?php echo htmlspecialchars($form_data['scholarFemale'][$index] ?? '0'); ?>"
                });
        <?php 
            endif;
        endforeach; 
        ?>
        
        updateClassOptions();
        updateTotals();
        updateAddClassButton();
    <?php endif; ?>
});

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