<!-- 
**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 fourth file (emp4.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 = 4;
$nextFile = 'emp5.php';
$previousFile = 'emp3.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 4: In-Service Training</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 and emp3.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="text"],
        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;
        }
        /* Training specific styles */
        .training-input {
            width: 100%;
            padding: 8px;
            border: 1px solid var(--medium-gray);
            border-radius: var(--border-radius);
        }
        .training-duration {
            width: 80px;
        }
    </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 4/7</h1>
        </div>
        <div class="progress-container">
            <div class="progress-bar" id="progressBar" style="width: 50%"></div>
            <div class="step completed" id="step1">
                <span>1</span>
                <span class="step-label">Personal Info</span>
            </div>
            <div class="step completed" id="step2">
                <span>2</span>
                <span class="step-label">Education</span>
            </div>
            <div class="step completed" id="step3">
                <span>3</span>
                <span class="step-label">Professional</span>
            </div>
            <div class="step active" 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 validateTrainingData()">
			<!-- ✅ Use $currentToken instead of directly accessing $_SESSION -->
			<input type="hidden" name="csrf_token" value="<?php echo $currentToken; ?>">
			<input type="hidden" name="step_4" value="1">
            
            <!-- Step 4: In-Service Training -->
            <div class="form-step active" id="step-4">
                <h2 class="section-title"><i class="fas fa-chalkboard-teacher"></i> In-Service Training (Last Five)</h2>
                <div class="instructions">
                    <h3><i class="fas fa-info-circle"></i> Instructions:</h3>
                    <ul>
                        <li>Enter training details for the last five in-service trainings attended.</li>
                        <li>Use the calendar picker or enter date in DD-MM-YYYY format for training date.</li>
                        <li>Duration should be entered in number of days (1-365).</li>
                        <li>Fill entries in chronological order (most recent first).</li>
                        <li><strong>Note: Filling training information is OPTIONAL.</strong></li>
                        <li><strong>However, if you start entering any training record, you must complete ALL fields for that training.</strong></li>
                        <li><strong>No partially filled records will be accepted.</strong></li>
                    </ul>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>Title of Training</th>
                            <th>Date (DD-MM-YYYY)</th>
                            <th>Institute</th>
                            <th>Place</th>
                            <th>Duration (Days)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Training 1 -->
                        <tr>
                            <td>
                                <input name="tetr1name" type="text" class="training-input" placeholder="e.g. Classroom Management"
                                    value="<?php echo isset($formData['tetr1name']) ? htmlspecialchars($formData['tetr1name']) : ''; ?>">
                            </td>
                            <td>
                                <div class="date-input-container">
                                    <input id="tetr1date" name="tetr1date" type="text" class="date-field training-date"
                                        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['tetr1date']) ? htmlspecialchars($formData['tetr1date']) : ''; ?>">
                                    <span class="datepicker-trigger" onclick="showDatePicker('tetr1date')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="tetr1date-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <input name="tetr1ins" type="text" class="training-input" placeholder="Institute Name"
                                    value="<?php echo isset($formData['tetr1ins']) ? htmlspecialchars($formData['tetr1ins']) : ''; ?>">
                            </td>
                            <td>
                                <input name="tetr1pla" type="text" class="training-input" placeholder="City OR Country"
                                    value="<?php echo isset($formData['tetr1pla']) ? htmlspecialchars($formData['tetr1pla']) : ''; ?>">
                            </td>
                            <td>
                                <input name="tetr1dur" type="number" min="1" max="365" class="training-duration" placeholder="Days"
                                    value="<?php echo isset($formData['tetr1dur']) ? htmlspecialchars($formData['tetr1dur']) : ''; ?>">
                            </td>
                        </tr>
                        <!-- Training 2 -->
                        <tr>
                            <td>
                                <input name="tetr2name" type="text" class="training-input" placeholder="e.g. Digital Pedagogy"
                                    value="<?php echo isset($formData['tetr2name']) ? htmlspecialchars($formData['tetr2name']) : ''; ?>">
                            </td>
                            <td>
                                <div class="date-input-container">
                                    <input id="tetr2date" name="tetr2date" type="text" class="date-field training-date"
                                        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['tetr2date']) ? htmlspecialchars($formData['tetr2date']) : ''; ?>">
                                    <span class="datepicker-trigger" onclick="showDatePicker('tetr2date')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="tetr2date-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <input name="tetr2ins" type="text" class="training-input" placeholder="Institute Name"
                                    value="<?php echo isset($formData['tetr2ins']) ? htmlspecialchars($formData['tetr2ins']) : ''; ?>">
                            </td>
                            <td>
                                <input name="tetr2pla" type="text" class="training-input" placeholder="City OR Country"
                                    value="<?php echo isset($formData['tetr2pla']) ? htmlspecialchars($formData['tetr2pla']) : ''; ?>">
                            </td>
                            <td>
                                <input name="tetr2dur" type="number" min="1" max="365" class="training-duration" placeholder="Days"
                                    value="<?php echo isset($formData['tetr2dur']) ? htmlspecialchars($formData['tetr2dur']) : ''; ?>">
                            </td>
                        </tr>
                        <!-- Training 3 -->
                        <tr>
                            <td>
                                <input name="tetr3name" type="text" class="training-input" placeholder="e.g. Assessment Techniques"
                                    value="<?php echo isset($formData['tetr3name']) ? htmlspecialchars($formData['tetr3name']) : ''; ?>">
                            </td>
                            <td>
                                <div class="date-input-container">
                                    <input id="tetr3date" name="tetr3date" type="text" class="date-field training-date"
                                        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['tetr3date']) ? htmlspecialchars($formData['tetr3date']) : ''; ?>">
                                    <span class="datepicker-trigger" onclick="showDatePicker('tetr3date')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="tetr3date-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <input name="tetr3ins" type="text" class="training-input" placeholder="Institute Name"
                                    value="<?php echo isset($formData['tetr3ins']) ? htmlspecialchars($formData['tetr3ins']) : ''; ?>">
                            </td>
                            <td>
                                <input name="tetr3pla" type="text" class="training-input" placeholder="City OR Country"
                                    value="<?php echo isset($formData['tetr3pla']) ? htmlspecialchars($formData['tetr3pla']) : ''; ?>">
                            </td>
                            <td>
                                <input name="tetr3dur" type="number" min="1" max="365" class="training-duration" placeholder="Days"
                                    value="<?php echo isset($formData['tetr3dur']) ? htmlspecialchars($formData['tetr3dur']) : ''; ?>">
                            </td>
                        </tr>
                        <!-- Training 4 -->
                        <tr>
                            <td>
                                <input name="tetr4name" type="text" class="training-input" placeholder="e.g. Special Education"
                                    value="<?php echo isset($formData['tetr4name']) ? htmlspecialchars($formData['tetr4name']) : ''; ?>">
                            </td>
                            <td>
                                <div class="date-input-container">
                                    <input id="tetr4date" name="tetr4date" type="text" class="date-field training-date"
                                        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['tetr4date']) ? htmlspecialchars($formData['tetr4date']) : ''; ?>">
                                    <span class="datepicker-trigger" onclick="showDatePicker('tetr4date')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="tetr4date-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <input name="tetr4ins" type="text" class="training-input" placeholder="Institute Name"
                                    value="<?php echo isset($formData['tetr4ins']) ? htmlspecialchars($formData['tetr4ins']) : ''; ?>">
                            </td>
                            <td>
                                <input name="tetr4pla" type="text" class="training-input" placeholder="City OR Country"
                                    value="<?php echo isset($formData['tetr4pla']) ? htmlspecialchars($formData['tetr4pla']) : ''; ?>">
                            </td>
                            <td>
                                <input name="tetr4dur" type="number" min="1" max="365" class="training-duration" placeholder="Days"
                                    value="<?php echo isset($formData['tetr4dur']) ? htmlspecialchars($formData['tetr4dur']) : ''; ?>">
                            </td>
                        </tr>
                        <!-- Training 5 -->
                        <tr>
                            <td>
                                <input name="tetr5name" type="text" class="training-input" placeholder="e.g. Leadership in Education"
                                    value="<?php echo isset($formData['tetr5name']) ? htmlspecialchars($formData['tetr5name']) : ''; ?>">
                            </td>
                            <td>
                                <div class="date-input-container">
                                    <input id="tetr5date" name="tetr5date" type="text" class="date-field training-date"
                                        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['tetr5date']) ? htmlspecialchars($formData['tetr5date']) : ''; ?>">
                                    <span class="datepicker-trigger" onclick="showDatePicker('tetr5date')">
                                    <i class="fas fa-calendar-alt"></i>
                                    </span>
                                </div>
                                <div id="tetr5date-error" class="error-message">Invalid date format (DD-MM-YYYY)</div>
                            </td>
                            <td>
                                <input name="tetr5ins" type="text" class="training-input" placeholder="Institute Name"
                                    value="<?php echo isset($formData['tetr5ins']) ? htmlspecialchars($formData['tetr5ins']) : ''; ?>">
                            </td>
                            <td>
                                <input name="tetr5pla" type="text" class="training-input" placeholder="City OR Country"
                                    value="<?php echo isset($formData['tetr5pla']) ? htmlspecialchars($formData['tetr5pla']) : ''; ?>">
                            </td>
                            <td>
                                <input name="tetr5dur" type="number" min="1" max="365" class="training-duration" placeholder="Days"
                                    value="<?php echo isset($formData['tetr5dur']) ? htmlspecialchars($formData['tetr5dur']) : ''; ?>">
                            </td>
                        </tr>
                    </tbody>
                </table>
                
                <!-- Form Actions -->
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="goBackToStep3()">
                        <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 4
        document.addEventListener('DOMContentLoaded', function() {
            <?php
            // Pre-fill form with saved data
            foreach ($formData as $field => $value) {
                if ($field !== 'csrf_token' && $field !== 'step_4') {
                    echo "if(document.querySelector('[name=\"$field\"]')) document.querySelector('[name=\"$field\"]').value = '" . addslashes($value) . "';";
                }
            }
            ?>
            
            // Initialize datepickers for all date fields
            $('.date-field').datepicker({
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true,
                yearRange: '-50:+0',
                maxDate: 0,
                onSelect: function(dateText, inst) {
                    // Hide error message when date is selected from picker
                    const errorElement = document.getElementById(this.id + '-error');
                    if (errorElement) {
                        errorElement.style.display = 'none';
                        this.style.borderColor = '';
                    }
                }
            });
            
            // Add real-time validation for date fields
            const dateFields = document.querySelectorAll('.date-field');
            dateFields.forEach(field => {
                field.addEventListener('blur', function() {
                    validateTrainingDateFormat(this);
                });
                
                field.addEventListener('input', function() {
                    // Clear error on input
                    const errorElement = document.getElementById(this.id + '-error');
                    if (errorElement) {
                        errorElement.style.display = 'none';
                        this.style.borderColor = '';
                    }
                });
            });
        });

        function showDatePicker(fieldId) {
            const $field = $('#' + fieldId);
            
            // If datepicker isn't initialized, initialize it first
            if (!$field.data('hasDatepicker')) {
                $field.datepicker({
                    dateFormat: 'dd-mm-yy',
                    changeMonth: true,
                    changeYear: true,
                    yearRange: '-50:+0',
                    maxDate: 0
                });
            }
            
            $field.datepicker('show');
        }

        // Training Data Validation - OPTIONAL but must be complete if started
        function validateTrainingData() {
            let isValid = true;
            
            // Get all training rows
            const trainings = [
                // Training 1
                {
                    name: document.getElementsByName('tetr1name')[0],
                    date: document.getElementsByName('tetr1date')[0],
                    institute: document.getElementsByName('tetr1ins')[0],
                    place: document.getElementsByName('tetr1pla')[0],
                    duration: document.getElementsByName('tetr1dur')[0]
                },
                // Training 2
                {
                    name: document.getElementsByName('tetr2name')[0],
                    date: document.getElementsByName('tetr2date')[0],
                    institute: document.getElementsByName('tetr2ins')[0],
                    place: document.getElementsByName('tetr2pla')[0],
                    duration: document.getElementsByName('tetr2dur')[0]
                },
                // Training 3
                {
                    name: document.getElementsByName('tetr3name')[0],
                    date: document.getElementsByName('tetr3date')[0],
                    institute: document.getElementsByName('tetr3ins')[0],
                    place: document.getElementsByName('tetr3pla')[0],
                    duration: document.getElementsByName('tetr3dur')[0]
                },
                // Training 4
                {
                    name: document.getElementsByName('tetr4name')[0],
                    date: document.getElementsByName('tetr4date')[0],
                    institute: document.getElementsByName('tetr4ins')[0],
                    place: document.getElementsByName('tetr4pla')[0],
                    duration: document.getElementsByName('tetr4dur')[0]
                },
                // Training 5
                {
                    name: document.getElementsByName('tetr5name')[0],
                    date: document.getElementsByName('tetr5date')[0],
                    institute: document.getElementsByName('tetr5ins')[0],
                    place: document.getElementsByName('tetr5pla')[0],
                    duration: document.getElementsByName('tetr5dur')[0]
                }
            ];

            // First validate all date formats
            for (let i = 0; i < trainings.length; i++) {
                const training = trainings[i];
                if (training.date.value.trim() !== '') {
                    if (!validateTrainingDateFormat(training.date)) {
                        alert(`ERROR: Invalid date format in Training ${i + 1}.\n\nPlease use DD-MM-YYYY format.`);
                        training.date.focus();
                        return false;
                    }
                }
            }

            // Validate each training record
            for (let i = 0; i < trainings.length; i++) {
                const training = trainings[i];
                const hasName = training.name.value.trim() !== '';
                const hasDate = training.date.value.trim() !== '';
                const hasInstitute = training.institute.value.trim() !== '';
                const hasPlace = training.place.value.trim() !== '';
                const hasDuration = training.duration.value.trim() !== '';
                
                // If any field is filled, all must be filled
                if (hasName || hasDate || hasInstitute || hasPlace || hasDuration) {
                    let missingFields = [];
                    
                    if (!hasName) missingFields.push('Training Title');
                    if (!hasDate) missingFields.push('Training Date');
                    if (!hasInstitute) missingFields.push('Institute');
                    if (!hasPlace) missingFields.push('Place');
                    if (!hasDuration) missingFields.push('Duration');
                    
                    if (missingFields.length > 0) {
                        isValid = false;
                        alert(`ERROR: Training ${i + 1} is partially filled.\n\nPlease complete all fields for this training:\n• ${missingFields.join('\n• ')}\n\nOR remove all entries for this training.`);
                        return false;
                    }
                    
                    // Validate duration
                    if (hasDuration) {
                        const duration = parseInt(training.duration.value);
                        if (duration < 1 || duration > 365) {
                            isValid = false;
                            alert(`ERROR: Invalid duration in Training ${i + 1}.\n\nDuration must be between 1 and 365 days.`);
                            training.duration.focus();
                            return false;
                        }
                    }
                    
                    // Validate date is not in future
                    if (hasDate) {
                        const dateValue = training.date.value;
                        const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
                        const match = dateValue.match(dateRegex);
                        
                        if (match) {
                            const day = parseInt(match[1], 10);
                            const month = parseInt(match[2], 10);
                            const year = parseInt(match[3], 10);
                            
                            const trainingDate = new Date(year, month - 1, day);
                            const today = new Date();
                            today.setHours(0, 0, 0, 0);
                            
                            if (trainingDate > today) {
                                isValid = false;
                                alert(`ERROR: Invalid training date in Training ${i + 1}.\n\nTraining date cannot be in the future.`);
                                training.date.focus();
                                return false;
                            }
                        }
                    }
                }
            }

            if (!isValid) {
                return false;
            }

            // Additional validation: Check chronological order (most recent first)
            const filledTrainings = trainings
                .map((training, index) => {
                    if (training.date.value.trim()) {
                        const dateValue = training.date.value;
                        const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
                        const match = dateValue.match(dateRegex);
                        if (match) {
                            const day = parseInt(match[1], 10);
                            const month = parseInt(match[2], 10);
                            const year = parseInt(match[3], 10);
                            return {
                                index: index + 1,
                                date: new Date(year, month - 1, day),
                                dateString: dateValue
                            };
                        }
                    }
                    return null;
                })
                .filter(training => training !== null)
                .sort((a, b) => b.date - a.date); // Sort descending (most recent first)

            // Check if filled trainings are in correct order
            for (let i = 0; i < filledTrainings.length - 1; i++) {
                if (filledTrainings[i].date < filledTrainings[i + 1].date) {
                    const proceed = confirm('⚠️ WARNING: Trainings are not in chronological order (most recent first).\n\nTraining ' + filledTrainings[i].index + ': ' + filledTrainings[i].dateString + 
                                          '\nTraining ' + filledTrainings[i + 1].index + ': ' + filledTrainings[i + 1].dateString + 
                                          '\n\nDo you want to continue anyway?');
                    if (!proceed) {
                        return false;
                    }
                    break;
                }
            }

            // Show warning if no trainings are filled (optional step)
            const hasAnyTraining = trainings.some(training => 
                training.name.value.trim() !== '' ||
                training.date.value.trim() !== '' ||
                training.institute.value.trim() !== '' ||
                training.place.value.trim() !== '' ||
                training.duration.value.trim() !== ''
            );

            if (!hasAnyTraining) {
                const proceed = confirm('⚠️ WARNING: No training records entered.\n\nIn-service training information is optional but recommended for a complete profile.\nDo you want to proceed without entering any training information?');
                if (!proceed) {
                    return false;
                }
            }

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

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

        function validateTrainingDateFormat(dateField) {
            const errorElement = document.getElementById(dateField.id + '-error');
            const dateValue = dateField.value.trim();
            
            if (dateValue === '') {
                errorElement.style.display = 'none';
                return true;
            }
            
            // Validate DD-MM-YYYY format
            const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
            const match = dateValue.match(dateRegex);
            
            if (!match) {
                errorElement.textContent = "Invalid date format (DD-MM-YYYY)";
                errorElement.style.display = 'block';
                dateField.style.borderColor = '#e74c3c';
                return false;
            }
            
            // Basic date validation
            const day = parseInt(match[1], 10);
            const month = parseInt(match[2], 10);
            const year = parseInt(match[3], 10);
            const currentYear = new Date().getFullYear();
            
            // Check if date is valid
            if (day < 1 || day > 31 || month < 1 || month > 12 || year < 1900 || year > currentYear) {
                errorElement.textContent = "Invalid date!";
                errorElement.style.display = 'block';
                dateField.style.borderColor = '#e74c3c';
                return false;
            }
            
            // Check specific month-day combinations
            const daysInMonth = [31, (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
            if (day > daysInMonth[month - 1]) {
                errorElement.textContent = "Invalid day for this month!";
                errorElement.style.display = 'block';
                dateField.style.borderColor = '#e74c3c';
                return false;
            }
            
            // Check if date is in future
            const inputDate = new Date(year, month - 1, day);
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            
            if (inputDate > today) {
                errorElement.textContent = "Date cannot be in the future!";
                errorElement.style.display = 'block';
                dateField.style.borderColor = '#e74c3c';
                return false;
            }
            
            errorElement.style.display = 'none';
            dateField.style.borderColor = '';
            return true;
        }

        // 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>