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

<?php
// school_step7.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']);
}

// Get current year
$current_year = date('Y');

// Generate session years array starting from last year (2025-2026 for current year 2026)
$session_years = [];
for ($i = 0; $i < 5; $i++) {
    $year = $current_year - 1 - $i; // Start from last year
    $next_year = $year + 1;
    $session_years[] = [
        'value' => $year . '-' . $next_year,
        'year' => $year,
        'display' => $year . '-' . $next_year
    ];
}

// Fetch existing board results data from database
$existing_results = [];
if (!empty($emis_code)) {
    try {
        $query = "SELECT * FROM school_board_results WHERE emis_code = ? ORDER BY session_year DESC, class_name";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $emis_code);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $existing_results[] = $row;
        }
        
        error_log("Found " . count($existing_results) . " existing board results for EMIS: $emis_code");
    } catch (Exception $e) {
        error_log("Error fetching existing board results: " . $e->getMessage());
    }
}

// Organize existing results by session for easier display
$results_by_session = [];
foreach ($existing_results as $result) {
    $session = $result['session_year'];
    if (!isset($results_by_session[$session])) {
        $results_by_session[$session] = [];
    }
    $results_by_session[$session][] = $result;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>School Board Results Registration - Step 7 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: 1400px; 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: #8e44ad; transform: translateY(-50%); z-index: 2; transition: width 0.3s ease; width: 70%; }
.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: #8e44ad; 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: #8e44ad; font-weight: 600; }
.form-container { background: white; border-radius: 10px; border-left: 4px solid #8e44ad; 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: #8e44ad; box-shadow: 0 0 0 3px rgba(142, 68, 173, 0.1); }
input[readonly] { background-color: #f8f9fa; border-color: #ddd; color: #666; }
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 #8e44ad; display: flex; align-items: center; gap: 10px; }
.section-title i { color: #8e44ad; }
.submit-btn { display: block; width: 200px; margin: 30px auto 0; padding: 15px 30px; background: linear-gradient(135deg, #8e44ad, #732d91); 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(142, 68, 173, 0.3); background: linear-gradient(135deg, #732d91, #5e2477); }
.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; }
.results-container { margin-top: 20px; }
.session-container { background-color: #f8f9fa; border-radius: 10px; margin-bottom: 30px; border: 1px solid #e0e0e0; overflow: hidden; }
.session-header { background: linear-gradient(135deg, #8e44ad, #732d91); color: white; padding: 15px 20px; font-weight: 600; font-size: 18px; }
.session-header i { margin-right: 10px; }
.session-content { padding: 20px; }
.entries-grid { display: grid; grid-template-columns: 1.5fr 2fr 2fr 2fr 1fr; gap: 15px; align-items: start; }
.entries-container {display: grid; grid-template-columns: 1fr; gap: 25px; /* This creates vertical gaps between grid items */}
.entry-row {display: grid; grid-template-columns: subgrid; grid-column: 1 / -1; background-color: #ffffff; border-radius: 8px; padding: 15px; border: 1px solid #eaeaea; box-shadow: 0 2px 4px rgba(0,0,0,0.02); }
.entry-row:hover {border-color: #8e44ad; box-shadow: 0 4px 8px rgba(142, 68, 173, 0.1); }
.class-select { grid-column: 1; }
.arts-section { grid-column: 2; }
.science-section { grid-column: 3; }
.overall-section { grid-column: 4; }
.actions-section { grid-column: 5; }
.category-box { background-color: white; border-radius: 8px; padding: 15px; border: 1px solid #e0e0e0; height: 100%; }
.category-box h5 { color: #2c3e50; margin-bottom: 12px; font-size: 14px; font-weight: 600; text-align: center; padding-bottom: 8px; border-bottom: 2px solid #8e44ad; }
.category-box .input-group { margin-bottom: 10px; }
.category-box .input-group label { font-size: 12px; color: #666; margin-bottom: 3px; display: block; }
.category-box .input-group input { width: 100%; padding: 8px 10px; font-size: 14px; }
.percentage-display { background-color: #f0f0f0; padding: 8px 12px; border-radius: 4px; font-size: 14px; font-weight: 600; color: #27ae60; text-align: center; margin-top: 8px; display: flex; align-items: center; justify-content: center; gap: 5px; }
.percentage-display span { color: #2c3e50; font-weight: normal; }
.percentage-display input { width: 70px !important; padding: 4px !important; font-size: 14px !important; text-align: center; border: none !important; background: transparent !important; font-weight: 600; color: #27ae60; }
.action-buttons { display: flex; gap: 15px; justify-content: center; margin-top: 20px; margin-bottom: 30px; }
.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; margin: 0 auto; }
.add-btn:hover { background-color: #27ae60; transform: translateY(-2px); }
.add-btn:active { transform: translateY(0); }
.remove-btn { background-color: #e74c3c; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer; font-size: 13px; display: flex; align-items: center; gap: 5px; transition: all 0.3s ease; width: 100%; justify-content: center; }
.remove-btn:hover { background-color: #c0392b; transform: scale(1.02); }
.remove-btn i { margin-right: 3px; }
.validation-success { border-color: #2ecc71 !important; }
.validation-error { border-color: #e74c3c !important; }
.validation-warning { border-color: #f39c12 !important; background-color: #fff8e1 !important; }
.school-info { background: #f8f9fa; padding: 15px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #8e44ad; }
.school-info h3 { color: #2c3e50; margin-bottom: 10px; font-size: 16px; }
.school-info p { color: #666; font-size: 14px; }
.summary-box { background-color: #f5f0f9; padding: 20px; border-radius: 8px; margin-top: 20px; border-left: 4px solid #8e44ad; }
.summary-box h4 { color: #2c3e50; margin-bottom: 15px; font-size: 18px; }
.summary-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; }
.stat-item { background: white; padding: 15px; border-radius: 6px; text-align: center; border: 1px solid #f0f0f0; }
.stat-item .value { font-size: 22px; font-weight: 700; color: #8e44ad; }
.stat-item .label { font-size: 12px; color: #666; margin-top: 5px; }
.session-info { background: #e8f4fc; padding: 10px 15px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #3498db; }
.session-info p { color: #2c3e50; font-size: 14px; margin: 0; }
.order-warning { background: #fff3cd; padding: 10px 15px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #ffc107; color: #856404; font-size: 14px; }
.order-warning i { color: #856404; margin-right: 8px; }
.order-indicator { background: #8e44ad; color: white; font-size: 12px; padding: 2px 8px; border-radius: 10px; margin-left: 5px; font-weight: bold; }
.error-text { color: #e74c3c; font-size: 11px; margin-top: 3px; display: none; }
.empty-state { text-align: center; padding: 30px; color: #7f8c8d; font-style: italic; }
.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, #8e44ad, #732d91); 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(142, 68, 173, 0.3); background: linear-gradient(135deg, #732d91, #5e2477); }
.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:disabled { background-color: #f5f5f5; color: #999; cursor: not-allowed; }

/* New styles for disabled options */
select option:disabled {
    color: #e74c3c !important;
    background-color: #fff0f0 !important;
    font-weight: 500;
    font-style: italic;
}

select option:checked {
    color: #27ae60 !important;
    font-weight: 600;
    background-color: #f0fff0 !important;
}

select option[value=""] {
    color: #7f8c8d !important;
    font-style: italic;
    background-color: white !important;
}

.select-hint {
    font-size: 11px;
    color: #666;
    margin-bottom: 15px;
    padding: 8px 12px;
    background-color: #f8f9fa;
    border-radius: 4px;
    display: flex;
    align-items: center;
    gap: 20px;
    border: 1px solid #e0e0e0;
}

.select-hint span {
    display: flex;
    align-items: center;
    gap: 6px;
}

.select-hint i {
    font-size: 12px;
}

.select-hint .text-green { color: #27ae60; }
.select-hint .text-red { color: #e74c3c; }
.select-hint .text-gray { color: #7f8c8d; }

@media (max-width: 1200px) {
    .entries-grid { grid-template-columns: 1fr; }
    .class-select, .arts-section, .science-section, .overall-section, .actions-section { grid-column: 1; }
}
@media (max-width: 768px) { 
    .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; }
    .summary-stats { grid-template-columns: repeat(2, 1fr); }
    .nav-btn { padding: 10px 20px; font-size: 14px; }
    .select-hint { flex-wrap: wrap; gap: 10px; }
}
@media (max-width: 480px) {
    .container { padding: 10px; }
    .form-container { padding: 15px; }
    .header { padding: 15px; }
    .summary-stats { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<?php include 'floating_logout_school.php'; ?>
<div class="container">
<div class="header">
<h1><i class="fas fa-chart-line"></i> School Board Results Registration - Step 7 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 completed" id="step6"><span>6</span><span class="step-label">Students</span></div>
<div class="step active" 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> Board Results Information</h3>
<p>Fill in board examination results for <strong><?php echo htmlspecialchars($school_name); ?></strong> (EMIS: <strong><?php echo htmlspecialchars($emis_code); ?></strong>). Add results for each class in each session.</p>
</div>
<div class="session-info">
<p><i class="fas fa-calendar-alt"></i> <strong>Current Year:</strong> <?php echo $current_year; ?> | <strong>Available Sessions (Last 5 Years):</strong>
 
    <?php 
    $session_displays = array_column($session_years, 'display');
    echo implode(', ', $session_displays);
    ?>
</p>
</div>
<div class="order-warning">
<i class="fas fa-exclamation-triangle"></i> 
<strong>Important:</strong> For each class, please enter results in descending order (newest to oldest). 
Each class can have results for multiple sessions, but cannot have duplicate entries for the same session.
</div>
<form method="POST" action="school_step7_save.php" id="resultsForm">
    <input type="hidden" name="school_board_results_submit" value="1">
    
    <!-- Section: Board Results Details -->
    <div class="form-section">
        <h3 class="section-title"><i class="fas fa-graduation-cap"></i> Board Examination Results by Session</h3>
        <div id="sessionsContainer">
            <!-- All 5 sessions will be generated here -->
        </div>
    </div>
    
    <!-- Summary Section -->
    <div class="summary-box">
        <h4><i class="fas fa-chart-bar"></i> Overall Results Summary</h4>
        <div class="summary-stats">
            <div class="stat-item">
                <div class="value" id="totalEntries">0</div>
                <div class="label">Total Entries</div>
            </div>
            <div class="stat-item">
                <div class="value" id="totalStudents">0</div>
                <div class="label">Total Students</div>
            </div>
            <div class="stat-item">
                <div class="value" id="totalPassed">0</div>
                <div class="label">Total Passed</div>
            </div>
            <div class="stat-item">
                <div class="value" id="overallPercentage">0%</div>
                <div class="label">Overall Pass %</div>
            </div>
        </div>
    </div>
    
    <div class="navigation-buttons">
        <button type="button" class="nav-btn back" onclick="window.location.href='school_step6.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>
$(document).ready(function() {
    // Initialize counters
    window.entryCounter = 0;
    
    // Available sessions (starting from last year)
    window.availableSessions = [
        <?php foreach ($session_years as $session): ?>
            {value: '<?php echo $session['value']; ?>', year: <?php echo $session['year']; ?>, display: '<?php echo $session['display']; ?>'},
        <?php endforeach; ?>
    ];
    
    // Available class options
    window.classList = ['5', '8', '9', '10', '11', '12'];
    window.classDisplay = {
        '5': '5th',
        '8': '8th',
        '9': '9th',
        '10': '10th',
        '11': 'First Year',
        '12': 'Second Year'
    };
    
    // Load existing results from database
    var existingResultsBySession = <?php echo json_encode($results_by_session); ?>;
    var formData = <?php echo json_encode($form_data); ?>;
    
    console.log('Existing results:', existingResultsBySession);
    
    // Generate all 5 sessions
    window.availableSessions.forEach(function(session) {
        addSession(session.value, existingResultsBySession[session.value] || []);
    });
    
    // Update summary after loading
    setTimeout(function() {
        updateSummary();
        updateAllClassOptions();
    }, 100);
    
    // Form validation
    $('#resultsForm').on('submit', function(e) {
        let isValid = true;
        let hasEntries = false;
        let validationErrors = [];
        
        // Check each session and entry
        $('.session-container').each(function() {
            const sessionYear = $(this).data('session');
            const entries = $(this).find('.entry-row');
            
            entries.each(function() {
                const className = $(this).find('.class-select select').val();
                
                if (className) {
                    hasEntries = true;
                    
                    // Get all values
                    const artsTotal = parseInt($(this).find('.arts-total').val()) || 0;
                    const artsPass = parseInt($(this).find('.arts-pass').val()) || 0;
                    const scienceTotal = parseInt($(this).find('.science-total').val()) || 0;
                    const sciencePass = parseInt($(this).find('.science-pass').val()) || 0;
                    
                    // Validate arts pass <= arts total
                    if (artsPass > artsTotal) {
                        isValid = false;
                        validationErrors.push(`Class ${getClassName(className)} in ${sessionYear}: Arts Pass (${artsPass}) cannot exceed Arts Total (${artsTotal})`);
                        $(this).find('.arts-pass').addClass('validation-warning');
                    }
                    
                    // Validate science pass <= science total
                    if (sciencePass > scienceTotal) {
                        isValid = false;
                        validationErrors.push(`Class ${getClassName(className)} in ${sessionYear}: Science Pass (${sciencePass}) cannot exceed Science Total (${scienceTotal})`);
                        $(this).find('.science-pass').addClass('validation-warning');
                    }
                    
                    // Check if at least one student exists
                    if (artsTotal === 0 && scienceTotal === 0) {
                        isValid = false;
                        validationErrors.push(`Class ${getClassName(className)} in ${sessionYear}: At least one student (Arts or Science) is required`);
                    }
                }
            });
        });
        
        if (!hasEntries) {
            e.preventDefault();
            alert('Please add at least one class entry.');
            return false;
        }
        
        if (!isValid) {
            e.preventDefault();
            alert('Please fix the following errors:\n- ' + validationErrors.join('\n- '));
            return false;
        }
        
        // Show loading state
        $('#submitBtn').html('<span class="loading-spinner"></span> Processing...').prop('disabled', true);
    });

    // Real-time validation
    $(document).on('input', '.arts-total, .arts-pass, .science-total, .science-pass', function() {
        validatePassNotExceedTotal($(this));
        calculateAllPercentages($(this).closest('.entry-row'));
    });

    // Number validation
    $(document).on('input', 'input[type="number"]', function() {
        const value = $(this).val();
        if (value && value < 0) {
            $(this).val(0);
        }
        updateSummary();
    });

    // Check for duplicate class in session and update class options
    $(document).on('change', '.class-select select', function() {
        checkDuplicateInSession($(this));
        updateAllClassOptions();
    });
});

// Function to validate pass does not exceed total
function validatePassNotExceedTotal(input) {
    const row = input.closest('.entry-row');
    
    // Arts validation
    const artsTotal = parseInt(row.find('.arts-total').val()) || 0;
    const artsPass = parseInt(row.find('.arts-pass').val()) || 0;
    if (artsPass > artsTotal) {
        row.find('.arts-pass').val(artsTotal);
    }
    
    // Science validation
    const scienceTotal = parseInt(row.find('.science-total').val()) || 0;
    const sciencePass = parseInt(row.find('.science-pass').val()) || 0;
    if (sciencePass > scienceTotal) {
        row.find('.science-pass').val(scienceTotal);
    }
}

// Get class display name
function getClassName(classValue) {
    const classNames = {
        '5': '5th',
        '8': '8th',
        '9': '9th',
        '10': '10th',
        '11': 'First Year',
        '12': 'Second Year'
    };
    return classNames[classValue] || classValue;
}

// Check for duplicate class in same session
function checkDuplicateInSession(selectElement) {
    const sessionContainer = selectElement.closest('.session-container');
    const selectedClass = selectElement.val();
    
    if (!selectedClass) return true;
    
    let hasDuplicate = false;
    sessionContainer.find('.class-select select').each(function() {
        if ($(this).val() === selectedClass && this !== selectElement[0]) {
            hasDuplicate = true;
        }
    });
    
    if (hasDuplicate) {
        alert(`Class ${getClassName(selectedClass)} already exists in this session. Please select a different class.`);
        selectElement.val('');
        return false;
    }
    
    return true;
}

// Update all class options across all sessions
function updateAllClassOptions() {
    // First, get all selected classes per session
    let selectedPerSession = {};
    
    $('.session-container').each(function() {
        const sessionYear = $(this).data('session');
        selectedPerSession[sessionYear] = [];
        
        $(this).find('.class-select select').each(function() {
            const val = $(this).val();
            if (val) {
                selectedPerSession[sessionYear].push(val);
            }
        });
    });
    
    // Now update each select dropdown
    $('.session-container').each(function() {
        const sessionYear = $(this).data('session');
        const sessionSelected = selectedPerSession[sessionYear] || [];
        
        $(this).find('.class-select select').each(function() {
            const currentValue = $(this).val();
            let options = '<option value="">Select Class...</option>';
            
            window.classList.forEach(function(classVal) {
                const isSelected = (currentValue == classVal);
                const isDisabled = (!isSelected && sessionSelected.includes(classVal));
                const displayText = window.classDisplay[classVal];
                const disabledText = isDisabled ? ' (Already Selected)' : '';
                
                options += `<option value="${classVal}" ${isSelected ? 'selected' : ''} ${isDisabled ? 'disabled' : ''}>${displayText}${disabledText}</option>`;
            });
            
            $(this).html(options);
        });
    });
}

// Calculate all percentages for a row
function calculateAllPercentages(row) {
    // Arts calculations
    const artsTotal = parseInt(row.find('.arts-total').val()) || 0;
    const artsPass = parseInt(row.find('.arts-pass').val()) || 0;
    const artsPercent = artsTotal > 0 ? ((artsPass / artsTotal) * 100).toFixed(2) : 0;
    row.find('.arts-percent').val(artsPercent);
    row.find('.arts-fail').val(artsTotal - artsPass);
    
    // Science calculations
    const scienceTotal = parseInt(row.find('.science-total').val()) || 0;
    const sciencePass = parseInt(row.find('.science-pass').val()) || 0;
    const sciencePercent = scienceTotal > 0 ? ((sciencePass / scienceTotal) * 100).toFixed(2) : 0;
    row.find('.science-percent').val(sciencePercent);
    row.find('.science-fail').val(scienceTotal - sciencePass);
    
    // Overall calculations
    const overallTotal = artsTotal + scienceTotal;
    const overallPass = artsPass + sciencePass;
    const overallPercent = overallTotal > 0 ? ((overallPass / overallTotal) * 100).toFixed(2) : 0;
    row.find('.overall-total').val(overallTotal);
    row.find('.overall-pass').val(overallPass);
    row.find('.overall-fail').val(overallTotal - overallPass);
    row.find('.overall-percent').val(overallPercent);
    
    updateSummary();
}

// Update overall summary
function updateSummary() {
    let totalEntries = 0;
    let totalStudents = 0;
    let totalPassed = 0;
    
    $('.entry-row').each(function() {
        const className = $(this).find('.class-select select').val();
        if (className) {
            totalEntries++;
            totalStudents += parseInt($(this).find('.overall-total').val()) || 0;
            totalPassed += parseInt($(this).find('.overall-pass').val()) || 0;
        }
    });
    
    const overallPercent = totalStudents > 0 ? ((totalPassed / totalStudents) * 100).toFixed(2) : 0;
    
    $('#totalEntries').text(totalEntries);
    $('#totalStudents').text(totalStudents);
    $('#totalPassed').text(totalPassed);
    $('#overallPercentage').text(overallPercent + '%');
}

// Add a session
window.addSession = function(sessionYear, entries = []) {
    const sessionId = 'session-' + sessionYear.replace(/-/g, '');
    
    const sessionHtml = `
        <div class="session-container" id="${sessionId}" data-session="${sessionYear}">
            <div class="session-header">
                <span><i class="fas fa-calendar-alt"></i> Session: ${sessionYear}</span>
            </div>
            <div class="session-content">
                <div class="select-hint">
                    <span><i class="fas fa-circle text-green"></i> Selected</span>
                    <span><i class="fas fa-circle text-red"></i> Already Selected (Disabled)</span>
                    <span><i class="fas fa-circle text-gray"></i> Available</span>
                </div>
                <div class="entries-container" id="${sessionId}-entries">
                    <!-- Entries will be added here -->
                </div>
                <button type="button" class="add-btn" onclick="addEntry('${sessionId}', '${sessionYear}')" style="margin-top: 15px;">
                    <i class="fas fa-plus"></i> Add Class to Session
                </button>
            </div>
        </div>
    `;
    
    $('#sessionsContainer').append(sessionHtml);
    
    // Add entries if provided
    if (entries && entries.length > 0) {
        entries.forEach(function(entry) {
            addEntry(sessionId, sessionYear, entry);
        });
    }
};

// Add an entry to a session
window.addEntry = function(sessionId, sessionYear, entryData = null) {
    window.entryCounter++;
    const entryId = 'entry-' + window.entryCounter;
    const sessionContainer = $('#' + sessionId);
    const entriesContainer = $('#' + sessionId + '-entries');
    
    // Get used classes in this session
    const usedClasses = [];
    entriesContainer.find('.class-select select').each(function() {
        const val = $(this).val();
        if (val) usedClasses.push(val);
    });
    
    // Set values from entryData if provided
    const classNameValue = entryData ? entryData.class_name : '';
    const artsTotal = entryData ? entryData.arts_students : 0;
    const scienceTotal = entryData ? entryData.science_students : 0;
    
    // For pass values, we need to handle the separate pass fields
    // This assumes your database has separate columns for arts_pass and science_pass
    const artsPass = entryData ? (entryData.arts_pass || 0) : 0;
    const sciencePass = entryData ? (entryData.science_pass || 0) : 0;
    
    const entryHtml = `
        <div class="entry-row" id="${entryId}">
            <div class="entries-grid">
                <!-- Class Selection -->
                <div class="class-select">
                    <div class="category-box">
                        <h5>Class</h5>
                        <select name="class_name[${sessionYear}][]" class="form-control" required>
                            <option value="">Select Class...</option>
                            ${generateClassOptions(classNameValue, usedClasses)}
                        </select>
                    </div>
                </div>
                
                <!-- Arts Section -->
                <div class="arts-section">
                    <div class="category-box">
                        <h5>Arts Students</h5>
                        <div class="input-group">
                            <label>Total Students</label>
                            <input type="number" name="arts_total[${sessionYear}][]" class="arts-total" min="0" value="${artsTotal}" required>
                        </div>
                        <div class="input-group">
                            <label>Pass Students</label>
                            <input type="number" name="arts_pass[${sessionYear}][]" class="arts-pass" min="0" value="${artsPass}" required>
                        </div>
                        <div class="input-group">
                            <label>Fail Students</label>
                            <input type="number" name="arts_fail[${sessionYear}][]" class="arts-fail" readonly>
                        </div>
                        <div class="percentage-display">
                            <span>Pass %</span>
                            <input type="number" name="arts_percent[${sessionYear}][]" class="arts-percent" readonly>
                        </div>
                    </div>
                </div>
                
                <!-- Science Section -->
                <div class="science-section">
                    <div class="category-box">
                        <h5>Science Students</h5>
                        <div class="input-group">
                            <label>Total Students</label>
                            <input type="number" name="science_total[${sessionYear}][]" class="science-total" min="0" value="${scienceTotal}" required>
                        </div>
                        <div class="input-group">
                            <label>Pass Students</label>
                            <input type="number" name="science_pass[${sessionYear}][]" class="science-pass" min="0" value="${sciencePass}" required>
                        </div>
                        <div class="input-group">
                            <label>Fail Students</label>
                            <input type="number" name="science_fail[${sessionYear}][]" class="science-fail" readonly>
                        </div>
                        <div class="percentage-display">
                            <span>Pass %</span>
                            <input type="number" name="science_percent[${sessionYear}][]" class="science-percent" readonly>
                        </div>
                    </div>
                </div>
                
                <!-- Overall Section -->
                <div class="overall-section">
                    <div class="category-box">
                        <h5>Overall</h5>
                        <div class="input-group">
                            <label>Total Students</label>
                            <input type="number" name="overall_total[${sessionYear}][]" class="overall-total" readonly>
                        </div>
                        <div class="input-group">
                            <label>Pass Students</label>
                            <input type="number" name="overall_pass[${sessionYear}][]" class="overall-pass" readonly>
                        </div>
                        <div class="input-group">
                            <label>Fail Students</label>
                            <input type="number" name="overall_fail[${sessionYear}][]" class="overall-fail" readonly>
                        </div>
                        <div class="percentage-display">
                            <span>Pass %</span>
                            <input type="number" name="overall_percent[${sessionYear}][]" class="overall-percent" readonly>
                        </div>
                    </div>
                </div>
                
                <!-- Actions -->
                <div class="actions-section">
                    <div class="category-box" style="height: 100%; display: flex; align-items: center; justify-content: center;">
                        <button type="button" class="remove-btn" onclick="removeEntry('${entryId}')">
                            <i class="fas fa-trash"></i> Remove
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    entriesContainer.append(entryHtml);
    
    // Calculate percentages if we have data
    if (entryData) {
        calculateAllPercentages($('#' + entryId));
    }
    
    updateSummary();
    updateAllClassOptions();
};

// Generate class options with disabled ones and "Already Selected" text
function generateClassOptions(selectedValue, usedClasses) {
    let options = '<option value="">Select Class...</option>';
    
    window.classList.forEach(function(classVal) {
        const isSelected = (selectedValue == classVal);
        const isDisabled = (!isSelected && usedClasses.includes(classVal));
        const displayText = window.classDisplay[classVal];
        const disabledText = isDisabled ? ' (Already Selected)' : '';
        
        options += `<option value="${classVal}" ${isSelected ? 'selected' : ''} ${isDisabled ? 'disabled' : ''}>${displayText}${disabledText}</option>`;
    });
    
    return options;
}

// Remove an entry
window.removeEntry = function(entryId) {
    const entry = $('#' + entryId);
    const sessionContainer = entry.closest('.session-container');
    
    if (sessionContainer.find('.entry-row').length <= 1) {
        if (!confirm('This is the last entry in this session. Removing it will leave the session empty. Continue?')) {
            return;
        }
    }
    
    entry.remove();
    updateSummary();
    updateAllClassOptions();

};

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