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

<?php
// ============================================================================
// FILE: school_step8.php
// STEP: 8 of 10 - School Budget Registration
// ============================================================================
// 1. SESSION & SECURITY
// 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';

// 2. FINANCIAL YEAR CALCULATION (July-based Academic Year)
$current_date = new DateTime();
$current_year = (int)$current_date->format('Y');
$july_first = new DateTime("$current_year-07-01");
if ($current_date >= $july_first) {
    $financial_year_start = $current_year;
    $financial_year_end = $current_year + 1;
} else {
    $financial_year_start = $current_year - 1;
    $financial_year_end = $current_year;
}
$financial_year_display = "$financial_year_start - $financial_year_end";

// 3. INITIALIZATION
$success_message = '';
$error_message = '';
$form_data = [];
$student_counts = ['primary' => 0, 'middle' => 0, 'high' => 0, 'higher_secondary' => 0];


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

// Handle session 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'])) {
    $form_data = $_SESSION['form_data'];
    unset($_SESSION['form_data']);
}

// 4. FUNCTION: Fetch Existing Budget Data (Schema-compliant)
function getExistingBudgetData($conn, $emis_code, $fy_start, $fy_end) {
    $budget_data = [];
    // Fetch main budget record
    $main_query = "SELECT * FROM school_budget
    WHERE emis_code = ?
    AND financial_year_start = ?
    AND financial_year_end = ?";
    $stmt = $conn->prepare($main_query);
    $stmt->bind_param("sii", $emis_code, $fy_start, $fy_end);
    $stmt->execute();
    $main_result = $stmt->get_result();
    if ($main_result->num_rows > 0) {
        $main_row = $main_result->fetch_assoc();
        $budget_id = $main_row['id'];
        // Map main fields
        $budget_data['govt_budget'] = $main_row['govt_budget'];
        $budget_data['budget_expenses'] = $main_row['budget_expenses'];
        $budget_data['previous_balance'] = $main_row['previous_balance'];
        $budget_data['donations'] = $main_row['donations'];
        $budget_data['fee_expenses'] = $main_row['fee_expenses'];
        $budget_data['submitted_govt'] = $main_row['submitted_govt'];
        $budget_data['cash_in_hand'] = $main_row['cash_in_hand'];
        $budget_data['cash_in_bank'] = $main_row['cash_in_bank'];
        $budget_data['primary_students'] = $main_row['primary_students'];
        $budget_data['middle_students'] = $main_row['middle_students'];
        $budget_data['high_students'] = $main_row['high_students'];
        $budget_data['higher_secondary_students'] = $main_row['higher_secondary_students'];
        $budget_data['total_school_funds'] = $main_row['total_school_funds'];
        // Fetch fund details from school_budget_funds
        $funds_query = "SELECT * FROM school_budget_funds
        WHERE budget_id = ?
        AND financial_year_start = ?
        AND financial_year_end = ?";
        $stmt = $conn->prepare($funds_query);
        $stmt->bind_param("iii", $budget_id, $fy_start, $fy_end);
        $stmt->execute();
        $funds_result = $stmt->get_result();
        while ($fund_row = $funds_result->fetch_assoc()) {
            $fund_id = $fund_row['fund_id'];
            $budget_data[$fund_id . '_frequency'] = $fund_row['fund_frequency'];
            $budget_data[$fund_id . '_primary'] = $fund_row['primary_amount'];
            $budget_data[$fund_id . '_middle'] = $fund_row['middle_amount'];
            $budget_data[$fund_id . '_high'] = $fund_row['high_amount'];
            $budget_data[$fund_id . '_higher_sec'] = $fund_row['higher_sec_amount'];
        }
    }
    return $budget_data;
}

// 5. FETCH STUDENT COUNTS FROM STEP 6
$section_classes = [
    'primary'          => [1,2,3,4,5,6,7,8,9],
    'middle'           => [10,11,12],
    'high'             => [13,14],
    'higher_secondary' => [15,16]
];
try {
    if (!empty($emis_code)) {
        $school_query = "SELECT id FROM school_students WHERE emis_code = ?";
        $stmt = $conn->prepare($school_query);
        $stmt->bind_param("s", $emis_code);
        $stmt->execute();
        $school_result = $stmt->get_result();
        if ($school_result->num_rows > 0) {
            $school_row = $school_result->fetch_assoc();
            $school_students_id = $school_row['id'];
            $summary_query = "SELECT sss.class_id, c.class_name, sss.total_male, sss.total_female,
            (sss.total_male + sss.total_female) as total_students
            FROM school_students_summary sss
            JOIN class c ON sss.class_id = c.class_id
            WHERE sss.ss_id = ?";
            $stmt = $conn->prepare($summary_query);
            $stmt->bind_param("i", $school_students_id);
            $stmt->execute();
            $summary_result = $stmt->get_result();
            $section_totals = ['primary'=>0,'middle'=>0,'high'=>0,'higher_secondary'=>0];
            while ($row = $summary_result->fetch_assoc()) {
                $class_id = $row['class_id'];
                $total = $row['total_students'];
                if (in_array($class_id, $section_classes['primary'])) $section_totals['primary'] += $total;
                elseif (in_array($class_id, $section_classes['middle'])) $section_totals['middle'] += $total;
                elseif (in_array($class_id, $section_classes['high'])) $section_totals['high'] += $total;
                elseif (in_array($class_id, $section_classes['higher_secondary'])) $section_totals['higher_secondary'] += $total;
            }
            $student_counts = $section_totals;
        }
    }
} catch (Exception $e) {
    error_log("Error fetching student counts: " . $e->getMessage());
}
$no_student_data = (array_sum($student_counts) == 0);

// Fetch existing budget data if available
if (!empty($emis_code)) {
    $existing_budget = getExistingBudgetData($conn, $emis_code, $financial_year_start, $financial_year_end);
    if (!empty($existing_budget)) {
        $form_data = array_merge($form_data, $existing_budget);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>School Budget Registration - Step 8 of 10</title>
<!-- External Libraries -->
<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">
<!-- ========================================================================
CSS STYLES - ORGANIZED BY SECTION
======================================================================== -->
<style>
/* GLOBAL RESET & BASE */
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f5f7fa; color: #333; line-height: 1.6; }
.container { max-width: 1200px; margin: 0 auto; padding: 20px; }
/* HEADER & PROGRESS BAR */
.header { text-align: center; margin-bottom: 30px; padding: 25px; background: linear-gradient(135deg, #2c3e50, #4a6491); color: #fff; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,.1); }
.header h1 { font-size: 28px; margin-bottom: 10px; }
.header p { opacity: .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: #e0e0e0; transform: translateY(-50%); z-index: 1; }
.progress-bar { position: absolute; top: 50%; left: 0; height: 4px; background: #f39c12; transform: translateY(-50%); z-index: 2; transition: width .3s ease; width: 80%; }
.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: #e0e0e0; color: #666; display: flex; align-items: center; justify-content: center; font-weight: 700; margin-bottom: 8px; border: 3px solid #fff; transition: all .3s ease; }
.step.completed span:first-child { background: #2ecc71; color: #fff; }
.step.active span:first-child { background: #f39c12; color: #fff; 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: #f39c12; font-weight: 600; }
/* FORM CONTAINER & GRID */
.form-container { background: #fff; border-radius: 10px; border-left: 4px solid #f39c12; padding: 30px; box-shadow: 0 5px 20px rgba(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; }
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 .3s ease; background: #fff; width: 100%; }
input[type="text"]:focus, input[type="email"]:focus, input[type="number"]:focus, select:focus, textarea:focus { outline: none; border-color: #f39c12; box-shadow: 0 0 0 3px rgba(243,156,18,.1); }
input[readonly] { background: #f8f9fa; border-color: #ddd; color: #666; font-weight: 600; }
.required::after { content: " *"; color: #e74c3c; }
.helper-text { font-size: 12px; color: #7f8c8d; margin-top: 5px; }
/* ALERTS & MESSAGES */
.alert { padding: 15px; border-radius: 6px; margin-bottom: 20px; text-align: center; font-weight: 500; }
.alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
.warning-message { background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin-bottom: 20px; border-radius: 4px; color: #856404; }
.warning-message i { color: #ffc107; margin-right: 10px; }
.balance-error { animation: shake .5s ease-in-out; margin-top: 20px; }
@keyframes shake { 0%, 100% { transform: translateX(0); } 10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); } 20%, 40%, 60%, 80% { transform: translateX(10px); } }
/* SECTIONS & TITLES */
.section-title { font-size: 18px; color: #2c3e50; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 2px solid #f39c12; display: flex; align-items: center; gap: 10px; }
.section-title i { color: #f39c12; }
.school-info { background: #f8f9fa; padding: 15px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #f39c12; }
.financial-year { background: #2c3e50; color: #fff; padding: 15px; border-radius: 6px; text-align: center; margin-bottom: 20px; font-weight: 600; font-size: 18px; box-shadow: 0 4px 10px rgba(0,0,0,.1); }
.financial-year small { display: block; font-size: 12px; opacity: .8; margin-top: 5px; color: #f39c12; }
.cash-position-section { background: #e8f4fc; padding: 20px; border-radius: 8px; margin: 20px 0; border-left: 4px solid #3498db; }
/* BUDGET SECTIONS & TABLES */
.budget-wrapper { display: grid; grid-template-columns: 1fr; gap: 20px; margin-bottom: 30px; }
.budget-section { background: #fff; border-radius: 10px; padding: 25px; border-left: 4px solid; box-shadow: 0 4px 15px rgba(0,0,0,.05); margin-bottom: 20px; }
.budget-section.govt { border-left-color: #3498db; }
.budget-section.school { border-left-color: #27ae60; }
.table-responsive { overflow-x: auto; margin: 20px 0; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,.05); }
.funds-matrix-table { width: 100%; border-collapse: collapse; background: #fff; font-size: 14px; min-width: 800px; border: 1px solid #27ae60; }
.funds-matrix-table th { background: linear-gradient(135deg, #2c3e50, #4a6491); color: #fff; padding: 15px 10px; font-weight: 600; text-align: center; }
.funds-matrix-table td { padding: 12px 8px; border-bottom: 1px solid #e0e0e0; vertical-align: middle; }
.funds-matrix-table tbody tr:hover { background: #f8f9fa; }
/* Highlight required fund rows */
.funds-matrix-table tbody tr[data-fund-required="true"] { background: #fffdf5; }
.funds-matrix-table tbody tr[data-fund-required="true"].error-row { background: #ffebee; border: 2px solid #e74c3c; }
.funds-matrix-table tbody tr[data-fund-required="true"]:hover { background: #fff3cd; }
.fund-label { font-weight: 600; color: #2c3e50; min-width: 200px; }
.fund-frequency { margin-top: 5px; }
.frequency-select-small { width: 100%; padding: 5px 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 12px; background: #fff; }
.fund-input { width: 120px; padding: 8px 10px 8px 30px !important; border: 1px solid #ddd; border-radius: 4px; font-size: 13px; }
.fund-total { font-weight: 700; color: #27ae60; text-align: right; padding-right: 15px !important; }
.section-totals-row th { background: linear-gradient(135deg, #f39c12, #e67e22); color: #fff; padding: 12px 10px; }
.input-with-icon { position: relative; }
.currency-symbol { position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: #666; font-weight: 600; z-index: 2; }
.currency-input { padding-left: 45px !important; }
/* STUDENT COUNTS SECTION */
.student-counts-grid { margin-bottom: 30px; padding: 25px; background: linear-gradient(135deg, #f8f9fa, #fff); border-radius: 12px; border: 1px solid #27ae60; box-shadow: 0 4px 15px rgba(39,174,96,.1); }
.student-counts-grid h4 { margin-bottom: 15px; color: #2c3e50; display: flex; align-items: center; gap: 10px; font-size: 18px; }
.info-message { background: #e8f4fc; border-left: 4px solid #3498db; padding: 12px 18px; margin-bottom: 25px; border-radius: 6px; font-size: 14px; color: #2c3e50; display: flex; align-items: center; gap: 10px; }
.info-message i { color: #3498db; font-size: 18px; }
.student-counts-grid .form-group { transition: all .3s ease; background: #fff; padding: 15px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.05); border-left: 4px solid #27ae60; }
.student-counts-grid .form-group:hover { transform: translateY(-2px); box-shadow: 0 6px 15px rgba(39,174,96,.15); }
/* TOTALS & SUMMARY */
.totals-summary { margin-top: 20px; display: flex; justify-content: flex-end; }
.summary-card { background: linear-gradient(135deg, #27ae60, #2ecc71); padding: 20px 30px; border-radius: 8px; color: #fff; min-width: 300px; }
.summary-card h4 { margin: 0 0 10px 0; font-size: 16px; opacity: .9; }
.total-amount-large { font-size: 32px; font-weight: 700; }
.result-box { background: #f8f9fa; padding: 15px; border-radius: 8px; margin-top: 20px; border-left: 3px solid; }
.result-box.govt { border-left-color: #3498db; }
.result-box.school { border-left-color: #27ae60; }
.result-value { font-size: 24px; font-weight: 700; margin-top: 10px; }
.result-value.positive { color: #27ae60; }
.result-value.negative { color: #e74c3c; }
.summary-section { background: linear-gradient(135deg, #f8f9fa, #fff); border-radius: 10px; padding: 25px; margin-top: 30px; border: 2px solid #f39c12; }
.summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-top: 20px; }
.summary-item { background: #fff; padding: 20px; border-radius: 8px; text-align: center; box-shadow: 0 4px 10px rgba(0,0,0,.05); border-top: 3px solid #f39c12; }
/* BUTTONS & NAVIGATION */
.navigation-buttons { display: flex; justify-content: space-between; margin-top: 40px; padding-top: 20px; border-top: 1px solid #eee; }
.nav-btn { padding: 12px 30px; background: linear-gradient(135deg, #f39c12, #e67e22); color: #fff; border: none; border-radius: 6px; font-size: 16px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 10px; transition: all .3s ease; }
.nav-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 15px rgba(243,156,18,.3); }
.nav-btn.back { background: linear-gradient(135deg, #7f8c8d, #95a5a6); }
.nav-btn:disabled { background: #95a5a6; cursor: not-allowed; opacity: .7; }
.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; }
@keyframes spin { to { transform: rotate(360deg); } }
/* BADGES & UTILITIES */
.fy-badge { display: inline-block; background: #f39c12; color: #2c3e50; padding: 5px 15px; border-radius: 50px; font-weight: 700; margin-left: 15px; font-size: 14px; }
/* RESPONSIVE DESIGN */
@media (max-width: 992px) { .budget-wrapper { grid-template-columns: 1fr; } }
@media (max-width: 768px) {
.form-grid, .summary-grid { grid-template-columns: 1fr; }
.student-counts-grid [style*="grid-template-columns: repeat(2, 1fr)"] { grid-template-columns: 1fr !important; }
.step { width: 60px; }
.step-label { font-size: 10px; }
.fund-input { width: 100px; }
}
@media (max-width: 480px) {
.container { padding: 10px; }
.form-container { padding: 15px; }
.header { padding: 15px; }
.nav-btn { padding: 10px 15px; font-size: 14px; }
}
</style>
</head>
<body>
<?php include 'floating_logout_school.php'; ?>
<div class="container">
<!-- Header -->
<div class="header">
<h1><i class="fas fa-chart-pie"></i> School Budget Registration - Step 8 of 10</h1>
<p>Complete all 10 steps to register a new school in Districts Schools Management System</p>
</div>
<!-- Progress Bar -->
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
<?php
$labels = ['Profile','Land','Building','Facilities','Posts','Students','Results','Budget','SMC','Location'];
for($i=1; $i<=10; $i++):
?>
<div class="step <?php echo $i<8?'completed':($i==8?'active':''); ?>" id="step<?php echo $i; ?>">
<span><?php echo $i; ?></span>
<span class="step-label"><?php echo $labels[$i-1]; ?></span>
</div>
<?php endfor; ?>
</div>
<!-- Messages -->
<?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; ?>
<?php if($no_student_data): ?>
<div class="warning-message">
<i class="fas fa-exclamation-triangle"></i>
<strong>No student data found.</strong> Please complete Step 6 first.
</div>
<?php endif; ?>
<!-- Main Form Container -->
<div class="form-container">
<div class="school-info">
<h3><i class="fas fa-info-circle"></i> Financial Information</h3>
<p>Fill in all financial details for <strong><?php echo htmlspecialchars($school_name); ?></strong>
(EMIS: <strong><?php echo htmlspecialchars($emis_code); ?></strong>).
All amounts in Pakistani Rupees (Rs.). Fields marked with <span style="color:#e74c3c">*</span> are compulsory.</p>
</div>
<div class="financial-year">
<i class="fas fa-calendar-alt"></i> Financial Year: <?php echo $financial_year_display; ?>
<small><i class="fas fa-clock"></i> Based on system date: <?php echo date('d-m-Y'); ?>
(<?php echo ($current_date>=$july_first)?'Second Half':'First Half'; ?> of year)</small>
</div>
<form method="POST" action="school_step8_save.php" id="budgetForm">
<!-- Hidden Financial Year Fields -->
<input type="hidden" name="financial_year_start" value="<?php echo $financial_year_start; ?>">
<input type="hidden" name="financial_year_end" value="<?php echo $financial_year_end; ?>">
<input type="hidden" name="financial_year_display" value="<?php echo $financial_year_display; ?>">
<input type="hidden" name="financial_year_calculated_on" value="<?php echo date('Y-m-d H:i:s'); ?>">
<!-- SECTION 1: Government Budget -->
<div class="budget-wrapper">
<div class="budget-section govt">
<h3 class="section-title">
<i class="fas fa-university"></i> Government Budget
<span class="fy-badge">FY <?php echo $financial_year_display; ?></span>
</h3>
<div class="form-grid">
<div class="form-group">
<label for="govt_budget" class="required">Budget Allocated</label>
<div class="input-with-icon">
<span class="currency-symbol">Rs.</span>
<input type="number" id="govt_budget" name="govt_budget" class="currency-input"
min="0" required
value="<?php echo htmlspecialchars($form_data['govt_budget']??''); ?>"
placeholder="Enter amount" onchange="calculateGovtBalance()" onkeyup="calculateGovtBalance()">
</div>
</div>
<div class="form-group">
<label for="budget_expenses" class="required">Expenses</label>
<div class="input-with-icon">
<span class="currency-symbol">Rs.</span>
<input type="number" id="budget_expenses" name="budget_expenses" class="currency-input"
min="0" required
value="<?php echo htmlspecialchars($form_data['budget_expenses']??''); ?>"
placeholder="Enter expenses" onchange="calculateGovtBalance()" onkeyup="calculateGovtBalance()">
</div>
</div>
</div>
<div class="result-box govt">
<h4><i class="fas fa-calculator"></i> Government Balance (as on 30-06-<?php echo $financial_year_end; ?>)</h4>
<div class="result-value" id="govtBalanceDisplay">Rs. 0</div>
<div class="helper-text">Budget Allocated - Expenses</div>
</div>
</div>
</div>
<!-- SECTION 2: School Funds Matrix (Student Counts at TOP) -->
<div class="budget-section school">
<h3 class="section-title">
<i class="fas fa-table"></i> School Funds Collection Matrix
<span class="fy-badge">FY <?php echo $financial_year_display; ?></span>
</h3>
<p class="section-description">Enter amount collected per student for each fund across sections. <span style="color:#e74c3c; font-weight:600;">Rows marked with * require at least one value greater than 0.</span></p>
<!-- Student Counts (MOVED TO TOP) -->
<div class="student-counts-grid">
<h4><i class="fas fa-users"></i> Student Counts by Section (from Step 6)</h4>
<div class="info-message">
<i class="fas fa-database"></i> Read-only counts loaded from Step 6, used for calculations.
</div>
<div style="display:grid; grid-template-columns:repeat(2,1fr); gap:20px">
<?php
$sections = [
['id'=>'primary', 'label'=>'Primary (ECE-5)', 'icon'=>'fa-child'],
['id'=>'middle', 'label'=>'Middle (6-8)', 'icon'=>'fa-user-graduate'],
['id'=>'high', 'label'=>'High (9-10)', 'icon'=>'fa-school'],
['id'=>'higher_secondary', 'label'=>'Higher Secondary (11-12)', 'icon'=>'fa-university']
];
foreach($sections as $sec):
$count = $student_counts[$sec['id']] ?? 0;
$field_name = $sec['id'].'_students';
$saved = $form_data[$field_name] ?? $count;
?>
<div class="form-group">
<label for="<?php echo $field_name; ?>" style="display:flex; align-items:center; gap:8px; margin-bottom:12px">
<i class="fas <?php echo $sec['icon']; ?>" style="color:#27ae60"></i>
<span><?php echo $sec['label']; ?></span>
</label>
<div style="display:flex; align-items:center; gap:10px">
<div style="flex:1; position:relative">
<span style="position:absolute; left:12px; top:50%; transform:translateY(-50%); color:#27ae60">👥</span>
<input type="number" id="<?php echo $field_name; ?>" name="<?php echo $field_name; ?>"
style="width:100%; padding:12px 15px 12px 40px; border:2px solid #27ae60; border-radius:8px; font-size:16px; font-weight:700; color:#27ae60; background:#f0f9f0"
value="<?php echo $saved; ?>" readonly>
</div>
<div style="min-width:100px; text-align:right">
<div style="font-size:20px; font-weight:700; color:#27ae60"><?php echo number_format($saved); ?></div>
<div style="font-size:12px; color:#666">Students</div>
</div>
</div>
<?php if($saved==0): ?>
<div style="margin-top:8px; padding:6px; background:#fff3cd; border-radius:4px; font-size:12px; color:#856404">
<i class="fas fa-exclamation-triangle"></i> No data - complete Step 6
</div>
<?php else: ?>
<div style="margin-top:8px; display:flex; gap:10px; font-size:11px; color:#666">
<span><i class="fas fa-check-circle" style="color:#27ae60"></i> Loaded from Step 6</span>
</div>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<div style="margin-top:20px; padding:15px; background:linear-gradient(135deg,#2c3e50,#4a6491); border-radius:8px; color:#fff; display:flex; justify-content:space-between; align-items:center">
<div style="display:flex; align-items:center; gap:15px">
<i class="fas fa-chart-pie" style="font-size:24px"></i>
<div>
<div style="font-size:14px; opacity:.9">Total Students</div>
<div style="font-size:28px; font-weight:700"><?php echo number_format(array_sum($student_counts)); ?></div>
</div>
</div>
<div style="text-align:right">
<div style="font-size:13px; opacity:.9">Financial Year</div>
<div style="font-size:18px; font-weight:600; background:#f39c12; color:#2c3e50; padding:5px 15px; border-radius:50px">
<?php echo $financial_year_display; ?>
</div>
</div>
</div>
</div>
<!-- Funds Collection Table -->
<div class="table-responsive">
<table class="funds-matrix-table">
<thead>
<tr>
<th>Fund Name</th>
<th>Primary</th>
<th>Middle</th>
<th>High</th>
<th>Higher Sec</th>
<th>Fund Total</th>
</tr>
</thead>
<tbody>
<?php
$funds = [
['id' => 'tuition', 'label' => 'Tuition Fund', 'icon' => 'fa-graduation-cap'],
['id' => 'development', 'label' => 'Development Fund', 'icon' => 'fa-building'],
['id' => 'building', 'label' => 'Building Fund', 'icon' => 'fa-house'],
['id' => 'admission', 'label' => 'Admission Fund', 'icon' => 'fa-user-plus'],
['id' => 'absentee', 'label' => 'Absentee Fine', 'icon' => 'fa-user-slash'],
['id' => 'scout', 'label' => 'Scout/Girl Guide', 'icon' => 'fa-flag'],
['id' => 'computer', 'label' => 'Computer Fund', 'icon' => 'fa-laptop'],
['id' => 'library', 'label' => 'Library Fund', 'icon' => 'fa-book'],
['id' => 'furniture', 'label' => 'Furniture Fund', 'icon' => 'fa-chair'],
['id' => 'annual', 'label' => 'Annual Fund', 'icon' => 'fa-calendar-alt'],
['id' => 'sports', 'label' => 'Sports Fund', 'icon' => 'fa-futbol'],
['id' => 'laboratory', 'label' => 'Laboratory Fund(Sci/Tech)', 'icon' => 'fa-flask'],
['id' => 'medical', 'label' => 'Medical Fund', 'icon' => 'fa-hospital'],
['id' => 'mosque', 'label' => 'Mosque Fund', 'icon' => 'fa-mosque'],
['id' => 'other', 'label' => 'Other Fund', 'icon' => 'fa-ellipsis-h']
];
// Funds that require at least 1 value > 0 out of 4 sections
$required_fund_ids = ['tuition', 'development', 'building', 'admission', 'annual'];

foreach($funds as $fund):
$freq_val = $form_data[$fund['id'].'_frequency'] ?? 'annual';
$is_required = in_array($fund['id'], $required_fund_ids);
$row_attrs = 'class="fund-row"';
if ($is_required) {
    $row_attrs .= ' data-fund-required="true"';
}
?>
<tr <?php echo $row_attrs; ?>>
<td class="fund-label">
<i class="fas <?php echo $fund['icon']; ?>"></i> <?php echo $fund['label']; ?>
<?php if($is_required): ?>
<span style="color:#e74c3c; font-size:12px; margin-left:5px;">*</span>
<?php endif; ?>
<div class="fund-frequency">
<select class="frequency-select-small"
id="<?php echo $fund['id']; ?>_frequency"
name="<?php echo $fund['id']; ?>_frequency"
onchange="calculateFundTotals()">
<option value="monthly" <?php echo $freq_val == 'monthly' ? 'selected' : ''; ?>>Monthly</option>
<option value="annual" <?php echo $freq_val == 'annual' ? 'selected' : ''; ?>>Annual</option>
</select>
</div>
</td>
<?php foreach(['primary','middle','high','higher_sec'] as $section):
$fn = $fund['id'].'_'.$section;
$fv = $form_data[$fn] ?? '';
?>
<td>
<div class="input-with-icon">
<span class="currency-symbol">Rs.</span>
<input type="number"
id="<?php echo $fn; ?>"
name="<?php echo $fn; ?>"
class="fund-input"
min="0" step="1"
value="<?php echo htmlspecialchars($fv); ?>"
onchange="calculateFundTotals()"
onkeyup="calculateFundTotals()"
placeholder="Amount">
</div>
</td>
<?php endforeach; ?>
<td class="fund-total" id="<?php echo $fund['id']; ?>_total">Rs. 0</td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr class="section-totals-row">
<th>Section Totals</th>
<th id="primary_section_total">Rs. 0</th>
<th id="middle_section_total">Rs. 0</th>
<th id="high_section_total">Rs. 0</th>
<th id="higher_sec_section_total">Rs. 0</th>
<th id="grand_total">Rs. 0</th>
</tr>
</tfoot>
</table>
</div>
<!-- Total Collections Summary -->
<div class="totals-summary">
<div class="summary-card">
<h4>Total School Funds (FY <?php echo $financial_year_display; ?>)</h4>
<div class="total-amount-large" id="total_school_funds">Rs. 0</div>
<input type="hidden" id="total_school_funds_input" name="total_school_funds" value="0">
</div>
</div>
</div>
<!-- SECTION 3: School Income & Expenses -->
<div class="budget-section school">
<h3 class="section-title">
<i class="fas fa-money-bill-wave"></i> School Income & Expenses
<span class="fy-badge">FY <?php echo $financial_year_display; ?></span>
</h3>
<div class="form-grid">
<div class="form-group">
<label for="previous_balance">Previous Balance (as on 30-06-<?php echo $financial_year_start; ?>)</label>
<div class="input-with-icon">
<span class="currency-symbol">Rs.</span>
<input type="number" id="previous_balance" name="previous_balance" class="currency-input"
min="0" value="<?php echo htmlspecialchars($form_data['previous_balance']??''); ?>"
placeholder="Carry forward" onchange="calculateAll()" onkeyup="calculateAll()">
</div>
</div>
<div class="form-group">
<label for="donations">Donations</label>
<div class="input-with-icon">
<span class="currency-symbol">Rs.</span>
<input type="number" id="donations" name="donations" class="currency-input"
min="0" value="<?php echo htmlspecialchars($form_data['donations']??''); ?>"
placeholder="Enter donations" onchange="calculateAll()" onkeyup="calculateAll()">
</div>
</div>
<div class="form-group">
<label for="fee_collected" class="required">Total Fee/Fund Collected</label>
<div class="input-with-icon">
<span class="currency-symbol">Rs.</span>
<input type="number" id="fee_collected" name="fee_collected" class="currency-input"
readonly placeholder="Auto-calculated from School Funds">
</div>
<div class="helper-text">Sum of all fund collections × student counts</div>
</div>
<div class="form-group">
<label for="fee_expenses" class="required">School Expenses</label>
<div class="input-with-icon">
<span class="currency-symbol">Rs.</span>
<input type="number" id="fee_expenses" name="fee_expenses" class="currency-input"
min="0" required
value="<?php echo htmlspecialchars($form_data['fee_expenses']??''); ?>"
placeholder="Enter expenses" onchange="calculateAll()" onkeyup="calculateAll()">
</div>
</div>
<div class="form-group">
<label for="submitted_govt" class="required">Submitted to Government</label>
<div class="input-with-icon">
<span class="currency-symbol">Rs.</span>
<input type="number" id="submitted_govt" name="submitted_govt" class="currency-input"
min="0" readonly
placeholder="Auto-calculated: Tuition + Annual + Admission + Absentee">
</div>
<div class="helper-text">Auto-sum of Tuition, Annual, Admission & Absentee funds</div>
</div>
</div>
<div class="result-box school">
<h4><i class="fas fa-calculator"></i> School Net Balance (as on 30-06-<?php echo $financial_year_end; ?>)</h4>
<div class="result-value" id="schoolBalanceDisplay">Rs. 0</div>
<div class="helper-text">(Prev Balance + Income + Donations) - Expenses - Submitted</div>
</div>
</div>
<!-- SECTION 4: Cash Position -->
<div class="cash-position-section">
<h3 class="section-title">
<i class="fas fa-wallet"></i> Cash Position (as on <?php echo date('d-m-Y'); ?>)
</h3>
<div class="form-grid">
<div class="form-group">
<label for="cash_in_hand" class="required">Cash in Hand</label>
<div class="input-with-icon">
<span class="currency-symbol">Rs.</span>
<input type="number" id="cash_in_hand" name="cash_in_hand" class="currency-input"
min="0"
value="<?php echo htmlspecialchars($form_data['cash_in_hand']??''); ?>"
placeholder="Physical cash" onchange="calculateAll()" onkeyup="calculateAll()">
</div>
</div>
<div class="form-group">
<label for="cash_in_bank" class="required">Cash in Bank</label>
<div class="input-with-icon">
<span class="currency-symbol">Rs.</span>
<input type="number" id="cash_in_bank" name="cash_in_bank" class="currency-input"
min="0"
value="<?php echo htmlspecialchars($form_data['cash_in_bank']??''); ?>"
placeholder="Bank balance" onchange="calculateAll()" onkeyup="calculateAll()">
</div>
</div>
<div class="form-group">
<label class="required">Total Cash Available</label>
<div class="input-with-icon">
<span class="currency-symbol">Rs.</span>
<input type="text" id="total_cash" readonly class="currency-input" placeholder="Auto-calculated">
</div>
<div class="helper-text">Must be greater than 0 (Hand or Bank)</div>
</div>
</div>
</div>
<!-- SECTION 5: Financial Summary -->
<div class="summary-section">
<h3 class="section-title">
<i class="fas fa-chart-line"></i> Financial Summary (FY <?php echo $financial_year_display; ?>)
</h3>
<div class="summary-grid">
<div class="summary-item budget">
<h4><i class="fas fa-university"></i> Total Available Funds</h4>
<div class="value" id="totalFundsDisplay">Rs. 0</div>
<div class="label">As on 30-06-<?php echo $financial_year_end; ?></div>
</div>
<div class="summary-item cash">
<h4><i class="fas fa-money-bill-alt"></i> Cash Position</h4>
<div class="value" id="cashPositionDisplay">Rs. 0</div>
<div class="label">As on <?php echo date('d-m-Y'); ?></div>
</div>
<div class="summary-item balance">
<h4><i class="fas fa-balance-scale"></i> Current Balance</h4>
<div class="value" id="currentBalanceDisplay">Rs. 0</div>
<div class="label">Net School Balance</div>
</div>
<div class="summary-item utilization">
<h4><i class="fas fa-percentage"></i> Fund Utilization</h4>
<div class="value" id="utilizationDisplay">0%</div>
<div class="label">Expenses vs Budget</div>
</div>
</div>
</div>
<!-- Navigation Buttons -->
<div class="navigation-buttons">
<button type="button" class="nav-btn back" onclick="window.location.href='school_step7.php'">
<i class="fas fa-arrow-left"></i> Back
</button>
<button type="submit" class="nav-btn" id="submitBtn" name="school_budget_submit">
<i class="fas fa-save"></i> Save & Continue
</button>
</div>
</form>
</div>
</div>
<!-- ========================================================================
JAVASCRIPT - CONSOLIDATED & OPTIMIZED
======================================================================== -->
<script>
$(document).ready(function() {
// Helper: Format Currency (PKR)
function formatCurrency(amount) {
return 'Rs. ' + parseFloat(amount).toLocaleString('en-PK', { maximumFractionDigits: 0 });
}

// Calculate Government Budget Balance
window.calculateGovtBalance = function() {
const govtBudget = parseFloat($('#govt_budget').val()) || 0;
const budgetExpenses = parseFloat($('#budget_expenses').val()) || 0;
const balance = govtBudget - budgetExpenses;
$('#govtBalanceDisplay').text(formatCurrency(balance));
};

// Calculate Fund Matrix Totals (includes NEW funds: building, absentee, admission)
window.calculateFundTotals = function() {
const primaryStudents = parseFloat($('#primary_students').val()) || 0;
const middleStudents = parseFloat($('#middle_students').val()) || 0;
const highStudents = parseFloat($('#high_students').val()) || 0;
const higherSecStudents = parseFloat($('#higher_secondary_students').val()) || 0;

// UPDATED: Includes 3 new funds
const funds = [
'tuition', 'development', 'building', 'admission', 'absentee',
'scout', 'computer', 'library', 'furniture', 'annual',
'sports', 'laboratory', 'medical', 'mosque', 'other'
];

let grandTotal = 0;
let sectionTotals = { primary: 0, middle: 0, high: 0, higherSec: 0 };
let fundTotals = {}; // Store individual fund totals

funds.forEach(fund => {
const multiplier = $('#' + fund + '_frequency').val() === 'monthly' ? 12 : 1;
const pAmt = parseFloat($('#' + fund + '_primary').val()) || 0;
const mAmt = parseFloat($('#' + fund + '_middle').val()) || 0;
const hAmt = parseFloat($('#' + fund + '_high').val()) || 0;
const hsAmt = parseFloat($('#' + fund + '_higher_sec').val()) || 0;

const pTotal = pAmt * primaryStudents * multiplier;
const mTotal = mAmt * middleStudents * multiplier;
const hTotal = hAmt * highStudents * multiplier;
const hsTotal = hsAmt * higherSecStudents * multiplier;

sectionTotals.primary += pTotal;
sectionTotals.middle += mTotal;
sectionTotals.high += hTotal;
sectionTotals.higherSec += hsTotal;

const fundTotal = pTotal + mTotal + hTotal + hsTotal;
fundTotals[fund] = fundTotal; // Store for submitted_govt calculation
grandTotal += fundTotal;

$('#' + fund + '_total').text('Rs. ' + fundTotal.toLocaleString('en-IN', { maximumFractionDigits: 0 }));
});

// Update Section Totals
$('#primary_section_total').text('Rs. ' + sectionTotals.primary.toLocaleString('en-IN', { maximumFractionDigits: 0 }));
$('#middle_section_total').text('Rs. ' + sectionTotals.middle.toLocaleString('en-IN', { maximumFractionDigits: 0 }));
$('#high_section_total').text('Rs. ' + sectionTotals.high.toLocaleString('en-IN', { maximumFractionDigits: 0 }));
$('#higher_sec_section_total').text('Rs. ' + sectionTotals.higherSec.toLocaleString('en-IN', { maximumFractionDigits: 0 }));
$('#grand_total').text('Rs. ' + grandTotal.toLocaleString('en-IN', { maximumFractionDigits: 0 }));

// Update Main Totals
$('#total_school_funds').text('Rs. ' + grandTotal.toLocaleString('en-IN', { maximumFractionDigits: 0 }));
$('#total_school_funds_input').val(grandTotal);
$('#fee_collected').val(grandTotal);

// === AUTO-CALCULATE SUBMITTED TO GOVERNMENT ===
// Sum of: Tuition + Annual + Admission + Absentee funds
const submittedGovt = (fundTotals['tuition'] || 0) +
(fundTotals['annual'] || 0) +
(fundTotals['admission'] || 0) +
(fundTotals['absentee'] || 0);
$('#submitted_govt').val(submittedGovt);
// =============================================

// Trigger Overall Calculation
calculateAll();
};

// Calculate All Financials & Validate Balance
window.calculateAll = function() {
const previousBalance = parseFloat($('#previous_balance').val()) || 0;
const donations = parseFloat($('#donations').val()) || 0;
const feeCollected = parseFloat($('#fee_collected').val()) || 0;
const feeExpenses = parseFloat($('#fee_expenses').val()) || 0;
const submittedGovt = parseFloat($('#submitted_govt').val()) || 0;

const schoolNetBalance = previousBalance + feeCollected + donations - feeExpenses - submittedGovt;

const cashInHand = parseFloat($('#cash_in_hand').val()) || 0;
const cashInBank = parseFloat($('#cash_in_bank').val()) || 0;
const totalCashAvailable = cashInHand + cashInBank;

const totalIncome = previousBalance + feeCollected + donations;
const totalExpenses = feeExpenses + submittedGovt;
const utilization = totalIncome > 0 ? ((totalExpenses / totalIncome) * 100).toFixed(1) : 0;

// Update Displays
$('#schoolBalanceDisplay').text(formatCurrency(schoolNetBalance));
$('#total_cash').val(formatCurrency(totalCashAvailable));
$('#totalFundsDisplay').text(formatCurrency(schoolNetBalance));
$('#cashPositionDisplay').text(formatCurrency(totalCashAvailable));
$('#currentBalanceDisplay').text(formatCurrency(schoolNetBalance));
$('#utilizationDisplay').text(utilization + '%');

// VALIDATION: Balance Reconciliation (tolerance: Rs. 1)
if (Math.abs(schoolNetBalance - totalCashAvailable) > 1) {
showBalanceError(`Balance mismatch: Rs.${schoolNetBalance.toLocaleString()} vs Rs.${totalCashAvailable.toLocaleString()}`);
} else {
clearBalanceError();
}
};

// Show Balance Error
function showBalanceError(message) {
$('.balance-error').remove();
$('.summary-section').after(
`<div class="alert alert-error balance-error">
<i class="fas fa-exclamation-triangle"></i> ${message}
</div>`
);
$('#submitBtn').prop('disabled', true);
}

// Clear Balance Error
function clearBalanceError() {
$('.balance-error').remove();
$('#submitBtn').prop('disabled', false);
}

// Input Validation: Prevent Negative Values
$('input[type="number"]:not([readonly])').on('input', function() {
if (parseFloat($(this).val()) < 0) {
$(this).val(0);
}
});

// === COMPULSORY FIELD VALIDATION LOGIC (UPDATED) ===
function validateCompulsoryFields() {
    let isValid = true;
    let errors = [];

    // 1. Validate Required Funds (1 out of 4 sections must have value > 0)
    $('tr[data-fund-required="true"]').each(function() {
        const row = $(this);
        const fundName = row.find('.fund-label').text().replace('*', '').trim();
        let hasPositiveValue = false;
        
        row.find('.fund-input').each(function() {
            const val = parseFloat($(this).val()) || 0;
            if (val > 0) {
                hasPositiveValue = true;
            }
        });
        
        if (!hasPositiveValue) {
            isValid = false;
            errors.push(`${fundName}: Enter at least one amount greater than 0 (Primary/Middle/High/Higher Sec).`);
            row.addClass('error-row');
        } else {
            row.removeClass('error-row');
        }
    });

    // 2. Validate Total Cash Available (Hand OR Bank must be > 0)
    const cashInHand = parseFloat($('#cash_in_hand').val()) || 0;
    const cashInBank = parseFloat($('#cash_in_bank').val()) || 0;
    if (cashInHand === 0 && cashInBank === 0) {
        isValid = false;
        errors.push("Total Cash Available: Enter Cash in Hand OR Cash in Bank (must be > 0).");
    }

    // 3. Validate Calculated Readonly Fields (> 0)
    const feeCollected = parseFloat($('#fee_collected').val()) || 0;
    if (feeCollected <= 0) {
        isValid = false;
        errors.push("Total Fee/Fund Collected: Must be greater than 0.");
    }

    const submittedGovt = parseFloat($('#submitted_govt').val()) || 0;
    if (submittedGovt <= 0) {
        isValid = false;
        errors.push("Submitted to Government: Must be greater than 0.");
    }

    if (!isValid) {
        alert("Please correct the following errors:\n\n" + errors.join("\n"));
        // Scroll to first error
        $('html, body').animate({ scrollTop: $(".error-row").first().offset().top - 100 }, 1000);
    }

    return isValid;
}

// Form Submission Handler
$('#budgetForm').on('submit', function(e) {
    // 1. Check Compulsory Fields Logic
    if (!validateCompulsoryFields()) {
        e.preventDefault();
        $('#submitBtn').html('<i class="fas fa-save"></i> Save & Continue').prop('disabled', false);
        return false;
    }

    // 2. Check Balance Reconciliation
    const schoolBalance = parseFloat($('#schoolBalanceDisplay').text().replace(/[^0-9.-]+/g, '')) || 0;
    const totalCash = parseFloat($('#total_cash').val().replace(/[^0-9.-]+/g, '')) || 0;
    if (Math.abs(schoolBalance - totalCash) > 1) {
        e.preventDefault();
        alert('Cannot submit: School Net Balance does not match Total Cash Available. Please reconcile.');
        $('#submitBtn').html('<i class="fas fa-save"></i> Save & Continue').prop('disabled', false);
        return false;
    }

    // Show Loading State
    $('#submitBtn').html('<span class="loading-spinner"></span>Processing...').prop('disabled', true);
    // Form submits naturally after this
});

// Initialize Calculations on Page Load
setTimeout(function() {
    calculateGovtBalance();
    calculateFundTotals();
}, 100);

// Debug Logging (Optional - Remove in Production)
console.log('Budget Form Loaded | FY: <?php echo $financial_year_display; ?> | EMIS: <?php echo $emis_code; ?>');
});
</script>
</body>
</html>