<!-- 

**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 second file (emp2.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 = 2;
$nextFile = 'emp3.php';
$previousFile = 'emp1.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 2</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>
         :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 datepicker */
         .ui-datepicker {
         background: #fff;
         border: 1px solid #ccc;
         border-radius: 1px;
         padding: 5px;
         box-shadow: 0 2px 5px rgba(0,0,0,0.1);
         }
         .ui-datepicker-header {
         background: var(--primary-color);
         color: white;
         border: none;
         border-radius: 2px;
         }
         .ui-datepicker-calendar th {
         background: blue;
         }
         .ui-datepicker-calendar .ui-state-active {
         background: var(--primary-color);
         color: white;
         }
         .datepicker-trigger {
         cursor: pointer;
         margin-left: -25px;
         color: #666;
         }
         .date-input-container {
         position: relative;
         display: flex;
         align-items: center;
         }
         .date-input-container input {
         padding-right: 30px;
         }
         .error-message {
         color: red;
         font-size: 0.9em;
         margin-top: 5px;
         display: none;
         }
         /* 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;
         }
         /* Added style for date fields */
         .date-field {
         cursor: pointer;
         background-color: #fff;
         }
         /* Style for subject input validation */
         .subject-input.invalid {
         border-color: #e74c3c;
         box-shadow: 0 0 0 2px rgba(231, 76, 60, 0.2);
         }
         .subject-error {
         color: #e74c3c;
         font-size: 0.8em;
         margin-top: 3px;
         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 2/7</h1>
        </div>
        <div class="progress-container">
            <div class="progress-bar" id="progressBar" style="width: 16.66%"></div>
            <div class="step completed" id="step1">
                <span>1</span>
                <span class="step-label">Personal Info</span>
            </div>
            <div class="step active" id="step2">
                <span>2</span>
                <span class="step-label">Education</span>
            </div>
            <div class="step" id="step3">
                <span>3</span>
                <span class="step-label">Professional</span>
            </div>
            <div class="step" id="step4">
                <span>4</span>
                <span class="step-label">Training</span>
            </div>
            <div class="step" 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 validateAcademicQualifications()">
			<!-- ✅ Use $currentToken instead of directly accessing $_SESSION -->
			<input type="hidden" name="csrf_token" value="<?php echo $currentToken; ?>">
			<input type="hidden" name="step_2" value="1">
			
            <!-- Step 2: Academic Qualifications -->
            <div class="form-step active" id="step-2">
                <h2 class="section-title"><i class="fas fa-graduation-cap"></i> Academic Qualifications</h2>
                <div class="instructions">
                    <h3><i class="fas fa-info-circle"></i> Instructions:</h3>
                    <ul>
                        <li>Enter the date in DD-MM-YYYY format or use the calendar picker.</li>
                        <li>Fill in all required fields marked with an asterisk (*).</li>
                        <li>Enter obtained marks to automatically calculate division.</li>
                        <li>Select the appropriate board/university from the dropdown.</li>
                        <li><strong>Qualifications must be entered in chronological order (Matric → Intermediate → Higher levels).</strong></li>
                        <li><strong>If you start entering a qualification, you must complete all its fields.</strong></li>
                        <li><strong>Minimum requirements: Matric and Intermediate must be completed.</strong></li>
                        <li><strong>Subject fields only accept alphabets and commas (no numbers or special characters).</strong></li>
                        <li><strong>Obtained marks cannot exceed total marks.</strong></li>
                        <li><strong>Note: Higher education qualifications (B.A/B.Sc, M.A/M.Sc, M.Phil, Ph.D) are OPTIONAL.</strong></li>
                        <li><strong>However, if you start entering any qualification, you must complete ALL fields for that qualification.</strong></li>
                        <li><strong>No partially filled records will be accepted for optional qualifications.</strong></li>
                    </ul>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>Degree</th>
                            <th>Result Declaration Date *</th>
                            <th>Subject(s) *</th>
                            <th>University/Board *</th>
                            <th>Total Marks *</th>
                            <th>Obtained Marks *</th>
                            <th>Grade/Division *</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Secondary Certificate -->
                        <tr>
                            <td>Secondary Certificate *</td>
                            <td>
                                <div class="date-input-container">
                                    <input id="tesscpass" name="tesscpass" type="text" class="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="<?php echo isset($formData['tesscpass']) ? htmlspecialchars($formData['tesscpass']) : ''; ?>"
                                        >
                                    <span class="datepicker-trigger" onclick="showDatePicker('tesscpass')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="tesscpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <input name="tesscsub" type="text" class="subject-input" 
                                    value="<?php echo isset($formData['tesscsub']) ? htmlspecialchars($formData['tesscsub']) : ''; ?>" 
                                    placeholder="e.g., Mathematics, English, Science">
                                <div class="subject-error" id="tesscsub-error">Only alphabets and commas allowed</div>
                            </td>
                            <td>
                                <select name="tesscuni" class="board-input" >
                                    <option value="" >Select Board/University</option>
                                    <?php
                                    // Fetch boards from database
                                    $sql = "SELECT b_id, b_name FROM boards WHERE status = 1 ORDER by b_id ASC";
                                    $result = $conn->query($sql);
                                    
                                    if ($result->num_rows > 0) {
                                        while($row = $result->fetch_assoc()) {
                                            $selected = (isset($formData['tesscuni']) && $formData['tesscuni'] == $row['b_id']) ? 'selected' : '';
                                            echo '<option value="' . $row['b_id'] . '" ' . $selected . '>' . $row['b_name'] . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                            </td>
                            <td><input name="tessctot" type="number" min="0" class="total-marks" value="<?php echo isset($formData['tessctot']) ? htmlspecialchars($formData['tessctot']) : '850'; ?>" required onchange="updateMaxObtainedMarks(); calculateDivision(this)"></td>
                            <td><input name="tesscom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                                value="<?php echo isset($formData['tesscom']) ? htmlspecialchars($formData['tesscom']) : ''; ?>" ></td>
                            <td><input name="tesscdiv" type="text" class="division-grade" readonly
                                value="<?php echo isset($formData['tesscdiv']) ? htmlspecialchars($formData['tesscdiv']) : ''; ?>"></td>
                        </tr>
                        <!-- Higher Secondary Certificate -->
                        <tr>
                            <td>Higher Secondary Certificate *</td>
                            <td>
                                <div class="date-input-container">
                                    <input id="tehscpass" name="tehscpass" type="text" class="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="<?php echo isset($formData['tehscpass']) ? htmlspecialchars($formData['tehscpass']) : ''; ?>"
                                        >
                                    <span class="datepicker-trigger" onclick="showDatePicker('tehscpass')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="tehscpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <input name="tehscsub" type="text" class="subject-input"
                                    value="<?php echo isset($formData['tehscsub']) ? htmlspecialchars($formData['tehscsub']) : ''; ?>"
                                    placeholder="e.g., Physics, Chemistry, Biology">
                                <div class="subject-error" id="tehscsub-error">Only alphabets and commas allowed</div>
                            </td>
                            <td>
                                <select name="tehscuni" class="board-input" >
                                    <option value="" >Select Board/University</option>
                                    <?php
                                    // Fetch boards from database
                                    $sql = "SELECT b_id, b_name FROM boards WHERE status = 1 ORDER by b_id ASC";
                                    $result = $conn->query($sql);
                                    
                                    if ($result->num_rows > 0) {
                                        while($row = $result->fetch_assoc()) {
                                            $selected = (isset($formData['tehscuni']) && $formData['tehscuni'] == $row['b_id']) ? 'selected' : '';
                                            echo '<option value="' . $row['b_id'] . '" ' . $selected . '>' . $row['b_name'] . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                            </td>
                            <td><input name="tehsctot" type="number" min="0" class="total-marks" value="<?php echo isset($formData['tehsctot']) ? htmlspecialchars($formData['tehsctot']) : '1100'; ?>" required onchange="updateMaxObtainedMarks(); calculateDivision(this)"></td>
                            <td><input name="tehscom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                                value="<?php echo isset($formData['tehscom']) ? htmlspecialchars($formData['tehscom']) : ''; ?>" ></td>
                            <td><input name="tehscdiv" type="text" class="division-grade" readonly
                                value="<?php echo isset($formData['tehscdiv']) ? htmlspecialchars($formData['tehscdiv']) : ''; ?>"></td>
                        </tr>
                     <!-- B.A/B.Sc/BS -->
                     <tr>
                        <td>B.A/B.Sc/BS</td>
                        <td>
                           <div class="date-input-container">
                              <input id="tebspass" name="tebspass" type="text" class="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="<?php echo isset($formData['tebspass']) ? htmlspecialchars($formData['tebspass']) : ''; ?>">
                              <span class="datepicker-trigger" onclick="showDatePicker('tebspass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="tebspass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                            <input name="tebssub" type="text" class="subject-input"
                               value="<?php echo isset($formData['tebssub']) ? htmlspecialchars($formData['tebssub']) : ''; ?>"
                               placeholder="e.g., Computer Science, Mathematics">
                            <div class="subject-error" id="tebssub-error">Only alphabets and commas allowed</div>
                        </td>
                        <td>
                           <select name="tebsuni" class="board-input">
                              <option value="" >Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         $selected = (isset($formData['tebsuni']) && $formData['tebsuni'] == $uni_id) ? 'selected' : '';
                                         echo '<option value="' . $uni_id . '" ' . $selected . '>' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tebstot" type="number" min="0" class="total-marks" value="<?php echo isset($formData['tebstot']) ? htmlspecialchars($formData['tebstot']) : '1000'; ?>" onchange="updateMaxObtainedMarks(); calculateDivision(this)"></td>
                        <td><input name="tebsom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                           value="<?php echo isset($formData['tebsom']) ? htmlspecialchars($formData['tebsom']) : ''; ?>"></td>
                        <td><input name="tebsdiv" type="text" class="division-grade" readonly
                           value="<?php echo isset($formData['tebsdiv']) ? htmlspecialchars($formData['tebsdiv']) : ''; ?>"></td>
                     </tr>
                     <!-- M.A/M.Sc/MCS -->
                     <tr>
                        <td>M.A/M.Sc/MCS</td>
                        <td>
                           <div class="date-input-container">
                              <input id="temapass" name="temapass" type="text" class="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="<?php echo isset($formData['temapass']) ? htmlspecialchars($formData['temapass']) : ''; ?>">
                              <span class="datepicker-trigger" onclick="showDatePicker('temapass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="temapass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                            <input name="temasub" type="text" class="subject-input"
                               value="<?php echo isset($formData['temasub']) ? htmlspecialchars($formData['temasub']) : ''; ?>"
                               placeholder="e.g., Software Engineering, Data Science">
                            <div class="subject-error" id="temasub-error">Only alphabets and commas allowed</div>
                        </td>
                        <td>
                           <select name="temauni" class="board-input">
                              <option value="" >Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         $selected = (isset($formData['temauni']) && $formData['temauni'] == $uni_id) ? 'selected' : '';
                                         echo '<option value="' . $uni_id . '" ' . $selected . '>' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tematot" type="number" min="0" class="total-marks" value="<?php echo isset($formData['tematot']) ? htmlspecialchars($formData['tematot']) : '1000'; ?>" onchange="updateMaxObtainedMarks(); calculateDivision(this)"></td>
                        <td><input name="temaom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                           value="<?php echo isset($formData['temaom']) ? htmlspecialchars($formData['temaom']) : ''; ?>"></td>
                        <td><input name="temadiv" type="text" class="division-grade" readonly
                           value="<?php echo isset($formData['temadiv']) ? htmlspecialchars($formData['temadiv']) : ''; ?>"></td>
                     </tr>
                     <!-- Master In Other Subject (1) -->
                     <tr>
                        <td>Master In Other Subject</td>
                        <td>
                           <div class="date-input-container">
                              <input id="temapass2" name="temapass2" type="text" class="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="<?php echo isset($formData['temapass2']) ? htmlspecialchars($formData['temapass2']) : ''; ?>">
                              <span class="datepicker-trigger" onclick="showDatePicker('temapass2')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="temapass2-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                            <input name="temasub2" type="text" class="subject-input"
                               value="<?php echo isset($formData['temasub2']) ? htmlspecialchars($formData['temasub2']) : ''; ?>"
                               placeholder="e.g., Business Administration, Economics">
                            <div class="subject-error" id="temasub2-error">Only alphabets and commas allowed</div>
                        </td>
                        <td>
                           <select name="temauni2" class="board-input">
                              <option value="" >Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         $selected = (isset($formData['temauni2']) && $formData['temauni2'] == $uni_id) ? 'selected' : '';
                                         echo '<option value="' . $uni_id . '" ' . $selected . '>' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tematot2" type="number" min="0" class="total-marks" value="<?php echo isset($formData['tematot2']) ? htmlspecialchars($formData['tematot2']) : '1000'; ?>" onchange="updateMaxObtainedMarks(); calculateDivision(this)"></td>
                        <td><input name="temaom2" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                           value="<?php echo isset($formData['temaom2']) ? htmlspecialchars($formData['temaom2']) : ''; ?>"></td>
                        <td><input name="temadiv2" type="text" class="division-grade" readonly
                           value="<?php echo isset($formData['temadiv2']) ? htmlspecialchars($formData['temadiv2']) : ''; ?>"></td>
                     </tr>
                     <!-- Master In Other Subject (2) -->
                     <tr>
                        <td>Master In Other Subject</td>
                        <td>
                           <div class="date-input-container">
                              <input id="temapass3" name="temapass3" type="text" class="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="<?php echo isset($formData['temapass3']) ? htmlspecialchars($formData['temapass3']) : ''; ?>">
                              <span class="datepicker-trigger" onclick="showDatePicker('temapass3')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="temapass3-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                            <input name="temasub3" type="text" class="subject-input"
                               value="<?php echo isset($formData['temasub3']) ? htmlspecialchars($formData['temasub3']) : ''; ?>"
                               placeholder="e.g., Psychology, Sociology">
                            <div class="subject-error" id="temasub3-error">Only alphabets and commas allowed</div>
                        </td>
                        <td>
                           <select name="temauni3" class="board-input">
                              <option value="" >Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         $selected = (isset($formData['temauni3']) && $formData['temauni3'] == $uni_id) ? 'selected' : '';
                                         echo '<option value="' . $uni_id . '" ' . $selected . '>' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tematot3" type="number" min="0" class="total-marks" value="<?php echo isset($formData['tematot3']) ? htmlspecialchars($formData['tematot3']) : '1000'; ?>" onchange="updateMaxObtainedMarks(); calculateDivision(this)"></td>
                        <td><input name="temaom3" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                           value="<?php echo isset($formData['temaom3']) ? htmlspecialchars($formData['temaom3']) : ''; ?>"></td>
                        <td><input name="temadiv3" type="text" class="division-grade" readonly
                           value="<?php echo isset($formData['temadiv3']) ? htmlspecialchars($formData['temadiv3']) : ''; ?>"></td>
                     </tr>
                     <!-- M.Phil -->
                     <tr>
                        <td>M.Phil</td>
                        <td>
                           <div class="date-input-container">
                              <input id="temphillpass" name="temphillpass" type="text" class="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="<?php echo isset($formData['temphillpass']) ? htmlspecialchars($formData['temphillpass']) : ''; ?>">
                              <span class="datepicker-trigger" onclick="showDatePicker('temphillpass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="temphillpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                            <input name="temphillsub" type="text" class="subject-input"
                               value="<?php echo isset($formData['temphillsub']) ? htmlspecialchars($formData['temphillsub']) : ''; ?>"
                               placeholder="e.g., Artificial Intelligence, Machine Learning">
                            <div class="subject-error" id="temphillsub-error">Only alphabets and commas allowed</div>
                        </td>
                        <td>
                           <select name="temphilluni" class="board-input">
                              <option value="" >Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         $selected = (isset($formData['temphilluni']) && $formData['temphilluni'] == $uni_id) ? 'selected' : '';
                                         echo '<option value="' . $uni_id . '" ' . $selected . '>' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="temphilltot" type="number" min="0" class="total-marks" value="<?php echo isset($formData['temphilltot']) ? htmlspecialchars($formData['temphilltot']) : '4'; ?>" onchange="updateMaxObtainedMarks(); calculateCGPA(this)"></td>
                        <td><input name="temphillom" type="number" min="0" max="4" step="0.01" class="obtained-marks" oninput="calculateCGPA(this)"
                           value="<?php echo isset($formData['temphillom']) ? htmlspecialchars($formData['temphillom']) : ''; ?>"></td>
                        <td><input name="temphilldiv" type="text" class="division-grade" readonly
                           value="<?php echo isset($formData['temphilldiv']) ? htmlspecialchars($formData['temphilldiv']) : ''; ?>"></td>
                     </tr>
                     <!-- Ph.D -->
                     <tr>
                        <td>Ph.D</td>
                        <td>
                           <div class="date-input-container">
                              <input id="tephdpass" name="tephdpass" type="text" class="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="<?php echo isset($formData['tephdpass']) ? htmlspecialchars($formData['tephdpass']) : ''; ?>">
                              <span class="datepicker-trigger" onclick="showDatePicker('tephdpass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="tephdpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                            <input name="tephdsub" type="text" class="subject-input"
                               value="<?php echo isset($formData['tephdsub']) ? htmlspecialchars($formData['tephdsub']) : ''; ?>"
                               placeholder="e.g., Data Analytics, Cybersecurity">
                            <div class="subject-error" id="tephdsub-error">Only alphabets and commas allowed</div>
                        </td>
                        <td>
                           <select name="tephduni" class="board-input">
                              <option value="" >Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         $selected = (isset($formData['tephduni']) && $formData['tephduni'] == $uni_id) ? 'selected' : '';
                                         echo '<option value="' . $uni_id . '" ' . $selected . '>' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="tephdtot" type="number" min="0" class="total-marks" value="<?php echo isset($formData['tephdtot']) ? htmlspecialchars($formData['tephdtot']) : '4'; ?>" onchange="updateMaxObtainedMarks(); calculateCGPA(this)"></td>
                        <td><input name="tephdom" type="number" min="0" max="4" step="0.01" class="obtained-marks" oninput="calculateCGPA(this)"
                           value="<?php echo isset($formData['tephdom']) ? htmlspecialchars($formData['tephdom']) : ''; ?>"></td>
                        <td><input name="tephddiv" type="text" class="division-grade" readonly
                           value="<?php echo isset($formData['tephddiv']) ? htmlspecialchars($formData['tephddiv']) : ''; ?>"></td>
                     </tr>
                     <!-- Other -->
                     <tr>
                        <td>Other</td>
                        <td>
                           <div class="date-input-container">
                              <input id="teotherpass" name="teotherpass" type="text" class="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="<?php echo isset($formData['teotherpass']) ? htmlspecialchars($formData['teotherpass']) : ''; ?>">
                              <span class="datepicker-trigger" onclick="showDatePicker('teotherpass')">
                              <i class="fas fa-calendar-alt"></i>
                              </span>
                           </div>
                           <div id="teotherpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                        </td>
                        <td>
                            <input name="teothersub" type="text" class="subject-input"
                               value="<?php echo isset($formData['teothersub']) ? htmlspecialchars($formData['teothersub']) : ''; ?>"
                               placeholder="e.g., Professional Certification, Specialization">
                            <div class="subject-error" id="teothersub-error">Only alphabets and commas allowed</div>
                        </td>
                        <td>
                           <select name="teotheruni" class="board-input">
                              <option value="" >Select Board/University</option>
                              <?php
                                 // Database connection (assuming $conn is already established)
                                 
                                 // Fetch active universities ordered by name
                                 $sql = "SELECT uni_id, uni_name, uni_location FROM universities WHERE status = 1 ORDER by uni_name ASC";
                                 $result = $conn->query($sql);
                                 
                                 if ($result && $result->num_rows > 0) {
                                     while ($row = $result->fetch_assoc()) {
                                         $uni_id = htmlspecialchars($row['uni_id']);
                                         $uni_name = htmlspecialchars($row['uni_name']);
                                         $uni_location = htmlspecialchars($row['uni_location']);
                                         $selected = (isset($formData['teotheruni']) && $formData['teotheruni'] == $uni_id) ? 'selected' : '';
                                         echo '<option value="' . $uni_id . '" ' . $selected . '>' . $uni_name . ' - ' . $uni_location . '</option>';
                                     }
                                 }
                                 ?>
                           </select>
                        </td>
                        <td><input name="teothertot" type="number" min="0" class="total-marks" value="<?php echo isset($formData['teothertot']) ? htmlspecialchars($formData['teothertot']) : ''; ?>" onchange="updateMaxObtainedMarks(); calculateDivision(this)"></td>
                        <td><input name="teotherom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                           value="<?php echo isset($formData['teotherom']) ? htmlspecialchars($formData['teotherom']) : ''; ?>"></td>
                        <td><input name="teotherdiv" type="text" class="division-grade" readonly
                           value="<?php echo isset($formData['teotherdiv']) ? htmlspecialchars($formData['teotherdiv']) : ''; ?>"></td>
                     </tr>
                  </tbody>
               </table>
            
            <!-- In emp2.php, update the back button -->
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="goBackToStep1()">
                    <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>
        </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>
        // SIMPLE SOLUTION: Update max attribute for obtained marks based on total marks
        function updateMaxObtainedMarks() {
            // Get all rows in the table
            const rows = document.querySelectorAll('tbody tr');
            
            rows.forEach(row => {
                const totalMarksInput = row.querySelector('.total-marks');
                const obtainedMarksInput = row.querySelector('.obtained-marks');
                
                if (totalMarksInput && obtainedMarksInput) {
                    const totalMarks = parseFloat(totalMarksInput.value) || 0;
                    // Set max attribute to total marks value
                    obtainedMarksInput.max = totalMarks;
                }
            });
        }

        // Function to validate subject input (only alphabets and commas)
        function validateSubjectInput(input) {
            const value = input.value;
            const errorElement = document.getElementById(input.id + '-error');
            
            // Regular expression to allow only alphabets, spaces, and commas
            const subjectPattern = /^[a-zA-Z\s,]*$/;
            
            if (value && !subjectPattern.test(value)) {
                // Invalid characters found
                input.classList.add('invalid');
                if (errorElement) {
                    errorElement.style.display = 'block';
                }
                return false;
            } else {
                // Valid input
                input.classList.remove('invalid');
                if (errorElement) {
                    errorElement.style.display = 'none';
                }
                return true;
            }
        }

        // Function to restrict subject input to alphabets and commas only
        function restrictSubjectInput(event) {
            const key = event.key;
            
            // Allow: backspace, delete, tab, escape, enter, comma, and space
            if ([
                'Backspace', 'Delete', 'Tab', 'Escape', 'Enter', 
                ',', ' ', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'
            ].includes(key)) {
                return;
            }
            
            // Allow Ctrl/Command + A, C, V, X
            if (event.ctrlKey || event.metaKey) {
                if (['a', 'c', 'v', 'x'].includes(key.toLowerCase())) {
                    return;
                }
            }
            
            // Only allow alphabets
            if (!/^[a-zA-Z]$/.test(key)) {
                event.preventDefault();
            }
        }

        // Function to validate date is not in future
        function validateDateNotFuture(input) {
            const errorElement = document.getElementById(input.id + '-error');
            const value = input.value.trim();
            
            if (!value) {
                if (errorElement) errorElement.style.display = 'none';
                input.setCustomValidity('');
                return true;
            }
            
            const datePattern = /^(\d{2})-(\d{2})-(\d{4})$/;
            if (!datePattern.test(value)) {
                if (errorElement) {
                    errorElement.textContent = "Invalid date format (DD-MM-YYYY)";
                    errorElement.style.display = 'block';
                }
                input.style.borderColor = '#e74c3c';
                input.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
                input.setCustomValidity('Please enter date in DD-MM-YYYY format');
                return false;
            }
            
            const parts = value.split('-');
            const day = parseInt(parts[0], 10);
            const month = parseInt(parts[1], 10) - 1;
            const year = parseInt(parts[2], 10);
            
            const inputDate = new Date(year, month, day);
            if (isNaN(inputDate.getTime()) || 
                inputDate.getDate() !== day || 
                inputDate.getMonth() !== month || 
                inputDate.getFullYear() !== year) {
                if (errorElement) {
                    errorElement.textContent = "Invalid date!";
                    errorElement.style.display = 'block';
                }
                input.style.borderColor = '#e74c3c';
                input.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
                input.setCustomValidity('Invalid date');
                return false;
            }
            
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            
            if (inputDate > today) {
                if (errorElement) {
                    errorElement.textContent = "Date cannot be in the future!";
                    errorElement.style.display = 'block';
                }
                input.style.borderColor = '#e74c3c';
                input.style.boxShadow = '0 0 0 2px rgba(231, 76, 60, 0.2)';
                input.setCustomValidity('Date cannot be in the future');
                return false;
            }
            
            if (errorElement) errorElement.style.display = 'none';
            input.style.borderColor = '';
            input.style.boxShadow = '';
            input.setCustomValidity('');
            return true;
        }

        // Initialize datepickers with future date restriction
        function initializeDatePickers() {
            $('.date-field').datepicker({
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true,
                yearRange: '-50:+0',
                maxDate: 0, // This prevents future date selection
                showOtherMonths: true,
                selectOtherMonths: true,
                beforeShowDay: function(date) {
                    var today = new Date();
                    today.setHours(0, 0, 0, 0);
                    return [date <= today, ""];
                },
                onSelect: function(dateText, inst) {
                    const errorElement = document.getElementById(this.id + '-error');
                    if (errorElement) errorElement.style.display = 'none';
                    
                    // Validate the selected date is not in future
                    validateDateNotFuture(this);
                },
                onClose: function(dateText, inst) {
                    validateDateNotFuture(this);
                }
            }).on('keydown', function(e) {
                if (e.keyCode === 13) {
                    $(this).datepicker('hide');
                    validateDateNotFuture(this);
                    e.preventDefault();
                    return false;
                }
            }).on('blur', function() {
                validateDateNotFuture(this);
            });
        }

function showDatePicker(fieldId) {
    const $field = $('#' + fieldId);
    
    // If datepicker isn't initialized, initialize it first
    if (!$field.data('hasDatepicker')) {
        initializeDatePickers();
    }
    
    // Small delay to ensure initialization is complete
    setTimeout(function() {
        $field.datepicker('show');
    }, 50);
}

        // Academic Qualifications Validation with marks restriction
        function calculateDivision(inputElement) {
			const row = inputElement.closest('tr');
			const totalMarksInput = row.querySelector('.total-marks');
			
			// Determine which input triggered the calculation
			let obtainedMarksInput;
			if (inputElement.classList.contains('obtained-marks')) {
				obtainedMarksInput = inputElement;
			} else {
				obtainedMarksInput = row.querySelector('.obtained-marks');
			}
			
			const divisionInput = row.querySelector('.division-grade');
			
			const totalMarks = parseFloat(totalMarksInput.value) || 0;
			
			// Check if obtained marks is empty FIRST
			if (!obtainedMarksInput.value.trim()) {
				divisionInput.value = '';
				return;
			}
			
			const obtainedMarks = parseFloat(obtainedMarksInput.value) || 0;
			
			// SIMPLE VALIDATION: Check if obtained marks exceed total marks
			if (obtainedMarks > totalMarks) {
				// Auto-correct to maximum allowed value
				obtainedMarksInput.value = totalMarks;
				// Recalculate with corrected value
				calculateDivision(obtainedMarksInput);
				return;
			}
			
			if (totalMarks <= 0 || obtainedMarks < 0) {
				divisionInput.value = '';
				return;
			}
			
			const percentage = (obtainedMarks / totalMarks) * 100;
			
			// Pakistani Grading System
			if (percentage >= 80) {
				divisionInput.value = "A+ (1st Division with Distinction)";
			} 
			
			else if (percentage >= 70) {
				divisionInput.value = "A (1st Division)";
			} 
			
			else if (percentage >= 60) {
				divisionInput.value = "B (1st Division)";
			} 
			
			else if (percentage >= 45) {
				divisionInput.value = "C (2nd Division)";
			} 
			
			else if (percentage >= 40) {
				divisionInput.value = "D (3rd Division)";
			} 
			
			else if (percentage >= 33) {
				divisionInput.value = "E (3rd Division)";
			}
			
			else {
				divisionInput.value = "F (Fail)";
			}
		}
        
        // For CGPA-based degrees (M.Phil, PhD) with CGPA restriction
		function calculateCGPA(inputElement) {
			const row = inputElement.closest('tr');
			const divisionInput = row.querySelector('.division-grade');
			
			// Check if CGPA is empty FIRST
			if (!inputElement.value.trim()) {
				divisionInput.value = '';
				return;
			}
			
			const cgpa = parseFloat(inputElement.value) || 0;
			
			// For CGPA, max is usually 4.0
			if (cgpa > 4.0) {
				inputElement.value = 4.0;
				calculateCGPA(inputElement);
				return;
			}
			
			if (cgpa >= 3.67) {
				divisionInput.value = "A+ (Excellent)";
			} else if (cgpa >= 3.33) {
				divisionInput.value = "A (Very Good)";
			} else if (cgpa >= 3.00) {
				divisionInput.value = "B+ (Good)";
			} else if (cgpa >= 2.67) {
				divisionInput.value = "B (Satisfactory)";
			} else if (cgpa >= 2.33) {
				divisionInput.value = "C+ (Pass)";
			} else if (cgpa >= 2.00) {
				divisionInput.value = "C (Minimum Pass)";
			} else {
				divisionInput.value = "F (Fail)";
			}
		}
        
        // Add this function to validate chronological order
        function checkChronologicalOrder() {
            const qualificationDates = [
                { id: 'tesscpass', level: 'Matric', date: document.querySelector('input[name="tesscpass"]').value },
                { id: 'tehscpass', level: 'Intermediate', date: document.querySelector('input[name="tehscpass"]').value },
                { id: 'tebspass', level: 'Bachelor', date: document.querySelector('input[name="tebspass"]').value },
                { id: 'temapass', level: 'Master', date: document.querySelector('input[name="temapass"]').value },
                { id: 'temapass2', level: 'Master 2', date: document.querySelector('input[name="temapass2"]').value },
                { id: 'temapass3', level: 'Master 3', date: document.querySelector('input[name="temapass3"]').value },
                { id: 'temphillpass', level: 'M.Phil', date: document.querySelector('input[name="temphillpass"]').value },
                { id: 'tephdpass', level: 'Ph.D', date: document.querySelector('input[name="tephdpass"]').value },
                { id: 'teotherpass', level: 'Other', date: document.querySelector('input[name="teotherpass"]').value }
            ];

            // Convert DD-MM-YYYY to YYYYMMDD for comparison
            function parseDate(dateStr) {
                if (!dateStr) return null;
                const parts = dateStr.split('-');
                if (parts.length !== 3) return null;
                return parseInt(parts[2] + parts[1] + parts[0]);
            }

            let previousDate = 0;
            let previousLevel = '';
            let outOfOrderQualifications = [];

            for (let qual of qualificationDates) {
                if (qual.date) {
                    const currentDate = parseDate(qual.date);
                    
                    if (currentDate) {
                        if (currentDate < previousDate && previousDate !== 0) {
                            outOfOrderQualifications.push({
                                level: qual.level,
                                date: qual.date,
                                previousLevel: previousLevel
                            });
                        }
                        previousDate = currentDate;
                        previousLevel = qual.level;
                    }
                }
            }

            return outOfOrderQualifications;
        }

        // ACADEMIC QUALIFICATIONS VALIDATION - All qualifications must be complete if started
	function validateAcademicQualifications() {
		let isValid = true;
		
		// Get ALL qualification rows including Matric and Intermediate
		const qualifications = [
			// Matric (Secondary Certificate) - REQUIRED but with "if started must complete" logic
			{
				name: 'Matric (Secondary Certificate)',
				date: document.getElementsByName('tesscpass')[0],
				subject: document.getElementsByName('tesscsub')[0],
				institution: document.getElementsByName('tesscuni')[0],
				totalMarks: document.getElementsByName('tessctot')[0],
				obtainedMarks: document.getElementsByName('tesscom')[0],
				division: document.getElementsByName('tesscdiv')[0],
				isPredefined: true,
				isRequired: true
			},
			// Intermediate (Higher Secondary Certificate) - REQUIRED but with "if started must complete" logic
			{
				name: 'Intermediate (Higher Secondary Certificate)',
				date: document.getElementsByName('tehscpass')[0],
				subject: document.getElementsByName('tehscsub')[0],
				institution: document.getElementsByName('tehscuni')[0],
				totalMarks: document.getElementsByName('tehsctot')[0],
				obtainedMarks: document.getElementsByName('tehscom')[0],
				division: document.getElementsByName('tehscdiv')[0],
				isPredefined: true,
				isRequired: true
			},
			// B.A/B.Sc/BS (OPTIONAL)
			{
				name: 'B.A/B.Sc/BS',
				date: document.getElementsByName('tebspass')[0],
				subject: document.getElementsByName('tebssub')[0],
				institution: document.getElementsByName('tebsuni')[0],
				totalMarks: document.getElementsByName('tebstot')[0],
				obtainedMarks: document.getElementsByName('tebsom')[0],
				division: document.getElementsByName('tebsdiv')[0],
				isPredefined: true,
				isRequired: false
			},
			// M.A/M.Sc/MCS (OPTIONAL)
			{
				name: 'M.A/M.Sc/MCS',
				date: document.getElementsByName('temapass')[0],
				subject: document.getElementsByName('temasub')[0],
				institution: document.getElementsByName('temauni')[0],
				totalMarks: document.getElementsByName('tematot')[0],
				obtainedMarks: document.getElementsByName('temaom')[0],
				division: document.getElementsByName('temadiv')[0],
				isPredefined: true,
				isRequired: false
			},
			// Master In Other Subject (1) (OPTIONAL)
			{
				name: 'Master In Other Subject (1)',
				date: document.getElementsByName('temapass2')[0],
				subject: document.getElementsByName('temasub2')[0],
				institution: document.getElementsByName('temauni2')[0],
				totalMarks: document.getElementsByName('tematot2')[0],
				obtainedMarks: document.getElementsByName('temaom2')[0],
				division: document.getElementsByName('temadiv2')[0],
				isPredefined: true,
				isRequired: false
			},
			// Master In Other Subject (2) (OPTIONAL)
			{
				name: 'Master In Other Subject (2)',
				date: document.getElementsByName('temapass3')[0],
				subject: document.getElementsByName('temasub3')[0],
				institution: document.getElementsByName('temauni3')[0],
				totalMarks: document.getElementsByName('tematot3')[0],
				obtainedMarks: document.getElementsByName('temaom3')[0],
				division: document.getElementsByName('temadiv3')[0],
				isPredefined: true,
				isRequired: false
			},
			// M.Phil (OPTIONAL)
			{
				name: 'M.Phil',
				date: document.getElementsByName('temphillpass')[0],
				subject: document.getElementsByName('temphillsub')[0],
				institution: document.getElementsByName('temphilluni')[0],
				totalMarks: document.getElementsByName('temphilltot')[0],
				obtainedMarks: document.getElementsByName('temphillom')[0],
				division: document.getElementsByName('temphilldiv')[0],
				isPredefined: true,
				isRequired: false
			},
			// Ph.D (OPTIONAL)
			{
				name: 'Ph.D',
				date: document.getElementsByName('tephdpass')[0],
				subject: document.getElementsByName('tephdsub')[0],
				institution: document.getElementsByName('tephduni')[0],
				totalMarks: document.getElementsByName('tephdtot')[0],
				obtainedMarks: document.getElementsByName('tephdom')[0],
				division: document.getElementsByName('tephddiv')[0],
				isPredefined: true,
				isRequired: false
			},
			// Other (OPTIONAL)
			{
				name: 'Other',
				date: document.getElementsByName('teotherpass')[0],
				subject: document.getElementsByName('teothersub')[0],
				institution: document.getElementsByName('teotheruni')[0],
				totalMarks: document.getElementsByName('teothertot')[0],
				obtainedMarks: document.getElementsByName('teotherom')[0],
				division: document.getElementsByName('teotherdiv')[0],
				isPredefined: true,
				isRequired: false
			}
		];

		// Validate subject fields first
		const subjectFields = document.querySelectorAll('.subject-input');
		let subjectValidationPassed = true;

		for (let field of subjectFields) {
			if (field.value && !validateSubjectInput(field)) {
				subjectValidationPassed = false;
				field.focus();
				break;
			}
		}

		if (!subjectValidationPassed) {
			alert('Please correct the subject fields. Only alphabets and commas are allowed.');
			return false;
		}

		// Validate date format for all .date-field inputs
		const dateFields = document.querySelectorAll('.date-field');
		const datePattern = /^\d{2}-\d{2}-\d{4}$/;

		for (let field of dateFields) {
			if (field.value && !datePattern.test(field.value)) {
				alert('Please enter dates in DD-MM-YYYY format.');
				field.focus();
				return false;
			}
			
			// Validate that date is not in future
			if (field.value && !validateDateNotFuture(field)) {
				alert('Please correct the date that appears to be in the future.');
				field.focus();
				return false;
			}
		}

		// Track if required qualifications are complete
		let hasMatric = false;
		let hasIntermediate = false;
		let requiredQualificationsMissing = [];

		// Validate each qualification
		for (let i = 0; i < qualifications.length; i++) {
			const qual = qualifications[i];
			const hasDate = qual.date.value.trim() !== '';
			const hasSubject = qual.subject.value.trim() !== '';
			const hasInstitution = qual.institution.value !== '';
			const hasTotalMarks = qual.totalMarks.value.trim() !== '';
			const hasObtainedMarks = qual.obtainedMarks.value.trim() !== '';
			const hasDivision = qual.division.value.trim() !== '';
			
			// Check if any user-entered field is filled (for "if started" logic)
			const hasUserEnteredData = hasDate || hasSubject || hasInstitution || hasObtainedMarks || hasDivision;
			
			// For required qualifications (Matric and Intermediate), check if they are started
			if (qual.isRequired && hasUserEnteredData) {
				// Mark as having this qualification
				if (qual.name.includes('Matric')) hasMatric = true;
				if (qual.name.includes('Intermediate')) hasIntermediate = true;
				
				// Check if all fields are filled
				let missingFields = [];
				
				if (!hasDate) missingFields.push('Date');
				if (!hasSubject) missingFields.push('Subject');
				if (!hasInstitution) missingFields.push('Institution');
				if (!hasObtainedMarks) missingFields.push('Obtained Marks');
				if (!hasDivision) missingFields.push('Division');
				
				if (missingFields.length > 0) {
					isValid = false;
					alert(`ERROR: ${qual.name} is partially filled.\n\nPlease complete all fields for this REQUIRED qualification:\n• ${missingFields.join('\n• ')}`);
					return false;
				}
			}
			// For optional qualifications, apply "if started must complete" logic
			else if (!qual.isRequired && hasUserEnteredData) {
				// Check if all fields are filled
				let missingFields = [];
				
				if (!hasDate) missingFields.push('Date');
				if (!hasSubject) missingFields.push('Subject');
				if (!hasInstitution) missingFields.push('Institution');
				if (!hasObtainedMarks) missingFields.push('Obtained Marks');
				if (!hasDivision) missingFields.push('Division');
				
				if (missingFields.length > 0) {
					isValid = false;
					alert(`ERROR: ${qual.name} is partially filled.\n\nPlease complete all fields for this qualification:\n• ${missingFields.join('\n• ')}\n\nOR remove all entries for this qualification.`);
					return false;
				}
			}
			
			// Validate marks for completed qualifications
			if (hasObtainedMarks && hasTotalMarks) {
				const totalMarks = parseFloat(qual.totalMarks.value) || 0;
				const obtainedMarks = parseFloat(qual.obtainedMarks.value) || 0;
				
				if (obtainedMarks > totalMarks) {
					isValid = false;
					alert(`ERROR: Invalid marks in ${qual.name}.\n\nObtained marks (${obtainedMarks}) cannot be greater than total marks (${totalMarks}).`);
					qual.obtainedMarks.focus();
					return false;
				}
				
				if (obtainedMarks < 0) {
					isValid = false;
					alert(`ERROR: Invalid marks in ${qual.name}.\n\nObtained marks must be a positive value.`);
					qual.obtainedMarks.focus();
					return false;
				}
			}
		}

		// Check if required qualifications are missing (if they were started)
		if (!hasMatric) {
			requiredQualificationsMissing.push('Matric');
		}
		if (!hasIntermediate) {
			requiredQualificationsMissing.push('Intermediate');
		}
		
		if (requiredQualificationsMissing.length > 0) {
			const proceed = confirm(`WARNING: The following REQUIRED qualifications are not filled:\n• ${requiredQualificationsMissing.join('\n• ')}\nMatric and Intermediate are minimum requirements for employment.\nDo you want to proceed without these required qualifications?`);
			if (!proceed) {
				return false;
			}
		}

		// Check chronological order
		const outOfOrder = checkChronologicalOrder();
		if (outOfOrder.length > 0) {
			let alertMessage = "Qualifications are not in chronological order:\n\n";
			
			outOfOrder.forEach(qual => {
				alertMessage += `- ${qual.level} (${qual.date}) appears to be before ${qual.previousLevel}\n`;
			});
			
			alertMessage += "\nPlease correct the dates to ensure qualifications are in chronological order (Matric → Intermediate → Higher levels).";
			
			if (!confirm(alertMessage + "\n\nContinue anyway?")) {
				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 goBackToStep1() {
			// Save current form data via AJAX first
			const formData = new FormData(document.getElementById('teacherForm'));
			
			// ✅ ADD THIS LINE - Include the step parameter
			formData.append('step', '2');
			
			fetch('save_emp_step_data.php', {
				method: 'POST',
				body: formData
			}).then(response => response.json())
			  .then(data => {
				  if (data.success) {
					  window.location.href = 'emp1.php?back=1';
				  } else {
					  alert('Error saving data: ' + data.message);
					  window.location.href = 'emp1.php?back=1';
				  }
			  }).catch(() => {
				  // Even if save fails, still go back
				  window.location.href = 'emp1.php?back=1';
			  });
		}

        // Initialize when document is ready
        document.addEventListener('DOMContentLoaded', function() {
            <?php
            // Pre-fill form with saved data
            foreach ($formData as $field => $value) {
                if ($field !== 'csrf_token' && $field !== 'step_2') {
                    echo "if(document.querySelector('[name=\"$field\"]')) document.querySelector('[name=\"$field\"]').value = '" . addslashes($value) . "';";
                }
            }
            ?>
            
            // Initialize datepickers
            initializeDatePickers();
            
            // Initialize max attributes for obtained marks
            updateMaxObtainedMarks();
            
            // Add event listeners to total marks inputs to update max attributes
            const totalMarksInputs = document.querySelectorAll('.total-marks');
            totalMarksInputs.forEach(input => {
                input.addEventListener('input', updateMaxObtainedMarks);
                input.addEventListener('change', updateMaxObtainedMarks);
            });
            
            // Add event listeners to subject inputs
            const subjectInputs = document.querySelectorAll('.subject-input');
            subjectInputs.forEach(input => {
                // Restrict input on key press
                input.addEventListener('keydown', restrictSubjectInput);
                
                // Validate on blur
                input.addEventListener('blur', function() {
                    validateSubjectInput(this);
                });
                
                // Validate on input (for paste operations)
                input.addEventListener('input', function() {
                    validateSubjectInput(this);
                });
            });
        });
    </script>
</body>
</html>