<!-- 

**File Structure:**
- emp1.php (Personal Information)
- emp2.php (Academic Qualifications)
- emp3.php (Professional Qualifications)
- emp4.php (In-Service Training)
- emp5.php (Subjects Teaching)
- emp6.php (Promotion History)
- emp7.php (Transfer History)

Here's the fifth file (emp5.php):
-->

<?php
require_once 'session_config_emp.php';
include_once 'connect.php';

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check if session is valid
if (!validateUserSession()) {
    // Redirect to login
    header('Location: login_emp.php');
    exit();
}

// Customize for each step
$stepNumber = 5; // Change for each file
$nextFile = 'emp6.php'; // Change for each file
$previousFile = 'emp4.php'; // Change for each file

// Check if user has completed previous steps
if (empty($_SESSION['form_data'])) {
    header("Location: $previousFile");
    exit();
}

$formData = $_SESSION['form_data'] ?? [];
$csrf_error = '';

// Handle form submission for current step
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["step_$stepNumber"])) {
    if (!isset($_POST['csrf_token']) || !validateCsrfToken($_POST['csrf_token'])) {
        $csrf_error = "Security token expired. Please try again.";
        regenerateCsrfToken();
    } else {
        // ✅ FIX: Remove CSRF token and step indicator from POST data
        $postData = $_POST;
        unset($postData['csrf_token']);
        unset($postData["step_$stepNumber"]);
        
        $_SESSION['form_data'] = array_merge($formData, $postData);
        regenerateCsrfToken();
        
        header("Location: $nextFile");
        exit();
    }
}

// ✅ FIX: Always use current session token
$currentToken = $_SESSION['csrf_token'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Profile Form - Step 5: Subjects Teaching</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    <style>
        /* Same CSS as previous files */
        :root {
            --primary-color: #3498db;
            --secondary-color: #2980b9;
            --accent-color: #e74c3c;
            --light-gray: #f5f5f5;
            --medium-gray: #e0e0e0;
            --dark-gray: #333;
            --success-color: #2ecc71;
            --warning-color: #f39c12;
            --border-radius: 6px;
            --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: 'Roboto', sans-serif;
            line-height: 1.6;
            color: var(--dark-gray);
            background-color: #f9f9f9;
            padding: 20px;
        }
        .form-container {
            max-width: 90%;
            margin: 10px auto;
            background: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            overflow: hidden;
        }
        .form-header {
            background: var(--primary-color);
            color: white;
            padding: 20px;
            text-align: center;
        }
        .form-header h1 {
            font-size: 24px;
            font-weight: 500;
        }
        .progress-container {
            display: flex;
            justify-content: space-between;
            position: relative;
            margin: 30px 50px;
        }
        .progress-container::before {
            content: "";
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--medium-gray);
            transform: translateY(-50%);
            z-index: 1;
        }
        .progress-bar {
            position: absolute;
            top: 50%;
            left: 0;
            height: 4px;
            background: var(--success-color);
            transform: translateY(-50%);
            z-index: 2;
            transition: var(--transition);
        }
        .step {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--medium-gray);
            color: var(--dark-gray);
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            z-index: 3;
            transition: var(--transition);
        }
        .step.active {
            background: var(--primary-color);
            color: white;
            transform: scale(1.1);
        }
        .step.completed {
            background: var(--success-color);
            color: white;
        }
        .step-label {
            position: absolute;
            top: 45px;
            font-size: 12px;
            color: var(--dark-gray);
            white-space: nowrap;
        }
        .step.active .step-label,
        .step.completed .step-label {
            color: var(--primary-color);
            font-weight: 500;
        }
        .form-step {
            display: none;
            padding: 30px;
        }
        .form-step.active {
            display: block;
            animation: fadeIn 0.5s ease;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .section-title {
            color: var(--primary-color);
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--medium-gray);
            font-size: 20px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-row {
            display: flex;
            flex-wrap: wrap;
            margin: 0 -10px;
        }
        .form-col {
            flex: 1;
            min-width: 250px;
            padding: 0 30px;
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #555;
        }
        input[type="text"],
        input[type="number"],
        input[type="date"],
        input[type="month"],
        input[type="file"],
        select,
        textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid var(--medium-gray);
            border-radius: var(--border-radius);
            font-size: 14px;
            transition: var(--transition);
        }
        input:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }
        .radio-group {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 8px;
        }
        .radio-option {
            display: flex;
            align-items: center;
        }
        .radio-option input {
            margin-right: 8px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        th, td {
            padding: 12px 5px;
            text-align: left;
            border-bottom: 1px solid var(--medium-gray);
        }
        th {
            background-color: var(--primary-color);
            color: white;
            font-weight: 500;
        }
        tr:nth-child(even) {
            background-color: var(--light-gray);
        }
        tr:hover {
            background-color: #f0f0f0;
        }
        .photo-upload {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin: 20px 0;
        }
        #fileDisplayArea {
            width: 150px;
            height: 180px;
            border: 2px dashed var(--medium-gray);
            border-radius: var(--border-radius);
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 15px;
            overflow: hidden;
            background-color: white;
        }
        #fileDisplayArea img {
            max-width: 100%;
            max-height: 100%;
            object-fit: cover;
        }
        .file-input-label {
            display: inline-block;
            padding: 10px 15px;
            background-color: var(--primary-color);
            color: white;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: var(--transition);
            text-align: center;
        }
        .file-input-label:hover {
            background-color: var(--secondary-color);
        }
        #tchpic {
            display: none;
        }
        .form-actions {
            display: flex;
            justify-content: space-between;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid var(--medium-gray);
        }
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: var(--border-radius);
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }


        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }
        .btn-primary:hover {
            background-color: var(--secondary-color);
        }
        .btn-secondary {
            background-color: var(--medium-gray);
            color: var(--dark-gray);
        }
        .btn-secondary:hover {
            background-color: #d0d0d0;
        }
        .btn-success {
            background-color: var(--success-color);
            color: white;
        }
        .btn-success:hover {
            background-color: #27ae60;
        }
        .btn i {
            margin-right: 8px;
        }
        .required-field::after {
            content: " *";
            color: var(--accent-color);
        }
        @media (max-width: 768px) {
            .form-col {
                min-width: 100%;
            }
            .progress-container {
                margin: 30px 20px;
            }
            .step-label {
                display: none;
            }
            .form-step {
                padding: 20px;
            }
        }
        /* Additional styles for Instructions window */
        .instructions {
            background-color: #e8f4fc;
            padding: 15px;
            border-radius: 6px;
            margin-top: 20px;
            font-size: 14px;
            line-height: 1.5;
        }
        .instructions h3 {
            color: #2c3e50;
            margin-bottom: 10px;
        }
        .instructions ul {
            padding-left: 20px;
        }
        .instructions li {
            margin-bottom: 5px;
        }
        .success-message {
            color: #27ae60;
            font-size: 13px;
            margin-top: 5px;
            display: none;
        }
        /* Subjects specific styles */
        .subject-select, .class-select, .section-select {
            width: 100%;
        }
        .periods-input {
            width: 80px;
            text-align: center;
        }
        .total-periods {
            font-weight: bold;
            color: var(--primary-color);
            font-size: 16px;
        }
        .periods-summary {
            background-color: var(--light-gray);
            padding: 15px;
            border-radius: var(--border-radius);
            margin: 20px 0;
            border-left: 4px solid var(--primary-color);
        }
        .optional-note {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
            padding: 10px;
            border-radius: var(--border-radius);
            margin: 10px 0;
            font-size: 14px;
        }
        .incomplete-row {
            background-color: #fff3cd !important;
        }
    </style>
</head>
<body>
    <!-- Floating Logout Button -->
    <div class="floating-logout-btn" style="position: fixed; bottom: 20px; right: 20px; z-index: 9999;">
        <button type="button" class="btn btn-danger shadow-lg" onclick="confirmLogout()" 
                style="border-radius: 50px; padding: 12px 25px; box-shadow: 0 4px 15px rgba(220, 53, 69, 0.4); font-weight: 600; transition: all 0.3s;">
            <i class="fas fa-sign-out-alt" style="margin-right: 8px;"></i> Logout
        </button>
    </div>

    <div class="form-container">
        <div class="form-header">
            <h1><i class="fas fa-user-tie"></i> Employee Profile Form - Step 5/7</h1>
        </div>
        <div class="progress-container">
            <div class="progress-bar" id="progressBar" style="width: 66.66%"></div>
            <div class="step completed" id="step1">
                <span>1</span>
                <span class="step-label">Personal Info</span>
            </div>
            <div class="step completed" id="step2">
                <span>2</span>
                <span class="step-label">Education</span>
            </div>
            <div class="step completed" id="step3">
                <span>3</span>
                <span class="step-label">Professional</span>
            </div>
            <div class="step completed" id="step4">
                <span>4</span>
                <span class="step-label">Training</span>
            </div>
            <div class="step active" id="step5">
                <span>5</span>
                <span class="step-label">Subjects</span>
            </div>
            <div class="step" id="step6">
                <span>6</span>
                <span class="step-label">Promotions</span>
            </div>
            <div class="step" id="step7">
                <span>7</span>
                <span class="step-label">Transfers</span>
            </div>
        </div>
        <form id="teacherForm" method="POST" onsubmit="return validateSubjectsData()">
            <!-- ✅ Use $currentToken instead of directly accessing $_SESSION -->
            <input type="hidden" name="csrf_token" value="<?php echo $currentToken; ?>">
            <input type="hidden" name="step_5" value="1">
            
            <!-- Step 5: Subjects Teaching -->
            <div class="form-step active" id="step-5">
                <h2 class="section-title"><i class="fas fa-book-open"></i> Subjects Teaching</h2>
                <div class="instructions">
                    <h3><i class="fas fa-info-circle"></i> Instructions:</h3>
                    <ul>
                        <li>Select the subjects and classes you are currently teaching (if applicable).</li>
                        <li>Enter the number of periods per week for each subject-class combination.</li>
                        <li>You can enter up to 10 different subject-class-section combinations.</li>
                        <li>Periods per week should be a positive number (1-40).</li>
                        <li><strong>Note: This section is OPTIONAL for non-teaching staff.</strong></li>
                        <li><strong>If you start entering a subject, you must complete ALL fields for that row (Subject, Class, Section, Periods).</strong></li>
                        <li><strong>No partially filled rows will be accepted.</strong></li>
                        <li>Incomplete rows will be highlighted in yellow.</li>
                    </ul>
                </div>

                <div class="optional-note">
                    <i class="fas fa-info-circle"></i> <strong>Optional Section:</strong> This section is for teaching staff only. 
                    Non-teaching employees can proceed without entering any subjects.
                </div>

                <!-- Periods Summary (Only show if subjects are entered) -->
                <div class="periods-summary" id="periodsSummary" style="display: none;">
                    <h4><i class="fas fa-chart-bar"></i> Teaching Load Summary</h4>
                    <p>Total Periods Per Week: <span id="totalPeriods" class="total-periods">0</span></p>
                    <p>Number of Subjects: <span id="subjectCount" class="total-periods">0</span></p>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>S.No</th>
                            <th>Subject Name</th>
                            <th>Class</th>
                            <th>Section</th>
                            <th>Periods Per Week</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        // Fetch subjects, classes and sections from database
                        $subjects = $conn->query("SELECT subj_id, subj_name FROM subjects ORDER BY subj_name");
                        $classes = $conn->query("SELECT class_id, class_name FROM class ORDER BY class_id");
                        $sections = $conn->query("SELECT section_id, section_name FROM sections ORDER BY section_name");
                        
                        // Generate 10 rows for subjects teaching
                        for ($i = 1; $i <= 10; $i++) {
                            $subjectValue = isset($formData["tesub{$i}sub"]) ? htmlspecialchars($formData["tesub{$i}sub"]) : '';
                            $classValue = isset($formData["tesub{$i}cla"]) ? htmlspecialchars($formData["tesub{$i}cla"]) : '';
                            $sectionValue = isset($formData["tesub{$i}sec"]) ? htmlspecialchars($formData["tesub{$i}sec"]) : '';
                            $periodsValue = isset($formData["tesub{$i}per"]) ? htmlspecialchars($formData["tesub{$i}per"]) : '';
                            
                            echo "<tr id=\"row-{$i}\">
                                    <td>{$i}</td>
                                    <td>
                                        <select name=\"tesub{$i}sub\" class=\"subject-select\" onchange=\"updateSummary(); checkRowCompleteness({$i}); checkForDuplicates(this);\">
                                            <option value=\"\" selected>Select Subject (Optional)</option>";
                            
                            // Populate subjects dropdown
                            if ($subjects->num_rows > 0) {
                                while($subject = $subjects->fetch_assoc()) {
                                    $selected = ($subjectValue == $subject['subj_id']) ? 'selected' : '';
                                    echo "<option value=\"{$subject['subj_id']}\" {$selected}>{$subject['subj_name']}</option>";
                                }
                                $subjects->data_seek(0); // Reset pointer for next row
                            }
                            
                            echo "  </select>
                                    </td>
                                    <td>
                                        <select name=\"tesub{$i}cla\" class=\"class-select\" onchange=\"updateSummary(); checkRowCompleteness({$i}); checkForDuplicates(this);\">
                                            <option value=\"\" selected>Select Class (Optional)</option>";
                            
                            // Populate classes dropdown
                            if ($classes->num_rows > 0) {
                                while($class = $classes->fetch_assoc()) {
                                    $selected = ($classValue == $class['class_id']) ? 'selected' : '';
                                    echo "<option value=\"{$class['class_id']}\" {$selected}>{$class['class_name']}</option>";
                                }
                                $classes->data_seek(0); // Reset pointer for next row
                            }
                            
                            echo "  </select>
                                    </td>
                                    <td>
                                        <select name=\"tesub{$i}sec\" class=\"section-select\" onchange=\"updateSummary(); checkRowCompleteness({$i}); checkForDuplicates(this);\">
                                            <option value=\"\" selected>Select Section (Optional)</option>";
                            
                            // Populate sections dropdown
                            if ($sections->num_rows > 0) {
                                while($section = $sections->fetch_assoc()) {
                                    $selected = ($sectionValue == $section['section_id']) ? 'selected' : '';
                                    echo "<option value=\"{$section['section_id']}\" {$selected}>{$section['section_name']}</option>";
                                }
                                $sections->data_seek(0); // Reset pointer for next row
                            }
                            
                            echo "  </select>
                                    </td>
                                    <td>
                                        <input name=\"tesub{$i}per\" type=\"number\" min=\"0\" max=\"40\" class=\"periods-input\" 
                                               placeholder=\"Periods\" value=\"{$periodsValue}\" oninput=\"updateSummary(); checkRowCompleteness({$i});\">
                                    </td>
                                  </tr>";
                        }
                        ?>
                    </tbody>
                </table>
                
                <!-- Form Actions -->
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="goBackToStep4()">
                        <i class="fas fa-arrow-left"></i> Back
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-arrow-right"></i> Next
                    </button>
                </div>
            </div>
        </form>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
    <script>
        // Logout confirmation function
        function confirmLogout() {
            if (confirm('Are you sure you want to logout?')) {
                window.location.href = 'logout_emp.php';
            }
        }

        // Optional: Add hover effect with JavaScript
        document.addEventListener('DOMContentLoaded', function() {
            const logoutBtn = document.querySelector('.floating-logout-btn button');
            if (logoutBtn) {
                logoutBtn.addEventListener('mouseenter', function() {
                    this.style.transform = 'translateY(-3px)';
                    this.style.boxShadow = '0 6px 20px rgba(220, 53, 69, 0.5)';
                });
                
                logoutBtn.addEventListener('mouseleave', function() {
                    this.style.transform = 'translateY(0)';
                    this.style.boxShadow = '0 4px 15px rgba(220, 53, 69, 0.4)';
                });
            }

            // Initialize summary and check all rows
            updateSummary();
            for (let i = 1; i <= 10; i++) {
                checkRowCompleteness(i);
            }
        });

        // Update teaching load summary
        function updateSummary() {
            let totalPeriods = 0;
            let subjectCount = 0;
            
            // Calculate totals from all rows
            for (let i = 1; i <= 10; i++) {
                const subject = document.querySelector(`[name="tesub${i}sub"]`).value;
                const classVal = document.querySelector(`[name="tesub${i}cla"]`).value;
                const sectionVal = document.querySelector(`[name="tesub${i}sec"]`).value;
                const periods = parseInt(document.querySelector(`[name="tesub${i}per"]`).value) || 0;
                
                // Count only if all required fields are filled
                if (subject && classVal && sectionVal && periods > 0) {
                    totalPeriods += periods;
                    subjectCount++;
                }
            }
            
            // Update summary display
            document.getElementById('totalPeriods').textContent = totalPeriods;
            document.getElementById('subjectCount').textContent = subjectCount;
            
            // Show/hide summary based on whether subjects are entered
            const summaryElement = document.getElementById('periodsSummary');
            if (subjectCount > 0) {
                summaryElement.style.display = 'block';
            } else {
                summaryElement.style.display = 'none';
            }
        }

        // Check if a row is complete or incomplete
        function checkRowCompleteness(rowNumber) {
            const subject = document.querySelector(`[name="tesub${rowNumber}sub"]`).value;
            const classVal = document.querySelector(`[name="tesub${rowNumber}cla"]`).value;
            const sectionVal = document.querySelector(`[name="tesub${rowNumber}sec"]`).value;
            const periods = document.querySelector(`[name="tesub${rowNumber}per"]`).value;
            
            // Check if any field is filled
            const hasAnyField = subject || classVal || sectionVal || periods;
            
            const row = document.getElementById(`row-${rowNumber}`);
            
            if (hasAnyField) {
                // Check if all fields are filled
                const isComplete = subject && classVal && sectionVal && periods;
                
                if (!isComplete) {
                    // Incomplete row - highlight in yellow
                    row.classList.add('incomplete-row');
                } else {
                    // Complete row - remove highlight
                    row.classList.remove('incomplete-row');
                }
            } else {
                // Empty row - remove highlight
                row.classList.remove('incomplete-row');
            }
        }

        // Subjects Data Validation - OPTIONAL but must be complete if started
        function validateSubjectsData() {
            let isValid = true;
            
            // Get all subject rows
            const subjectRows = [];
            for (let i = 1; i <= 10; i++) {
                subjectRows.push({
                    row: i,
                    subject: document.querySelector(`[name="tesub${i}sub"]`),
                    class: document.querySelector(`[name="tesub${i}cla"]`),
                    section: document.querySelector(`[name="tesub${i}sec"]`),
                    periods: document.querySelector(`[name="tesub${i}per"]`)
                });
            }

            // Validate each subject row
            for (let i = 0; i < subjectRows.length; i++) {
                const row = subjectRows[i];
                const hasSubject = row.subject.value !== '';
                const hasClass = row.class.value !== '';
                const hasSection = row.section.value !== '';
                const hasPeriods = row.periods.value.trim() !== '';
                
                // If any field is filled, all must be filled
                if (hasSubject || hasClass || hasSection || hasPeriods) {
                    let missingFields = [];
                    
                    if (!hasSubject) missingFields.push('Subject Name');
                    if (!hasClass) missingFields.push('Class');
                    if (!hasSection) missingFields.push('Section');
                    if (!hasPeriods) missingFields.push('Periods Per Week');
                    
                    if (missingFields.length > 0) {
                        isValid = false;
                        alert(`ERROR: Row ${row.row} is partially filled.\n\nPlease complete all fields for this subject:\n• ${missingFields.join('\n• ')}\n\nOR remove all entries for this row.`);
                        return false;
                    }
                    
                    // Validate periods
                    if (hasPeriods) {
                        const periods = parseInt(row.periods.value);
                        if (periods < 1 || periods > 40) {
                            isValid = false;
                            alert(`ERROR: Invalid periods in row ${row.row}.\n\nPeriods per week must be between 1 and 40.`);
                            row.periods.focus();
                            return false;
                        }
                    }
                }
            }

            if (!isValid) {
                return false;
            }

            // Check for duplicate subject-class-section combinations
            const subjectClassSectionCombinations = new Set();
            for (let i = 0; i < subjectRows.length; i++) {
                const row = subjectRows[i];
                const subject = row.subject.value;
                const classVal = row.class.value;
                const sectionVal = row.section.value;
                
                if (subject && classVal && sectionVal) {
                    const combination = `${subject}-${classVal}-${sectionVal}`;
                    if (subjectClassSectionCombinations.has(combination)) {
                        isValid = false;
                        alert(`ERROR: Duplicate subject-class-section combination found in row ${row.row}.\n\nEach subject-class-section combination must be unique.`);
                        row.subject.focus();
                        return false;
                    }
                    subjectClassSectionCombinations.add(combination);
                }
            }

            // Show warning if no subjects are entered (optional step)
            const hasAnySubject = subjectRows.some(row => 
                row.subject.value !== '' || 
                row.class.value !== '' || 
                row.section.value !== '' ||
                row.periods.value.trim() !== ''
            );

            if (!hasAnySubject) {
                const proceed = confirm('⚠️ WARNING: No subjects entered.\n\nSubjects teaching information is optional and only required for teaching staff.\nDo you want to proceed without entering any subjects?');
                if (!proceed) {
                    return false;
                }
            }

            // Validate total periods (optional warning for high load)
            const totalPeriods = parseInt(document.getElementById('totalPeriods').textContent) || 0;
            if (totalPeriods > 35) {
                const proceed = confirm(`⚠️ WARNING: High teaching load detected (${totalPeriods} periods per week).\n\nThis exceeds the typical teaching load. Do you want to continue?`);
                if (!proceed) {
                    return false;
                }
            }

            // Auto-save form data before proceeding
            const formData = new FormData(document.getElementById('teacherForm'));
            
            return fetch('save_emp_step_data.php', {
                method: 'POST',
                body: formData
            }).then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return true;
            }).catch(error => {
                console.error('Error saving form data:', error);
                // Even if save fails, allow form submission
                return true;
            });
        }

        // Back button function
        function goBackToStep4() {
            const formData = new FormData(document.getElementById('teacherForm'));
            formData.append('step', '5'); // ✅ ADD THIS
            
            fetch('save_emp_step_data.php', {
                method: 'POST',
                body: formData
            }).then(response => response.json())
              .then(data => {
                  if (data.success) {
                      window.location.href = 'emp4.php?back=1';
                  } else {
                      alert('Error: ' + data.message);
                      window.location.href = 'emp4.php?back=1';
                  }
              }).catch(() => {
                  window.location.href = 'emp4.php?back=1';
              });
        }

        // Check for duplicate subject-class-section combinations
        function checkForDuplicates(changedElement) {
            const row = changedElement.closest('tr');
            const rowIndex = Array.from(row.parentNode.children).indexOf(row) + 1;
            const currentSubject = row.querySelector('.subject-select').value;
            const currentClass = row.querySelector('.class-select').value;
            const currentSection = row.querySelector('.section-select').value;
            
            if (!currentSubject || !currentClass || !currentSection) return;
            
            // Check for duplicates in other rows
            const allRows = document.querySelectorAll('tbody tr');
            for (let i = 0; i < allRows.length; i++) {
                if (i + 1 === rowIndex) continue; // Skip current row
                
                const otherRow = allRows[i];
                const otherSubject = otherRow.querySelector('.subject-select').value;
                const otherClass = otherRow.querySelector('.class-select').value;
                const otherSection = otherRow.querySelector('.section-select').value;
                
                if (otherSubject === currentSubject && 
                    otherClass === currentClass && 
                    otherSection === currentSection) {
                    alert('⚠️ This subject-class-section combination already exists in another row.');
                    changedElement.value = '';
                    updateSummary();
                    checkRowCompleteness(rowIndex);
                    break;
                }
            }
            
            updateSummary();
            checkRowCompleteness(rowIndex);
        }

        // Real-time validation for periods input
        function validatePeriodsInput(input) {
            const value = parseInt(input.value) || 0;
            
            if (value < 0) {
                input.value = '';
            } else if (value > 40) {
                input.value = 40;
            }
            
            updateSummary();
        }

        // Initialize input validations
        document.addEventListener('DOMContentLoaded', function() {
            // Add input event listeners for periods fields
            const periodsFields = document.querySelectorAll('.periods-input');
            periodsFields.forEach(field => {
                field.addEventListener('input', function() {
                    validatePeriodsInput(this);
                    const rowNumber = this.name.match(/\d+/)[0];
                    checkRowCompleteness(rowNumber);
                });
                field.addEventListener('blur', function() {
                    validatePeriodsInput(this);
                    const rowNumber = this.name.match(/\d+/)[0];
                    checkRowCompleteness(rowNumber);
                });
            });
        });

        // Prevent form submission on Enter key in input fields
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('teacherForm');
            const inputs = form.querySelectorAll('input, select, textarea');
            
            inputs.forEach(input => {
                input.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        return false;
                    }
                });
            });
        });
    </script>
</body>
</html>