<!-- 
**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 third file (emp3.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 = 3;
$nextFile = 'emp4.php';
$previousFile = 'emp2.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 3: Professional Qualifications</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 emp2.php */
        :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>
</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 3/7</h1>
        </div>
        <div class="progress-container">
            <div class="progress-bar" id="progressBar" style="width: 33.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 active" 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 validateProfessionalQualifications()">
			<!-- ✅ Use $currentToken instead of directly accessing $_SESSION -->
			<input type="hidden" name="csrf_token" value="<?php echo $currentToken; ?>">
			<input type="hidden" name="step_3" value="1">
            

            <!-- Step 3: Professional Qualifications -->
            <div class="form-step active" id="step-3">
                <h2 class="section-title"><i class="fas fa-certificate"></i> Professional 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>Note: Filling professional qualifications is 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.</strong></li>
                    </ul>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>Degree Name</th>
                            <th>Result Declaration Date</th>
                            <th>Institution</th>
                            <th>Total Marks</th>
                            <th>Obtained Marks</th>
                            <th>Grade/Division</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- PT/CT -->
                        <tr>
                            <td>PT/CT</td>
                            <td>
                                <div class="date-input-container">
                                    <input id="teptpass" name="teptpass" 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['teptpass']) ? htmlspecialchars($formData['teptpass']) : ''; ?>">
                                    <span class="datepicker-trigger" onclick="showDatePicker('teptpass')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="teptpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <select name="teptis" class="board-input">
                                    <option value="" >Select Board/University</option>
                                    <?php
                                    // Fetch universities from database
                                    $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()) {
                                            $selected = (isset($formData['teptis']) && $formData['teptis'] == $row['uni_id']) ? 'selected' : '';
                                            echo '<option value="' . $row['uni_id'] . '" ' . $selected . '>' . $row['uni_name'] . ' - ' . $row['uni_location'] . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                            </td>
                            <td><input name="tepttot" type="number" class="total-marks" value="<?php echo isset($formData['tepttot']) ? htmlspecialchars($formData['tepttot']) : '1000'; ?>" min="1" onchange="updateMaxObtainedMarks(); calculateDivision(this)"></td>
                            <td><input name="teptom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                                value="<?php echo isset($formData['teptom']) ? htmlspecialchars($formData['teptom']) : ''; ?>"></td>
                            <td><input name="teptdiv" type="text" class="division-grade" readonly
                                value="<?php echo isset($formData['teptdiv']) ? htmlspecialchars($formData['teptdiv']) : ''; ?>"></td>
                        </tr>
                        <!-- B.Ed/BS.Ed -->
                        <tr>
                            <td>B.Ed/BS.Ed</td>
                            <td>
                                <div class="date-input-container">
                                    <input id="tebedpass" name="tebedpass" 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['tebedpass']) ? htmlspecialchars($formData['tebedpass']) : ''; ?>">
                                    <span class="datepicker-trigger" onclick="showDatePicker('tebedpass')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="tebedpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <select name="tebedis" class="board-input">
                                    <option value="" >Select Board/University</option>
                                    <?php
                                    // Fetch universities from database
                                    $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()) {
                                            $selected = (isset($formData['tebedis']) && $formData['tebedis'] == $row['uni_id']) ? 'selected' : '';
                                            echo '<option value="' . $row['uni_id'] . '" ' . $selected . '>' . $row['uni_name'] . ' - ' . $row['uni_location'] . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                            </td>
                            <td><input name="tebedtot" type="number" class="total-marks" value="<?php echo isset($formData['tebedtot']) ? htmlspecialchars($formData['tebedtot']) : '1000'; ?>" min="1" onchange="updateMaxObtainedMarks(); calculateDivision(this)"></td>
                            <td><input name="tebedom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                                value="<?php echo isset($formData['tebedom']) ? htmlspecialchars($formData['tebedom']) : ''; ?>"></td>
                            <td><input name="tebeddiv" type="text" class="division-grade" readonly
                                value="<?php echo isset($formData['tebeddiv']) ? htmlspecialchars($formData['tebeddiv']) : ''; ?>"></td>
                        </tr>
                        <!-- M.Ed/M.A Education -->
                        <tr>
                            <td>M.Ed/M.A Education</td>
                            <td>
                                <div class="date-input-container">
                                    <input id="temedpass" name="temedpass" 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['temedpass']) ? htmlspecialchars($formData['temedpass']) : ''; ?>">
                                    <span class="datepicker-trigger" onclick="showDatePicker('temedpass')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="temedpass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <select name="temedis" class="board-input">
                                    <option value="" >Select Board/University</option>
                                    <?php
                                    // Fetch universities from database
                                    $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()) {
                                            $selected = (isset($formData['temedis']) && $formData['temedis'] == $row['uni_id']) ? 'selected' : '';
                                            echo '<option value="' . $row['uni_id'] . '" ' . $selected . '>' . $row['uni_name'] . ' - ' . $row['uni_location'] . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                            </td>
                            <td><input name="temedtot" type="number" class="total-marks" value="<?php echo isset($formData['temedtot']) ? htmlspecialchars($formData['temedtot']) : '1000'; ?>" min="1" onchange="updateMaxObtainedMarks(); calculateDivision(this)"></td>
                            <td><input name="temedom" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                                value="<?php echo isset($formData['temedom']) ? htmlspecialchars($formData['temedom']) : ''; ?>"></td>
                            <td><input name="temeddiv" type="text" class="division-grade" readonly
                                value="<?php echo isset($formData['temeddiv']) ? htmlspecialchars($formData['temeddiv']) : ''; ?>"></td>
                        </tr>
                        <!-- Other Qualification 1 -->
                        <tr>
                            <td><input name="teo1name" type="text" placeholder="Other Qualification" class="degree-input"
                                value="<?php echo isset($formData['teo1name']) ? htmlspecialchars($formData['teo1name']) : ''; ?>"></td>
                            <td>
                                <div class="date-input-container">
                                    <input id="teo1pass" name="teo1pass" 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['teo1pass']) ? htmlspecialchars($formData['teo1pass']) : ''; ?>">

                                    <span class="datepicker-trigger" onclick="showDatePicker('teo1pass')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="teo1pass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <select name="teo1is" class="institution-input">
                                    <option value="" >Select Board/University</option>
                                    <?php
                                    // Fetch universities from database
                                    $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()) {
                                            $selected = (isset($formData['teo1is']) && $formData['teo1is'] == $row['uni_id']) ? 'selected' : '';
                                            echo '<option value="' . $row['uni_id'] . '" ' . $selected . '>' . $row['uni_name'] . ' - ' . $row['uni_location'] . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                            </td>
                            <td><input name="teo1tot" type="number" class="total-marks" min="1" onchange="updateMaxObtainedMarks(); calculateDivision(this)"
                                value="<?php echo isset($formData['teo1tot']) ? htmlspecialchars($formData['teo1tot']) : ''; ?>"></td>
                            <td><input name="teo1om" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                                value="<?php echo isset($formData['teo1om']) ? htmlspecialchars($formData['teo1om']) : ''; ?>"></td>
                            <td><input name="teo1div" type="text" class="division-grade" readonly
                                value="<?php echo isset($formData['teo1div']) ? htmlspecialchars($formData['teo1div']) : ''; ?>"></td>
                        </tr>
                        <!-- Other Qualification 2 -->
                        <tr>
                            <td><input name="teo2name" type="text" placeholder="Other Qualification" class="degree-input"
                                value="<?php echo isset($formData['teo2name']) ? htmlspecialchars($formData['teo2name']) : ''; ?>"></td>
                            <td>
                                <div class="date-input-container">
                                    <input id="teo2pass" name="teo2pass" 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['teo2pass']) ? htmlspecialchars($formData['teo2pass']) : ''; ?>">
                                    <span class="datepicker-trigger" onclick="showDatePicker('teo2pass')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="teo2pass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <select name="teo2is" class="institution-input">
                                    <option value="" >Select Board/University</option>
                                    <?php
                                    // Fetch universities from database
                                    $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()) {
                                            $selected = (isset($formData['teo2is']) && $formData['teo2is'] == $row['uni_id']) ? 'selected' : '';
                                            echo '<option value="' . $row['uni_id'] . '" ' . $selected . '>' . $row['uni_name'] . ' - ' . $row['uni_location'] . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                            </td>
                            <td><input name="teo2tot" type="number" class="total-marks" min="1" onchange="updateMaxObtainedMarks(); calculateDivision(this)"
                                value="<?php echo isset($formData['teo2tot']) ? htmlspecialchars($formData['teo2tot']) : ''; ?>"></td>
                            <td><input name="teo2om" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                                value="<?php echo isset($formData['teo2om']) ? htmlspecialchars($formData['teo2om']) : ''; ?>"></td>
                            <td><input name="teo2div" type="text" class="division-grade" readonly
                                value="<?php echo isset($formData['teo2div']) ? htmlspecialchars($formData['teo2div']) : ''; ?>"></td>
                        </tr>
                        <!-- Other Qualification 3 -->
                        <tr>
                            <td><input name="teo3name" type="text" placeholder="Other Qualification" class="degree-input"
                                value="<?php echo isset($formData['teo3name']) ? htmlspecialchars($formData['teo3name']) : ''; ?>"></td>
                            <td>
                                <div class="date-input-container">
                                    <input id="teo3pass" name="teo3pass" 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['teo3pass']) ? htmlspecialchars($formData['teo3pass']) : ''; ?>">
                                    <span class="datepicker-trigger" onclick="showDatePicker('teo3pass')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="teo3pass-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <select name="teo3is" class="institution-input">
                                    <option value="" >Select Board/University</option>
                                    <?php
                                    // Fetch universities from database
                                    $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()) {
                                            $selected = (isset($formData['teo3is']) && $formData['teo3is'] == $row['uni_id']) ? 'selected' : '';
                                            echo '<option value="' . $row['uni_id'] . '" ' . $selected . '>' . $row['uni_name'] . ' - ' . $row['uni_location'] . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                            </td>
                            <td><input name="teo3tot" type="number" class="total-marks" min="1" onchange="updateMaxObtainedMarks(); calculateDivision(this)"
                                value="<?php echo isset($formData['teo3tot']) ? htmlspecialchars($formData['teo3tot']) : ''; ?>"></td>
                            <td><input name="teo3om" type="number" min="0" class="obtained-marks" oninput="calculateDivision(this)"
                                value="<?php echo isset($formData['teo3om']) ? htmlspecialchars($formData['teo3om']) : ''; ?>"></td>
                            <td><input name="teo3div" type="text" class="division-grade" readonly
                                value="<?php echo isset($formData['teo3div']) ? htmlspecialchars($formData['teo3div']) : ''; ?>"></td>
                        </tr>
                    </tbody>
                </table>
                

                <!-- Form Actions -->
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="goBackToStep2()">
                        <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 3
        document.addEventListener('DOMContentLoaded', function() {
            <?php
            // Pre-fill form with saved data
            foreach ($formData as $field => $value) {
                if ($field !== 'csrf_token' && $field !== 'step_3') {
                    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'
            });
            
            // Initialize max attributes for obtained marks
            updateMaxObtainedMarks();
        });

        // 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) || 1000;
                    // Set max attribute to total marks value
                    obtainedMarksInput.max = totalMarks;
                }
            });
        }

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

        // Division calculation function with simple validation
			function calculateDivision(inputElement) {
				const row = inputElement.closest('tr');
				const totalMarksInput = row.querySelector('.total-marks');
				const obtainedMarksInput = row.querySelector('.obtained-marks');
				const divisionInput = row.querySelector('.division-grade');
				
				const totalMarks = parseFloat(totalMarksInput.value) || 0;
				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;
				}
				
				// If obtained marks is empty, clear division
				if (!obtainedMarksInput.value.trim()) {
					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)";
			}
		}

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

// Professional Qualifications Validation - OPTIONAL but must be complete if started
function validateProfessionalQualifications() {
    let isValid = true;
    
    // Get all qualification rows
    const qualifications = [
        // PT/CT
        {
            name: 'PT/CT',
            date: document.getElementsByName('teptpass')[0],
            institution: document.getElementsByName('teptis')[0],
            totalMarks: document.getElementsByName('tepttot')[0],
            obtainedMarks: document.getElementsByName('teptom')[0],
            division: document.getElementsByName('teptdiv')[0],
            isPredefined: true
        },
        // B.Ed/BS.Ed
        {
            name: 'B.Ed/BS.Ed',
            date: document.getElementsByName('tebedpass')[0],
            institution: document.getElementsByName('tebedis')[0],
            totalMarks: document.getElementsByName('tebedtot')[0],
            obtainedMarks: document.getElementsByName('tebedom')[0],
            division: document.getElementsByName('tebeddiv')[0],
            isPredefined: true
        },
        // M.Ed/M.A Education
        {
            name: 'M.Ed/M.A Education',
            date: document.getElementsByName('temedpass')[0],
            institution: document.getElementsByName('temedis')[0],
            totalMarks: document.getElementsByName('temedtot')[0],
            obtainedMarks: document.getElementsByName('temedom')[0],
            division: document.getElementsByName('temeddiv')[0],
            isPredefined: true
        },
        // Other Qualification 1
        {
            name: document.getElementsByName('teo1name')[0],
            date: document.getElementsByName('teo1pass')[0],
            institution: document.getElementsByName('teo1is')[0],
            totalMarks: document.getElementsByName('teo1tot')[0],
            obtainedMarks: document.getElementsByName('teo1om')[0],
            division: document.getElementsByName('teo1div')[0],
            isPredefined: false
        },
        // Other Qualification 2
        {
            name: document.getElementsByName('teo2name')[0],
            date: document.getElementsByName('teo2pass')[0],
            institution: document.getElementsByName('teo2is')[0],
            totalMarks: document.getElementsByName('teo2tot')[0],
            obtainedMarks: document.getElementsByName('teo2om')[0],
            division: document.getElementsByName('teo2div')[0],
            isPredefined: false
        },
        // Other Qualification 3
        {
            name: document.getElementsByName('teo3name')[0],
            date: document.getElementsByName('teo3pass')[0],
            institution: document.getElementsByName('teo3is')[0],
            totalMarks: document.getElementsByName('teo3tot')[0],
            obtainedMarks: document.getElementsByName('teo3om')[0],
            division: document.getElementsByName('teo3div')[0],
            isPredefined: false
        }
    ];

    // Validate each qualification
    for (let i = 0; i < qualifications.length; i++) {
        const qual = qualifications[i];
        const qualName = typeof qual.name === 'string' ? qual.name : qual.name.value.trim();
        const hasDate = qual.date.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() !== '';
        
        // For predefined qualifications, ignore the pre-filled total marks when checking for partial data
        const hasUserEnteredData = hasDate || hasInstitution || hasObtainedMarks || hasDivision || 
                                  (typeof qual.name !== 'string' && qualName !== '');
        
        // If any user-entered field is filled, all must be filled
        if (hasUserEnteredData) {
            let missingFields = [];
            
            if (typeof qual.name !== 'string' && qualName === '') {
                missingFields.push('Qualification Name');
            }
            if (!hasDate) missingFields.push('Date');
            if (!hasInstitution) missingFields.push('Institution');
            if (!hasObtainedMarks) missingFields.push('Obtained Marks');
            if (!hasDivision) missingFields.push('Division');
            
            if (missingFields.length > 0) {
                isValid = false;
                alert(`ERROR: ${typeof qual.name === 'string' ? qual.name : 'Other Qualification'} 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 date format for filled dates
            if (hasDate) {
                const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
                const match = qual.date.value.match(dateRegex);
                
                if (!match) {
                    isValid = false;
                    alert(`ERROR: Invalid date format in ${typeof qual.name === 'string' ? qual.name : 'Other Qualification'}.\n\nPlease use DD-MM-YYYY format.`);
                    qual.date.focus();
                    return false;
                }
                
                // Basic date validation
                const day = parseInt(match[1], 10);
                const month = parseInt(match[2], 10);
                const year = parseInt(match[3], 10);
                
                if (day < 1 || day > 31 || month < 1 || month > 12 || year < 1900 || year > new Date().getFullYear()) {
                    isValid = false;
                    alert(`ERROR: Invalid date in ${typeof qual.name === 'string' ? qual.name : 'Other Qualification'}.\n\nPlease enter a valid date.`);
                    qual.date.focus();
                    return false;
                }
            }
            
            // Validate marks (safety check even though browser handles it)
            if (hasObtainedMarks) {
                const totalMarks = parseFloat(qual.totalMarks.value) || 1000;
                const obtainedMarks = parseFloat(qual.obtainedMarks.value);
                
                if (obtainedMarks > totalMarks) {
                    isValid = false;
                    alert(`ERROR: Invalid marks in ${typeof qual.name === 'string' ? qual.name : 'Other Qualification'}.\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 ${typeof qual.name === 'string' ? qual.name : 'Other Qualification'}.\n\nObtained marks must be a positive value.`);
                    qual.obtainedMarks.focus();
                    return false;
                }
            }
        }
    }

    if (!isValid) {
        return false;
    }

    // Additional validation: Check if at least one professional qualification is filled
    const hasAnyProfessionalQual = qualifications.some(qual => {
        const qualName = typeof qual.name === 'string' ? qual.name : qual.name.value.trim();
        const hasDate = qual.date.value.trim() !== '';
        const hasInstitution = qual.institution.value !== '';
        const hasObtainedMarks = qual.obtainedMarks.value.trim() !== '';
        const hasDivision = qual.division.value.trim() !== '';
        
        return hasDate || hasInstitution || hasObtainedMarks || hasDivision || 
               (typeof qual.name !== 'string' && qualName !== '');
    });

    // Show warning if no professional qualifications are filled (optional step)
    if (!hasAnyProfessionalQual) {
const proceed = confirm('⚠️ WARNING: No professional qualifications entered.\n\nProfessional qualifications are optional but highly recommended for a complete profile.\nDo you want to proceed without entering any professional qualifications?');        if (!proceed) {
            return false;
        }
    }

    // Auto-save form data before proceeding
    const formData = new FormData(document.getElementById('teacherForm'));
    
    return fetch('save_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;
    });
}

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

    // Add event listeners for total marks to update max attributes
    const totalMarksInputs = document.querySelectorAll('.total-marks');
    totalMarksInputs.forEach(input => {
        input.addEventListener('input', updateMaxObtainedMarks);
        input.addEventListener('change', updateMaxObtainedMarks);
    });
});

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);
    
    if (day < 1 || day > 31 || month < 1 || month > 12 || year < 1900 || year > new Date().getFullYear()) {
        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',
        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>
</body>
</html>