<!-- 
  **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 fifth file (school_step5.php):
    -->
	
	<?php
// school_step5.php
// Session started
require_once 'session_config_school.php';

// Validate school session
if (!validateSchoolSession()) {
    header("Location: login.php");
    exit;
}

// School Profile Completion Check
require_once 'school_profile_completion_check.php';

// Database connection
include_once 'connect.php';

// Initialize variables
$success_message = '';
$error_message = '';

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

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

// 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']);
}

// Clear form data after displaying (will be repopulated if needed)
if (isset($_SESSION['form_data'])) {
    unset($_SESSION['form_data']);
}

// =================== FETCH EXISTING DATA ===================
$existing_post_details = [];
$total_summary = [
    'total_male' => 0,
    'total_female' => 0,
    'total_budget' => 0,
    'total_filled' => 0,
    'total_vacant' => 0
];
$school_posts_id = null;

// First, get the school_posts master record ID for this school
if (!empty($emis_code)) {
    // Check if master record exists in school_posts
    $stmt = $conn->prepare("SELECT id, male_staff, female_staff, budget_posts, filled_posts, vacant_posts FROM school_posts WHERE emis_code = ?");
    $stmt->bind_param("s", $emis_code);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $school_posts_id = $row['id'];
        
        // Set master totals
        $total_summary['total_male'] = $row['male_staff'];
        $total_summary['total_female'] = $row['female_staff'];
        $total_summary['total_budget'] = $row['budget_posts'];
        $total_summary['total_filled'] = $row['filled_posts'];
        $total_summary['total_vacant'] = $row['vacant_posts'];
        
        // Now get all designation details from school_posts_summary
        $stmt2 = $conn->prepare("
            SELECT sps.*, d.designation_name 
            FROM school_posts_summary sps
            JOIN designations d ON sps.des_id = d.des_id
            WHERE sps.sp_id = ?
            ORDER BY sps.id
        ");
        $stmt2->bind_param("i", $school_posts_id);
        $stmt2->execute();
        $result2 = $stmt2->get_result();
        
        while ($row2 = $result2->fetch_assoc()) {
            $existing_post_details[] = [
                'post_name' => $row2['designation_name'],
                'des_id' => $row2['des_id'],
                'male_staff' => $row2['male_staff'],
                'female_staff' => $row2['female_staff'],
                'budget_posts' => $row2['budget_posts'],
                'filled_posts' => $row2['filled_posts'],
                'vacant_posts' => $row2['vacant_posts']
            ];
        }
        $stmt2->close();
    }
    $stmt->close();
}

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

// =================== HELPER FUNCTIONS ===================
/**
 * Get form field value with priority: POST > Session > Database > Default
 * For array fields like post_name[], male[], etc.
 */
function getPostFieldValue($field_name, $index, $default = '') {
    global $_POST, $_SESSION, $existing_post_details;
    
    // Priority 1: POST data (form submission)
    if (isset($_POST[$field_name]) && is_array($_POST[$field_name]) && isset($_POST[$field_name][$index])) {
        $value = $_POST[$field_name][$index];
        if ($value !== '') {
            return $value;
        }
    }
    
    // Priority 2: Session data (form repopulation after error)
    if (isset($_SESSION['form_data'][$field_name]) && is_array($_SESSION['form_data'][$field_name]) && isset($_SESSION['form_data'][$field_name][$index])) {
        $value = $_SESSION['form_data'][$field_name][$index];
        if ($value !== '') {
            return $value;
        }
    }
    
    // Priority 3: Existing database data
    if (isset($existing_post_details[$index])) {
        switch ($field_name) {
            case 'post_name':
                // Return des_id for post_name field (will be used to select the correct option)
                return $existing_post_details[$index]['des_id'] ?? $default;
            case 'male':
                return $existing_post_details[$index]['male_staff'] ?? $default;
            case 'female':
                return $existing_post_details[$index]['female_staff'] ?? $default;
            case 'post_as_per_budget':
                return $existing_post_details[$index]['budget_posts'] ?? $default;
            case 'filled_post':
                return $existing_post_details[$index]['filled_posts'] ?? $default;
            case 'vacant_post':
                return $existing_post_details[$index]['vacant_posts'] ?? $default;
        }
    }
    
    return $default;
}

/**
 * Check if there are any existing posts to pre-populate
 */
function hasExistingData() {
    global $existing_post_details;
    return !empty($existing_post_details);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>School Posts Registration - Step 5 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: #3498db; transform: translateY(-50%); z-index: 2; transition: width 0.3s ease; width: 50%; }
.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: #3498db; 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: #3498db; font-weight: 600; }
.form-container { background: white; border-radius: 10px; border-left: 4px solid #3498db; 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: #3498db; box-shadow: 0 0 0 3px rgba(52, 152, 219, 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: " (optional)"; 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 #3498db; display: flex; align-items: center; gap: 10px; }
.section-title i { color: #3498db; }
.submit-btn { display: block; width: 200px; margin: 30px auto 0; padding: 15px 30px; background: linear-gradient(135deg, #3498db, #2980b9); 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(52, 152, 219, 0.3); background: linear-gradient(135deg, #2980b9, #1f6399); }
.submit-btn:active { transform: translateY(0); }
.loading-spinner { display: inline-block; width: 20px; height: 20px; border: 3px solid rgba(255,255,255,.3); border-radius: 50%; border-top-color: #fff; animation: spin 1s ease-in-out infinite; margin-right: 10px; vertical-align: middle; }
@keyframes spin { to { transform: rotate(360deg); } }
.helper-text { font-size: 12px; color: #7f8c8d; margin-top: 5px; }
.alert { padding: 15px; border-radius: 6px; margin-bottom: 20px; text-align: center; font-weight: 500; }
.alert-success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.alert-error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
.radio-group { display: flex; gap: 30px; margin-bottom: 20px; justify-content: center; }
.radio-option { display: flex; align-items: center; gap: 8px; cursor: pointer; }
.radio-option input[type="radio"] { width: 18px; height: 18px; cursor: pointer; }
.radio-label { font-weight: 600; color: #2c3e50; cursor: pointer; }
.posts-container { margin-top: 20px; }
.post-row { display: grid; grid-template-columns: repeat(6, 1fr) auto; gap: 15px; padding: 20px; margin-bottom: 15px; background-color: #f8f9fa; border-radius: 8px; border-left: 3px solid #3498db; align-items: center; transition: all 0.3s ease; }
.post-row:hover { background-color: #f1f8ff; border-left-color: #2980b9; }
.post-row-header { display: grid; grid-template-columns: repeat(6, 1fr) auto; gap: 15px; padding: 15px 20px; background-color: #2c3e50; color: white; border-radius: 8px 8px 0 0; font-weight: 600; margin-bottom: 10px; }
.post-row .form-group { margin-bottom: 0; }
.post-row .form-group label { font-size: 12px; color: #666; margin-bottom: 4px; }
.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; }
.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 #3498db; }
.school-info h3 { color: #2c3e50; margin-bottom: 10px; font-size: 16px; }
.school-info p { color: #666; font-size: 14px; }
.total-summary { background-color: #e8f4fc; padding: 15px; border-radius: 8px; margin-top: 20px; border-left: 4px solid #3498db; }
.total-summary h4 { color: #2c3e50; margin-bottom: 10px; }
.summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }
.summary-item { background: white; padding: 10px; border-radius: 6px; text-align: center; }
.summary-item .value { font-size: 24px; font-weight: 700; color: #3498db; }
.summary-item .label { font-size: 12px; color: #666; margin-top: 5px; }
.incomplete-row { border-left-color: #f39c12; background-color: #fff8e1; }
.complete-row { border-left-color: #27ae60; }
.auto-calculated { background-color: #f0f8ff; }
.auto-calculated input { background-color: #f8f9fa; color: #666; cursor: not-allowed; }
@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, #3498db, #2980b9); 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(52, 152, 219, 0.3); background: linear-gradient(135deg, #2980b9, #1f6399); }
.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; font-style: italic; }
/* Responsive styles */
@media (max-width: 992px) {
    .post-row, .post-row-header { grid-template-columns: repeat(3, 1fr); }
    .post-row-header { display: none; }
}
@media (max-width: 768px) { 
    .form-grid, .post-row, .post-row-header { 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; }
    .post-row { padding: 15px; }
    .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; }
    .summary-grid { grid-template-columns: 1fr; }
}
</style>

</head>
<body>
<?php include 'floating_logout_school.php'; ?>
<div class="container">
<div class="header">
<h1><i class="fas fa-users"></i> School Posts Registration - Step 5 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 active" id="step5"><span>5</span><span class="step-label">School Posts</span></div>
<div class="step" id="step6"><span>6</span><span class="step-label">Students</span></div>
<div class="step" id="step7"><span>7</span><span class="step-label">Board Results</span></div>
<div class="step" id="step8"><span>8</span><span class="step-label">Budget</span></div>
<div class="step" id="step9"><span>9</span><span class="step-label">SMC</span></div>
<div class="step" id="step10"><span>10</span><span class="step-label">Location & View</span></div>
</div>
<?php if(!empty($success_message)): ?>
<div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?></div>
<?php endif; ?>
<?php if(!empty($error_message)): ?>
<div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error_message); ?></div>
<?php endif; ?>
<div class="form-container">
<div class="school-info">
<h3><i class="fas fa-info-circle"></i> Staff Posts Information</h3>
<p>Fill in all staff posts details for <strong><?php echo htmlspecialchars($school_name); ?></strong> (EMIS: <strong><?php echo htmlspecialchars($emis_code); ?></strong>). Filled and Vacant posts are calculated automatically.</p>
<p><small><i class="fas fa-info-circle"></i> <strong>Note:</strong> Post Name, Budget Posts, and at least one staff count (Male or Female) are required to add the next post.</small></p>
</div>
<!-- 🔒 SECURITY: Added CSRF token -->
<form method="POST" action="school_step5_save.php" id="postsForm">
<input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
<input type="hidden" name="school_posts_id" value="<?php echo htmlspecialchars($school_posts_id ?? ''); ?>">

<!-- Section: Posts Details -->
<div class="form-section">
<h3 class="section-title"><i class="fas fa-clipboard-list"></i> Staff Posts Details</h3>
<div class="posts-container">
<div class="post-row-header">
<div>Post Name *</div>
<div>Male Staff</div>
<div>Female Staff</div>
<div>Budget Posts *</div>
<div>Filled Posts</div>
<div>Vacant Posts</div>
<div>Action</div>
</div>
<div id="postsContainer">
<!-- Posts will be dynamically added here -->
</div>
<div class="action-buttons">
<button type="button" class="add-btn" id="addPostBtn" onclick="addPostRow()" <?php echo hasExistingData() ? '' : 'disabled'; ?>>
<i class="fas fa-plus"></i> Add Post
</button>
</div>
</div>
</div>
<!-- Summary Section -->
<div class="total-summary">
<h4><i class="fas fa-chart-bar"></i> Total Summary</h4>
<div class="summary-grid">
<div class="summary-item">
<div class="value" id="totalMale"><?php echo $total_summary['total_male']; ?></div>
<div class="label">Total Male Staff</div>
</div>
<div class="summary-item">
<div class="value" id="totalFemale"><?php echo $total_summary['total_female']; ?></div>
<div class="label">Total Female Staff</div>
</div>
<div class="summary-item">
<div class="value" id="totalBudget"><?php echo $total_summary['total_budget']; ?></div>
<div class="label">Total Budget Posts</div>
</div>
<div class="summary-item">
<div class="value" id="totalFilled"><?php echo $total_summary['total_filled']; ?></div>
<div class="label">Total Filled Posts</div>
</div>
<div class="summary-item">
<div class="value" id="totalVacant"><?php echo $total_summary['total_vacant']; ?></div>
<div class="label">Total Vacant Posts</div>
</div>
</div>
</div>
<div class="navigation-buttons">
<button type="button" class="nav-btn back" onclick="window.location.href='school_step4.php'">
<i class="fas fa-arrow-left"></i> Back
</button>
<button type="submit" class="nav-btn" id="submitBtn" style="margin-left: auto;" name="school_posts_submit">
<i class="fas fa-save"></i> Save & Continue
</button>
</div>
</form>
</div>
</div>
<script>
$(document).ready(function() {
    // Initialize post counter
    window.postCounter = 0;
    
    // Store designations data from PHP
    window.designations = <?php echo json_encode($designations); ?>;
    
    // Store summary data
    window.totalSummary = <?php echo json_encode($total_summary); ?>;
    
    // Pre-populate form from existing data
    <?php if (!empty($existing_post_details)): ?>
        // Clear default state - we'll add rows from existing data
        window.postCounter = 0;
        
        <?php foreach ($existing_post_details as $index => $post): ?>
            addPostRow(
                <?php echo $post['des_id']; ?>,
                <?php echo $post['male_staff']; ?>,
                <?php echo $post['female_staff']; ?>,
                <?php echo $post['budget_posts']; ?>
            );
        <?php endforeach; ?>
        
        // Update dropdown options after adding all rows
        setTimeout(function() {
            updatePostOptions();
            updateAddPostButton();
        }, 100);
    <?php else: ?>
        // Add first empty post row
        addPostRow();
    <?php endif; ?>
    
    // Function to calculate filled and vacant posts for a row
    window.calculatePosts = function(rowElement) {
        const maleInput = rowElement.find('input[name="male[]"]');
        const femaleInput = rowElement.find('input[name="female[]"]');
        const budgetInput = rowElement.find('input[name="post_as_per_budget[]"]');
        const filledInput = rowElement.find('input[name="filled_post[]"]');
        const vacantInput = rowElement.find('input[name="vacant_post[]"]');
        
        // Get values
        const male = parseInt(maleInput.val()) || 0;
        const female = parseInt(femaleInput.val()) || 0;
        const budget = parseInt(budgetInput.val()) || 0;
        
        // Calculate filled posts (male + female)
        const filled = male + female;
        
        // Calculate vacant posts (budget - (male + female))
        let vacant = budget - filled;
        if (vacant < 0) vacant = 0;
        
        // Update the calculated fields
        filledInput.val(filled);
        vacantInput.val(vacant);
        
        // Update totals
        updateTotals();
    };
    
    // NEW FUNCTION: Validate that filled posts don't exceed budget posts
    window.validateFilledVsBudget = function(rowElement) {
        const male = parseInt(rowElement.find('input[name="male[]"]').val()) || 0;
        const female = parseInt(rowElement.find('input[name="female[]"]').val()) || 0;
        const budget = parseInt(rowElement.find('input[name="post_as_per_budget[]"]').val()) || 0;
        const filled = male + female;
        
        // Add or remove error class based on validation
        if (filled > budget && budget > 0) {
            rowElement.find('input[name="male[]"], input[name="female[]"], input[name="post_as_per_budget[]"]').addClass('validation-error');
            rowElement.find('.filled-error-message').remove();
            rowElement.append('<div class="filled-error-message" style="color: #e74c3c; font-size: 12px; margin-top: 5px; grid-column: 1 / -1;"><i class="fas fa-exclamation-circle"></i> Filled posts cannot exceed budget posts</div>');
            return false;
        } else {
            rowElement.find('input[name="male[]"], input[name="female[]"], input[name="post_as_per_budget[]"]').removeClass('validation-error');
            rowElement.find('.filled-error-message').remove();
            return true;
        }
    };
    
    // Check if current row is complete (for enabling Add Post button)
    window.checkRowComplete = function(rowElement) {
        const postName = rowElement.find('select[name="post_name[]"]').val();
        const male = parseInt(rowElement.find('input[name="male[]"]').val()) || 0;
        const female = parseInt(rowElement.find('input[name="female[]"]').val()) || 0;
        const budget = rowElement.find('input[name="post_as_per_budget[]"]').val();
        const filled = male + female;
        const budgetNum = parseInt(budget) || 0;
        
        // Required: Post Name, Budget Posts, and at least one staff count (male OR female)
        // AND filled posts must not exceed budget
        const isComplete = postName !== '' && 
                          budget !== '' && 
                          budgetNum > 0 &&
                          (male > 0 || female > 0) &&
                          filled <= budgetNum; // ADDED: Filled posts validation
        
        // Update row styling
        if (isComplete) {
            rowElement.removeClass('incomplete-row').addClass('complete-row');
        } else {
            rowElement.removeClass('complete-row').addClass('incomplete-row');
        }
        
        return isComplete;
    };
    
    // Function to update Add Post button state
    window.updateAddPostButton = function() {
        const lastRow = $('.post-row:last');
        if (lastRow.length > 0) {
            const lastRowComplete = window.checkRowComplete(lastRow);
            $('#addPostBtn').prop('disabled', !lastRowComplete);
        } else {
            $('#addPostBtn').prop('disabled', true);
        }
    };
    
    // Form validation (for submission)
    $('#postsForm').on('submit', function(e) {
        let isValid = true;
        let hasPosts = false;
        let selectedPosts = new Set();
        let hasDuplicates = false;
        let incompleteRows = 0;
        let filledExceedsBudget = false;
        let errorMessages = [];
        
        // Clear previous error styling
        $('.validation-error').removeClass('validation-error');
        $('select, input').css('border-color', '');
        $('.filled-error-message').remove();
        
        // Validate each post row
        $('.post-row').each(function(index) {
            const postName = $(this).find('select[name="post_name[]"]').val();
            const male = parseInt($(this).find('input[name="male[]"]').val()) || 0;
            const female = parseInt($(this).find('input[name="female[]"]').val()) || 0;
            const budget = $(this).find('input[name="post_as_per_budget[]"]').val();
            const budgetNum = parseInt(budget) || 0;
            const filled = male + female;
            
            // Check if at least post name is filled
            if (postName) {
                hasPosts = true;
                
                // Check for duplicate posts
                if (selectedPosts.has(postName)) {
                    hasDuplicates = true;
                    $(this).find('select[name="post_name[]"]').addClass('validation-error');
                    errorMessages.push(`Duplicate post: ${$(this).find('select[name="post_name[]"] option:selected').text()} can only be added once.`);
                } else {
                    selectedPosts.add(postName);
                }
                
                // NEW: Check if filled posts exceed budget
                if (budgetNum > 0 && filled > budgetNum) {
                    filledExceedsBudget = true;
                    $(this).find('input[name="male[]"], input[name="female[]"], input[name="post_as_per_budget[]"]').addClass('validation-error');
                    errorMessages.push(`Row ${index + 1}: Filled posts (${filled}) cannot exceed budget posts (${budgetNum}).`);
                    isValid = false;
                }
                
                // Check if all required fields are filled for submission
                const rowCompleteForSubmission = postName !== '' && 
                                                budget !== '' && 
                                                budgetNum > 0 &&
                                                (male > 0 || female > 0);
                
                if (!rowCompleteForSubmission) {
                    incompleteRows++;
                    
                    // Highlight incomplete required fields
                    if (postName === '') {
                        $(this).find('select[name="post_name[]"]').addClass('validation-error');
                    }
                    if (budget === '' || budgetNum <= 0) {
                        $(this).find('input[name="post_as_per_budget[]"]').addClass('validation-error');
                    }
                    if (male === 0 && female === 0) {
                        $(this).find('input[name="male[]"]').addClass('validation-error');
                        $(this).find('input[name="female[]"]').addClass('validation-error');
                    }
                    
                    isValid = false;
                }
            } else if (postName === '' && (budget !== '' || male > 0 || female > 0)) {
                // If post name is empty but other fields have values
                isValid = false;
                $(this).find('select[name="post_name[]"]').addClass('validation-error');
                errorMessages.push(`Row ${index + 1}: Please select a post name.`);
            }
        });
        
        if (!hasPosts) {
            e.preventDefault();
            alert('Please add at least one staff post.');
            return false;
        }
        
        if (hasDuplicates) {
            e.preventDefault();
            alert('Duplicate posts detected:\n' + errorMessages.join('\n'));
            return false;
        }
        
        if (filledExceedsBudget) {
            e.preventDefault();
            alert('Validation Error:\n' + errorMessages.join('\n'));
            return false;
        }
        
        if (incompleteRows > 0) {
            e.preventDefault();
            alert('Please complete all required fields (Post Name, Budget Posts > 0, and at least one staff count) in each post row before submitting.');
            return false;
        }
        
        if (!isValid && errorMessages.length > 0) {
            e.preventDefault();
            alert('Please fix the following errors:\n' + errorMessages.join('\n'));
            return false;
        }
        
        // Show loading state
        $('#submitBtn').html('<span class="loading-spinner"></span> Processing...').prop('disabled', true);
    });

    // Real-time validation feedback
    $(document).on('blur', 'select[name="post_name[]"], input[name="post_as_per_budget[]"]', function() {
        if (!$(this).val() || ($(this).attr('name') === 'post_as_per_budget[]' && parseInt($(this).val()) <= 0)) {
            $(this).addClass('validation-error');
        } else {
            $(this).removeClass('validation-error');
        }
        // Check row completion on blur
        const rowElement = $(this).closest('.post-row');
        window.checkRowComplete(rowElement);
        updateAddPostButton();
    });

    // Real-time calculation and validation on input change
    $(document).on('input', 'input[name="male[]"], input[name="female[]"], input[name="post_as_per_budget[]"]', function() {
        const rowElement = $(this).closest('.post-row');
        
        // Validate number range
        let value = parseInt($(this).val()) || 0;
        if (value < 0) {
            $(this).val(0);
            value = 0;
        } else if (value > 500) {
            $(this).val(500);
            value = 500;
            alert('Maximum value allowed is 500');
        }
        
        // If this is budget field and value is 0, highlight it
        if ($(this).attr('name') === 'post_as_per_budget[]' && value <= 0) {
            $(this).addClass('validation-error');
        } else {
            $(this).removeClass('validation-error');
        }
        
        // Calculate filled and vacant posts
        calculatePosts(rowElement);
        
        // NEW: Validate filled vs budget
        validateFilledVsBudget(rowElement);
        
        // Check row completion (for Add Post button)
        window.checkRowComplete(rowElement);
        updateAddPostButton();
        
        // Clear error styling when at least one staff count is entered
        if ($(this).attr('name') === 'male[]' || $(this).attr('name') === 'female[]') {
            const male = parseInt(rowElement.find('input[name="male[]"]').val()) || 0;
            const female = parseInt(rowElement.find('input[name="female[]"]').val()) || 0;
            
            if (male > 0 || female > 0) {
                rowElement.find('input[name="male[]"]').removeClass('validation-error');
                rowElement.find('input[name="female[]"]').removeClass('validation-error');
            }
        }
    });

    // Number validation for all number inputs
    $(document).on('input', 'input[type="number"]', function() {
        let value = parseInt($(this).val()) || 0;
        if (value < 0) {
            $(this).val(0);
        } else if (value > 500) {
            $(this).val(500);
            alert('Maximum value allowed is 500');
        }
    });

    // Handle post selection change
    $(document).on('change', 'select[name="post_name[]"]', function() {
        updatePostOptions();
        // Check row completion
        const rowElement = $(this).closest('.post-row');
        window.checkRowComplete(rowElement);
        updateAddPostButton();
    });
});

// Function to update dropdown options (disable already selected posts)
window.updatePostOptions = function() {
    // Get all currently selected post IDs (excluding empty values)
    const selectedPosts = [];
    $('select[name="post_name[]"]').each(function() {
        const value = $(this).val();
        if (value) {
            selectedPosts.push(value);
        }
    });
    
    // Update each dropdown
    $('select[name="post_name[]"]').each(function() {
        const currentValue = $(this).val();
        let optionsHtml = '<option value="">-- Select Designation --</option>';
        
        // Check if designations array exists and has data
        if (window.designations && window.designations.length > 0) {
            // Build options from designations array using des_id as value
            window.designations.forEach(function(designation) {
                const value = designation.des_id;
                const text = designation.designation_name;
                
                if (value == currentValue) {
                    // Current selection - enabled and selected
                    optionsHtml += `<option value="${value}" selected>${text}</option>`;
                } else if (selectedPosts.includes(value.toString())) {
                    // Already selected in another row - disabled
                    optionsHtml += `<option value="${value}" disabled>${text} (Already Selected)</option>`;
                } else {
                    // Available for selection
                    optionsHtml += `<option value="${value}">${text}</option>`;
                }
            });
        } else {
            // Fallback if no designations are loaded
            optionsHtml += '<option value="" disabled>No designations available</option>';
        }
        
        $(this).html(optionsHtml);
    });
};

// Make addPostRow globally accessible
window.addPostRow = function(des_id = '', male = 0, female = 0, budget = 0) {
    // Check if last row is complete before adding new one (unless pre-populating)
    if (!des_id) {
        const lastRow = $('.post-row:last');
        if (lastRow.length > 0) {
            const isComplete = window.checkRowComplete(lastRow);
            if (!isComplete) {
                alert('Please complete Post Name, Budget Posts (>0), and add at least one staff count (Male or Female) in the current post before adding a new one.');
                return false;
            }
        }
    }
    
    window.postCounter++;
    const rowId = 'post-row-' + window.postCounter;
    
    // Generate options HTML
    let optionsHtml = '<option value="">-- Select Designation --</option>';
    
    // Check if designations array exists and has data
    if (window.designations && window.designations.length > 0) {
        window.designations.forEach(function(designation) {
            const selected = (designation.des_id == des_id) ? 'selected' : '';
            optionsHtml += `<option value="${designation.des_id}" ${selected}>${designation.designation_name}</option>`;
        });
    } else {
        optionsHtml += '<option value="" disabled>No designations available</option>';
    }
    
    const postRow = $(`
        <div class="post-row incomplete-row" id="${rowId}">
            <div class="form-group">
                <label for="postName_${window.postCounter}" class="required">Post Name</label>
                <select id="postName_${window.postCounter}" name="post_name[]" required>
                    ${optionsHtml}
                </select>
            </div>
            <div class="form-group">
                <label for="male_${window.postCounter}" class="optional">Male Staff</label>
                <input type="number" id="male_${window.postCounter}" name="male[]" min="0" max="500" value="${male}" placeholder="0">
            </div>
            <div class="form-group">
                <label for="female_${window.postCounter}" class="optional">Female Staff</label>
                <input type="number" id="female_${window.postCounter}" name="female[]" min="0" max="500" value="${female}" placeholder="0">
            </div>
            <div class="form-group">
                <label for="postAsPerBudget_${window.postCounter}" class="required">Budget Posts</label>
                <input type="number" id="postAsPerBudget_${window.postCounter}" name="post_as_per_budget[]" min="0" max="500" value="${budget}" placeholder="0" required>
            </div>
            <div class="form-group auto-calculated">
                <label for="filledPost_${window.postCounter}">Filled Posts</label>
                <input type="number" id="filledPost_${window.postCounter}" name="filled_post[]" min="0" max="500" value="${parseInt(male) + parseInt(female)}" readonly>
            </div>
            <div class="form-group auto-calculated">
                <label for="vacantPost_${window.postCounter}">Vacant Posts</label>
                <input type="number" id="vacantPost_${window.postCounter}" name="vacant_post[]" min="0" max="500" value="${Math.max(0, parseInt(budget) - (parseInt(male) + parseInt(female)))}" readonly>
            </div>
            <div class="form-group">
                <label style="visibility: hidden;">Actions</label>
                <button type="button" class="remove-btn" onclick="removePostRow('${rowId}')">
                    <i class="fas fa-trash"></i> Remove
                </button>
            </div>
        </div>
    `);
    
    $('#postsContainer').append(postRow);
    
    // Update dropdown options after adding new row
    setTimeout(function() {
        updatePostOptions();
        updateTotals();
        
        // NEW: Validate filled vs budget for this new row
        const newRow = $('#' + rowId);
        if (newRow.length) {
            window.validateFilledVsBudget(newRow);
        }
    }, 100);
    
    // Disable Add Post button for new incomplete row (unless pre-populating with complete data)
    if (!des_id || !budget || (male === 0 && female === 0)) {
        $('#addPostBtn').prop('disabled', true);
    }
    
    return true;
};

window.removePostRow = function(rowId) {
    if ($('.post-row').length <= 1) {
        alert('At least one post row is required.');
        return;
    }
    
    if (confirm('Are you sure you want to remove this post?')) {
        $('#' + rowId).fadeOut(300, function() {
            $(this).remove();
            updatePostOptions();
            updateTotals();
            
            // Check completion of last row and update Add Post button
            const lastRow = $('.post-row:last');
            if (lastRow.length > 0) {
                window.checkRowComplete(lastRow);
                updateAddPostButton();
            } else {
                // If no rows left, add a new empty row
                addPostRow();
            }

        });
    }
};

window.updateTotals = function() {
    let totalMale = 0;
    let totalFemale = 0;
    let totalBudget = 0;
    let totalFilled = 0;
    let totalVacant = 0;
    
    $('.post-row').each(function() {
        const male = parseInt($(this).find('input[name="male[]"]').val()) || 0;
        const female = parseInt($(this).find('input[name="female[]"]').val()) || 0;
        const budget = parseInt($(this).find('input[name="post_as_per_budget[]"]').val()) || 0;
        const filled = parseInt($(this).find('input[name="filled_post[]"]').val()) || 0;
        const vacant = parseInt($(this).find('input[name="vacant_post[]"]').val()) || 0;
        
        totalMale += male;
        totalFemale += female;
        totalBudget += budget;
        totalFilled += filled;
        totalVacant += vacant;
    });
    
    $('#totalMale').text(totalMale);
    $('#totalFemale').text(totalFemale);
    $('#totalBudget').text(totalBudget);
    $('#totalFilled').text(totalFilled);
    $('#totalVacant').text(totalVacant);
};

// 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
        setTimeout(function() {
            updatePostOptions();
            updateTotals();
            updateAddPostButton();
        }, 100);
    }
});
</script>
</body>
</html>