<!-- 

**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 sixth file (emp6.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 = 6;
$nextFile = 'emp7.php';
$previousFile = 'emp5.php';

// 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 before saving
        $postData = $_POST;
        unset($postData['csrf_token']); // Remove CSRF token
        unset($postData["step_$stepNumber"]); // Remove step indicator
        
        // Save current step data (without CSRF token)
        $_SESSION['form_data'] = array_merge($formData, $postData);
        
        // ✅ FIX: Regenerate CSRF token for next step
        regenerateCsrfToken();
        
        // Redirect to next step
        header("Location: $nextFile");
        exit();
    }
}

// ✅ FIX: Always use current session token for the form
$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 6: Promotion History</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;
        }
        /* Promotion specific styles */
        .promotion-select {
            width: 100%;
        }
        .promotion-date {
            width: 150px;
        }
        .optional-note {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
            padding: 10px;
            border-radius: var(--border-radius);
            margin: 10px 0;
            font-size: 14px;
        }
        .date-input-container {
            position: relative;
            display: flex;
            align-items: center;
        }
        .datepicker-trigger {
            cursor: pointer;
            margin-left: -25px;
            color: #666;
        }
        .error-message {
            color: red;
            font-size: 0.9em;
            margin-top: 5px;
            display: none;
        }
    </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>

<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)';
        });
    }
});
</script>
    <div class="form-container">
        <div class="form-header">
            <h1><i class="fas fa-user-tie"></i> Employee Profile Form - Step 6/7</h1>
        </div>
        <div class="progress-container">
            <div class="progress-bar" id="progressBar" style="width: 83.33%"></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 completed" id="step5">
                <span>5</span>
                <span class="step-label">Subjects</span>
            </div>
            <div class="step active" 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 validatePromotionData()">
			<!-- ✅ Correct: Uses $currentToken -->
            <input type="hidden" name="csrf_token" value="<?php echo $currentToken; ?>">
            <input type="hidden" name="step_6" value="1">
            
            <!-- Step 6: Promotion History -->
            <div class="form-step active" id="step-6">
                <h2 class="section-title"><i class="fas fa-chart-line"></i> Promotion History (Last Five in Ascending, If applicable)</h2>
                <div class="instructions">
                    <h3><i class="fas fa-info-circle"></i> Instructions:</h3>
                    <ul>
                        <li>Enter promotion details for the last five promotions (if applicable).</li>
                        <li>Fill entries in chronological order (oldest promotion first).</li>
                        <li>Use the calendar picker or enter date in DD-MM-YYYY format.</li>
                        <li>Select appropriate designations and pay scales from dropdowns.</li>
                        <li><strong>Note: This section is OPTIONAL for employees without promotion history.</strong></li>
                        <li><strong>If you start entering a promotion record, you must complete ALL fields for that promotion.</strong></li>
                        <li><strong>No partially filled records will be accepted.</strong></li>
                    </ul>
                </div>

                <div class="optional-note">
                    <i class="fas fa-info-circle"></i> <strong>Optional Section:</strong> This section is for employees who have received promotions. 
                    If you haven't been promoted or don't have promotion records, you can proceed without entering any data.
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>Previous Designation</th>
                            <th>Previous Scale</th>
                            <th>New Designation</th>
                            <th>New Scale</th>
                            <th>Date of Promotion</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        // Fetch designations and pay scales from database
                        $designations = $conn->query("SELECT des_id, designation_name FROM designations ORDER BY designation_name");
                        $bps_scales = $conn->query("SELECT bps_id, bps_name, bps_label FROM bps ORDER BY bps_id");
                        
                        // Generate 5 promotion history rows
                        for ($i = 1; $i <= 5; $i++) {
                            $prevDesigValue = isset($formData["tepro{$i}pre"]) ? htmlspecialchars($formData["tepro{$i}pre"]) : '';
                            $prevScaleValue = isset($formData["tepro{$i}presc"]) ? htmlspecialchars($formData["tepro{$i}presc"]) : '';
                            $newDesigValue = isset($formData["tepro{$i}new"]) ? htmlspecialchars($formData["tepro{$i}new"]) : '';
                            $newScaleValue = isset($formData["tepro{$i}newsc"]) ? htmlspecialchars($formData["tepro{$i}newsc"]) : '';
                            $promoDateValue = isset($formData["tepro{$i}date"]) ? htmlspecialchars($formData["tepro{$i}date"]) : '';
                            
                            echo "<tr>
                                    <td>
                                        <select name=\"tepro{$i}pre\" class=\"promotion-select\">
                                            <option value=\"\" selected>Select Previous Designation</option>";
                            
                            // Populate previous designation dropdown
                            if ($designations->num_rows > 0) {
                                while($desg = $designations->fetch_assoc()) {
                                    $selected = ($prevDesigValue == $desg['des_id']) ? 'selected' : '';
                                    echo "<option value=\"{$desg['des_id']}\" {$selected}>{$desg['designation_name']}</option>";
                                }
                                $designations->data_seek(0);
                            }
                            
                            echo "  </select>
                                    </td>
                                    <td>
                                        <select name=\"tepro{$i}presc\" class=\"promotion-select\">
                                            <option value=\"\" selected>Select Previous Scale</option>";
                            
                            // Populate previous scale dropdown
                            if ($bps_scales->num_rows > 0) {
                                while($scale = $bps_scales->fetch_assoc()) {
                                    $selected = ($prevScaleValue == $scale['bps_id']) ? 'selected' : '';
                                    echo "<option value=\"{$scale['bps_id']}\" {$selected}>{$scale['bps_label']} ({$scale['bps_name']})</option>";
                                }
                                $bps_scales->data_seek(0);
                            }
                            
                            echo "  </select>
                                    </td>
                                    <td>
                                        <select name=\"tepro{$i}new\" class=\"promotion-select\">
                                            <option value=\"\" selected>Select New Designation</option>";
                            
                            // Populate new designation dropdown
                            if ($designations->num_rows > 0) {
                                while($desg = $designations->fetch_assoc()) {
                                    $selected = ($newDesigValue == $desg['des_id']) ? 'selected' : '';
                                    echo "<option value=\"{$desg['des_id']}\" {$selected}>{$desg['designation_name']}</option>";
                                }
                                $designations->data_seek(0);
                            }
                            
                            echo "  </select>
                                    </td>
                                    <td>
                                        <select name=\"tepro{$i}newsc\" class=\"promotion-select\">
                                            <option value=\"\" selected>Select New Scale</option>";
                            
                            // Populate new scale dropdown
                            if ($bps_scales->num_rows > 0) {
                                while($scale = $bps_scales->fetch_assoc()) {
                                    $selected = ($newScaleValue == $scale['bps_id']) ? 'selected' : '';
                                    echo "<option value=\"{$scale['bps_id']}\" {$selected}>{$scale['bps_label']} ({$scale['bps_name']})</option>";
                                }
                                $bps_scales->data_seek(0);
                            }
                            
                            echo "  </select>
                                    </td>
                                    <td>
                                        <div class=\"date-input-container\">
                                            <input id=\"tepro{$i}date\" name=\"tepro{$i}date\" type=\"text\" class=\"promotion-date date-field\"
                                                placeholder=\"DD-MM-YYYY\"
                                                maxlength=\"10\"
                                                pattern=\"\\d{2}-\\d{2}-\\d{4}\"
                                                title=\"Please enter date in DD-MM-YYYY format\"
                                                value=\"{$promoDateValue}\">
                                            <span class=\"datepicker-trigger\" onclick=\"showDatePicker('tepro{$i}date')\">
                                                <i class=\"fas fa-calendar-alt\"></i>
                                            </span>
                                        </div>
                                        <div id=\"tepro{$i}date-error\" class=\"error-message\">Invalid date format (DD-MM-YYYY)</div>
                                    </td>
                                  </tr>";
                        }
                        ?>
                    </tbody>
                </table>
                
                <!-- Form Actions -->
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="goBackToStep5()">
                        <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>
        // JavaScript functions for step 6
        document.addEventListener('DOMContentLoaded', function() {
            <?php
            // Pre-fill form with saved data
            foreach ($formData as $field => $value) {
                if ($field !== 'csrf_token' && $field !== 'step_6') {
                    echo "if(document.querySelector('[name=\"$field\"]')) document.querySelector('[name=\"$field\"]').value = '" . addslashes($value) . "';";
                }
            }
            ?>
            
            // Initialize datepickers
            $('.date-field').datepicker({
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true,
                yearRange: '-50:+0',
                maxDate: 0 // Cannot select future dates
            });
        });

        function showDatePicker(fieldId) {
            $('#' + fieldId).datepicker('show');
        }

        // Promotion Data Validation - OPTIONAL but must be complete if started
        function validatePromotionData() {
            let isValid = true;
            
            // Get all promotion rows
            const promotions = [];
            for (let i = 1; i <= 5; i++) {
                promotions.push({
                    row: i,
                    prevDesignation: document.querySelector(`[name="tepro${i}pre"]`),
                    prevScale: document.querySelector(`[name="tepro${i}presc"]`),
                    newDesignation: document.querySelector(`[name="tepro${i}new"]`),
                    newScale: document.querySelector(`[name="tepro${i}newsc"]`),
                    promoDate: document.querySelector(`[name="tepro${i}date"]`)
                });
            }

            // Validate each promotion record
            for (let i = 0; i < promotions.length; i++) {
                const promo = promotions[i];
                const hasPrevDesig = promo.prevDesignation.value !== '';
                const hasPrevScale = promo.prevScale.value !== '';
                const hasNewDesig = promo.newDesignation.value !== '';
                const hasNewScale = promo.newScale.value !== '';
                const hasPromoDate = promo.promoDate.value.trim() !== '';
                
                // If any field is filled, all must be filled
                if (hasPrevDesig || hasPrevScale || hasNewDesig || hasNewScale || hasPromoDate) {
                    let missingFields = [];
                    
                    if (!hasPrevDesig) missingFields.push('Previous Designation');
                    if (!hasPrevScale) missingFields.push('Previous Scale');
                    if (!hasNewDesig) missingFields.push('New Designation');
                    if (!hasNewScale) missingFields.push('New Scale');
                    if (!hasPromoDate) missingFields.push('Date of Promotion');
                    
                    if (missingFields.length > 0) {
                        isValid = false;
                        alert(`ERROR: Promotion record ${promo.row} is partially filled.\n\nPlease complete all fields for this promotion:\n• ${missingFields.join('\n• ')}\n\nOR remove all entries for this promotion.`);
                        return false;
                    }
                    
                    // Validate date format
                    if (hasPromoDate) {
                        const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
                        const match = promo.promoDate.value.match(dateRegex);
                        
                        if (!match) {
                            isValid = false;
                            alert(`ERROR: Invalid date format in promotion record ${promo.row}.\n\nPlease use DD-MM-YYYY format.`);
                            promo.promoDate.focus();
                            return false;
                        }
                        
                        // Basic date validation
                        const day = parseInt(match[1], 10);
                        const month = parseInt(match[2], 10);
                        const year = parseInt(match[3], 10);
                        const currentYear = new Date().getFullYear();
                        
                        if (day < 1 || day > 31 || month < 1 || month > 12 || year < 1900 || year > currentYear) {
                            isValid = false;
                            alert(`ERROR: Invalid date in promotion record ${promo.row}.\n\nPlease enter a valid date.`);
                            promo.promoDate.focus();
                            return false;
                        }
                        
                        // Validate date is not in future
                        const promoDate = new Date(year, month - 1, day);
                        const today = new Date();
                        today.setHours(0, 0, 0, 0);
                        
                        if (promoDate > today) {
                            isValid = false;
                            alert(`ERROR: Promotion date in record ${promo.row} cannot be in the future.`);
                            promo.promoDate.focus();
                            return false;
                        }
                    }
                }
            }

            if (!isValid) {
                return false;
            }

            // Additional validation: Check chronological order (oldest first)
            const filledPromotions = promotions
                .map(promo => ({
                    row: promo.row,
                    date: promo.promoDate.value,
                    dateObj: promo.promoDate.value ? parseDate(promo.promoDate.value) : null
                }))
                .filter(promo => promo.dateObj !== null)
                .sort((a, b) => a.dateObj - b.dateObj); // Sort ascending (oldest first)

            // Check if filled promotions are in correct order
            for (let i = 0; i < filledPromotions.length - 1; i++) {
                if (filledPromotions[i].dateObj > filledPromotions[i + 1].dateObj) {
                    const proceed = confirm('⚠️ WARNING: Promotions are not in chronological order (oldest first).\n\nDo you want to continue anyway?');
                    if (!proceed) {
                        return false;
                    }
                    break;
                }
            }

            // Show warning if no promotions are filled (optional step)
            const hasAnyPromotion = promotions.some(promo => 
                promo.prevDesignation.value !== '' ||
                promo.prevScale.value !== '' ||
                promo.newDesignation.value !== '' ||
                promo.newScale.value !== '' ||
                promo.promoDate.value.trim() !== ''
            );

            if (!hasAnyPromotion) {
                const proceed = confirm('⚠️ WARNING: No promotion records entered.\n\nPromotion history is optional and only required for employees with promotion history.\nDo you want to proceed without entering any promotion records?');
                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;
            });
        }

        // Helper function to parse DD-MM-YYYY date
        function parseDate(dateStr) {
            const parts = dateStr.split('-');
            if (parts.length !== 3) return null;
            const day = parseInt(parts[0], 10);
            const month = parseInt(parts[1], 10) - 1; // Months are 0-indexed in JavaScript
            const year = parseInt(parts[2], 10);
            return new Date(year, month, day);
        }

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

        // Real-time date format validation
        document.addEventListener('DOMContentLoaded', function() {
            // Add input event listeners for date fields
            const dateFields = document.querySelectorAll('.date-field');
            dateFields.forEach(field => {
                field.addEventListener('input', function() {
                    validateDateFormat(this);
                });
                field.addEventListener('blur', function() {
                    validateDateFormat(this);
                });
            });
        });

        function validateDateFormat(dateField) {
            const errorElement = document.getElementById(dateField.id + '-error');
            const dateValue = dateField.value.trim();
            
            if (dateValue === '') {
                errorElement.style.display = 'none';
                return true;
            }
            
            const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
            const match = dateValue.match(dateRegex);
            
            if (!match) {
                errorElement.style.display = 'block';
                return false;
            }
            
            // Basic date validation
            const day = parseInt(match[1], 10);
            const month = parseInt(match[2], 10);
            const year = parseInt(match[3], 10);
            const currentYear = new Date().getFullYear();
            
            if (day < 1 || day > 31 || month < 1 || month > 12 || year < 1900 || year > currentYear) {
                errorElement.style.display = 'block';
                return false;
            }
            
            errorElement.style.display = 'none';
            return true;
        }

        // Enhanced datepicker functionality
        $(function() {
            $('.date-field').datepicker({
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true,
                yearRange: '-50:+0',
                maxDate: 0,
                onSelect: function(dateText, inst) {
                    // Hide error message when date is selected from picker
                    const errorElement = document.getElementById(this.id + '-error');
                    if (errorElement) {
                        errorElement.style.display = 'none';
                    }
                }
            });
        });

        // 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>
    <script>
function validatePromotionData() {
    let valid = true;
    let errorMessage = "";

    for (let i = 1; i <= 5; i++) {

        let prevDesig = document.querySelector(`[name="tepro${i}pre"]`).value.trim();
        let prevScale = document.querySelector(`[name="tepro${i}presc"]`).value.trim();
        let newDesig  = document.querySelector(`[name="tepro${i}new"]`).value.trim();
        let newScale  = document.querySelector(`[name="tepro${i}newsc"]`).value.trim();
        let promoDate = document.querySelector(`[name="tepro${i}date"]`).value.trim();

        // Skip empty rows (optional section)
        if (prevDesig === "" && prevScale === "" && newDesig === "" && newScale === "" && promoDate === "") {
            continue;
        }

        // Prevent partially filled promotion rows
        if (prevDesig === "" || prevScale === "" || newDesig === "" || newScale === "" || promoDate === "") {
            alert(`Please complete all fields for Promotion Row #${i}.`);
            return false;
        }

        // Restriction: Previous Designation = New Designation
        if (prevDesig === newDesig) {
            alert(`Row ${i}: Previous Designation and New Designation cannot be the same.`);
            return false;
        }

        // Restriction: Previous Scale = New Scale
        if (prevScale === newScale) {
            alert(`Row ${i}: Previous Scale and New Scale cannot be the same.`);
            return false;
        }
    }

    return true;
}
</script>

</body>
</html>