<!-- 
	**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 seventh file (emp7.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 = 7;
	$nextFile = 'submit_employee.php';
	$previousFile = 'emp6.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 and step fields before merging
	        $postData = $_POST;
	        unset($postData['csrf_token']);
	        unset($postData["step_$stepNumber"]);
	        
	        // Save current step data
	        $_SESSION['form_data'] = array_merge($formData, $postData);
	        
	        // Save the validated CSRF token for final submission
	        $_SESSION['final_csrf_token'] = $_POST['csrf_token'];
	        
	        // For debugging - check what's being saved
	        error_log("=== Transfer Data Being Saved ===");
	        for ($i = 1; $i <= 5; $i++) {
	            $fromField = "tetra{$i}from";
	            $toField = "tetra{$i}to";
	            if (isset($_SESSION['form_data'][$fromField])) {
	                error_log("Transfer $i - From: " . $_SESSION['form_data'][$fromField]);
	            }
	            if (isset($_SESSION['form_data'][$toField])) {
	                error_log("Transfer $i - To: " . $_SESSION['form_data'][$toField]);
	            }
	        }
	        
	        // Redirect to final submission
	        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 7: Transfer History</title>
		<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
		<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
		<style>
			/* Same CSS as previous files */
			:root {
			--primary-color: #3498db;
			--secondary-color: #2980b9;
			--accent-color: #e74c3c;
			--light-gray: #f5f5f5;
			--medium-gray: #e0e0e0;
			--dark-gray: #333;
			--success-color: #2ecc71;
			--warning-color: #f39c12;
			--border-radius: 6px;
			--box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
			--transition: all 0.3s ease;
			}
			* {
			box-sizing: border-box;
			margin: 0;
			padding: 0;
			}
			body {
			font-family: 'Roboto', sans-serif;
			line-height: 1.6;
			color: var(--dark-gray);
			background-color: #f9f9f9;
			padding: 20px;
			}
			.form-container {
			max-width: 90%;
			margin: 10px auto;
			background: white;
			border-radius: var(--border-radius);
			box-shadow: var(--box-shadow);
			overflow: hidden;
			}
			.form-header {
			background: var(--primary-color);
			color: white;
			padding: 20px;
			text-align: center;
			}
			.form-header h1 {
			font-size: 24px;
			font-weight: 500;
			}
			.progress-container {
			display: flex;
			justify-content: space-between;
			position: relative;
			margin: 30px 50px;
			}
			.progress-container::before {
			content: "";
			position: absolute;
			top: 50%;
			left: 0;
			right: 0;
			height: 4px;
			background: var(--medium-gray);
			transform: translateY(-50%);
			z-index: 1;
			}
			.progress-bar {
			position: absolute;
			top: 50%;
			left: 0;
			height: 4px;
			background: var(--success-color);
			transform: translateY(-50%);
			z-index: 2;
			transition: var(--transition);
			}
			.step {
			width: 40px;
			height: 40px;
			border-radius: 50%;
			background: var(--medium-gray);
			color: var(--dark-gray);
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			z-index: 3;
			transition: var(--transition);
			}
			.step.active {
			background: var(--primary-color);
			color: white;
			transform: scale(1.1);
			}
			.step.completed {
			background: var(--success-color);
			color: white;
			}
			.step-label {
			position: absolute;
			top: 45px;
			font-size: 12px;
			color: var(--dark-gray);
			white-space: nowrap;
			}
			.step.active .step-label,
			.step.completed .step-label {
			color: var(--primary-color);
			font-weight: 500;
			}
			.form-step {
			display: none;
			padding: 30px;
			}
			.form-step.active {
			display: block;
			animation: fadeIn 0.5s ease;
			}
			@keyframes fadeIn {
			from { opacity: 0; transform: translateY(20px); }
			to { opacity: 1; transform: translateY(0); }
			}
			.section-title {
			color: var(--primary-color);
			margin-bottom: 20px;
			padding-bottom: 10px;
			border-bottom: 2px solid var(--medium-gray);
			font-size: 20px;
			}
			.form-group {
			margin-bottom: 20px;
			}
			.form-row {
			display: flex;
			flex-wrap: wrap;
			margin: 0 -10px;
			}
			.form-col {
			flex: 1;
			min-width: 250px;
			padding: 0 30px;
			margin-bottom: 15px;
			}
			label {
			display: block;
			margin-bottom: 8px;
			font-weight: 500;
			color: #555;
			}
			input[type="text"],
			input[type="number"],
			input[type="date"],
			input[type="month"],
			input[type="file"],
			select,
			textarea {
			width: 100%;
			padding: 12px;
			border: 1px solid var(--medium-gray);
			border-radius: var(--border-radius);
			font-size: 14px;
			transition: var(--transition);
			}
			input:focus,
			select:focus,
			textarea:focus {
			outline: none;
			border-color: var(--primary-color);
			box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
			}
			.radio-group {
			display: flex;
			flex-wrap: wrap;
			gap: 15px;
			margin-top: 8px;
			}
			.radio-option {
			display: flex;
			align-items: center;
			}
			.radio-option input {
			margin-right: 8px;
			}
			table {
			width: 100%;
			border-collapse: collapse;
			margin: 20px 0;
			box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
			}
			th, td {
			padding: 12px 5px;
			text-align: left;
			border-bottom: 1px solid var(--medium-gray);
			}
			th {
			background-color: var(--primary-color);
			color: white;
			font-weight: 500;
			}
			tr:nth-child(even) {
			background-color: var(--light-gray);
			}
			tr:hover {
			background-color: #f0f0f0;
			}
			.photo-upload {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin: 20px 0;
			}
			#fileDisplayArea {
			width: 150px;
			height: 180px;
			border: 2px dashed var(--medium-gray);
			border-radius: var(--border-radius);
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 15px;
			overflow: hidden;
			background-color: white;
			}
			#fileDisplayArea img {
			max-width: 100%;
			max-height: 100%;
			object-fit: cover;
			}
			.file-input-label {
			display: inline-block;
			padding: 10px 15px;
			background-color: var(--primary-color);
			color: white;
			border-radius: var(--border-radius);
			cursor: pointer;
			transition: var(--transition);

			text-align: center;
			}
			.file-input-label:hover {
			background-color: var(--secondary-color);
			}
			#tchpic {
			display: none;
			}
			.form-actions {
			display: flex;
			justify-content: space-between;
			margin-top: 30px;
			padding-top: 20px;
			border-top: 1px solid var(--medium-gray);
			}
			.btn {
			padding: 12px 24px;
			border: none;
			border-radius: var(--border-radius);
			font-size: 16px;
			font-weight: 500;
			cursor: pointer;
			transition: var(--transition);
			display: inline-flex;
			align-items: center;
			justify-content: center;
			}
			.btn-primary {
			background-color: var(--primary-color);
			color: white;
			}
			.btn-primary:hover {
			background-color: var(--secondary-color);
			}
			.btn-secondary {
			background-color: var(--medium-gray);
			color: var(--dark-gray);
			}
			.btn-secondary:hover {
			background-color: #d0d0d0;
			}
			.btn-success {
			background-color: var(--success-color);
			color: white;
			}
			.btn-success:hover {
			background-color: #27ae60;
			}
			.btn i {
			margin-right: 8px;
			}
			.required-field::after {
			content: " *";
			color: var(--accent-color);
			}
			@media (max-width: 768px) {
			.form-col {
			min-width: 100%;
			}
			.progress-container {
			margin: 30px 20px;
			}
			.step-label {
			display: none;
			}
			.form-step {
			padding: 20px;
			}
			}
			/* Additional styles for Instructions window */
			.instructions {
			background-color: #e8f4fc;
			padding: 15px;
			border-radius: 6px;
			margin-top: 20px;
			font-size: 14px;
			line-height: 1.5;
			}
			.instructions h3 {
			color: #2c3e50;
			margin-bottom: 10px;
			}
			.instructions ul {
			padding-left: 20px;
			}
			.instructions li {
			margin-bottom: 5px;
			}
			.success-message {
			color: #27ae60;
			font-size: 13px;
			margin-top: 5px;
			display: none;
			}
			/* Transfer specific styles */
			.transfer-select {
			width: 100%;
			}
			.transfer-date {
			width: 150px;
			}
			.optional-note {
			background-color: #fff3cd;
			border: 1px solid #ffeaa7;
			color: #856404;
			padding: 10px;
			border-radius: var(--border-radius);
			margin: 10px 0;
			font-size: 14px;
			}
			.date-input-container {
			position: relative;
			display: flex;
			align-items: center;
			}
			.datepicker-trigger {
			cursor: pointer;
			margin-left: -25px;
			color: #666;
			}
			.error-message {
			color: red;
			font-size: 0.9em;
			margin-top: 5px;
			display: none;
			}
			.completion-message {
			background-color: #d4edda;
			border: 1px solid #c3e6cb;
			color: #155724;
			padding: 15px;
			border-radius: var(--border-radius);
			margin: 20px 0;
			text-align: center;
			}
			/* Searchable EMIS dropdown */
			.searchable-dropdown {
			position: relative;
			}
			.dropdown-search-container {
			position: relative;
			}
			.dropdown-search-input {
			width: 100%;
			padding: 12px 40px 12px 12px;
			border: 1px solid #e0e0e0;
			border-radius: 6px;
			font-size: 14px;
			}
			.search-icon {
			position: absolute;
			right: 12px;
			top: 50%;
			transform: translateY(-50%);
			color: #999;
			}
			.search-results {
			position: absolute;
			top: 100%;
			left: 0;
			right: 0;
			background: #fff;
			border: 1px solid #ddd;
			max-height: 220px;
			overflow-y: auto;
			z-index: 9999;
			display: none;
			}
			.search-results div {
			padding: 10px;
			cursor: pointer;
			}
			.search-results div:hover {
			background: #f1f1f1;
			}
		</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 7/7</h1>
			</div>
			<div class="progress-container">
				<div class="progress-bar" id="progressBar" style="width: 100%"></div>
				<div class="step completed" id="step1">
					<span>1</span>
					<span class="step-label">Personal Info</span>
				</div>
				<div class="step completed" id="step2">
					<span>2</span>
					<span class="step-label">Education</span>
				</div>
				<div class="step completed" id="step3">
					<span>3</span>
					<span class="step-label">Professional</span>
				</div>
				<div class="step completed" id="step4">
					<span>4</span>
					<span class="step-label">Training</span>
				</div>
				<div class="step completed" id="step5">
					<span>5</span>
					<span class="step-label">Subjects</span>
				</div>
				<div class="step completed" id="step6">
					<span>6</span>
					<span class="step-label">Promotions</span>
				</div>
				<div class="step active" id="step7">
					<span>7</span>
					<span class="step-label">Transfers</span>
				</div>
			</div>
			<form id="teacherForm" method="POST" action="emp7.php" onsubmit="return validateTransferData()">
				<!-- Step indicator -->
				<input type="hidden" name="step_<?php echo $stepNumber; ?>" value="1">
				<!-- ✅ Use $currentToken -->
				<input type="hidden" name="csrf_token" value="<?php echo $currentToken; ?>">
				<!-- Step 7: Transfer History -->
				<div class="form-step active" id="step-7">
					<h2 class="section-title"><i class="fas fa-exchange-alt"></i> Transfer History (Last Five in Ascending, If applicable)</h2>
					<div class="completion-message">
						<i class="fas fa-check-circle"></i> <strong>Final Step!</strong> You're almost done. Complete this section and submit your employee profile.
					</div>
					<div class="instructions">
						<h3><i class="fas fa-info-circle"></i> Instructions:</h3>
						<ul>
							<li>Enter transfer details for the last five transfers (if applicable).</li>
							<li>Fill entries in chronological order (oldest transfer first).</li>
							<li>Use the calendar picker or enter date in DD-MM-YYYY format.</li>
							<li>Select appropriate schools and transfer reasons from dropdowns.</li>
							<li><strong>Note: This section is OPTIONAL for employees without transfer history.</strong></li>
							<li><strong>If you start entering a transfer record, you must complete ALL fields for that transfer.</strong></li>
							<li><strong>No partially filled records will be accepted.</strong></li>
						</ul>
					</div>
					<div class="optional-note">
						<i class="fas fa-info-circle"></i> <strong>Optional Section:</strong> This section is for employees who have been transferred between institutions. 
						If you haven't been transferred or don't have transfer records, you can proceed to submit the form.
					</div>
					<table>
						<thead>
							<tr>
								<th>Transfer From (Institute)</th>
								<th>Transfer To (Institute)</th>
								<th>Reason of Transfer</th>
								<th>Date of Transfer</th>
							</tr>
						</thead>
						<tbody>
							<?php
								$schools = $conn->query("SELECT emis_code, school_name FROM school_emis ORDER BY emis_code");
								$reasons = $conn->query("SELECT reason_id, reason_name FROM transfer_reasons WHERE is_active = 1");
								
								for ($i = 1; $i <= 5; $i++) {
								
								    $fromVal = $formData["tetra{$i}from"] ?? '';
								    $toVal   = $formData["tetra{$i}to"] ?? '';
								    $reason  = $formData["tetra{$i}reason"] ?? '';
								    $date    = $formData["tetra{$i}date"] ?? '';
								
								    echo "<tr>";
								
								    /* ========= FROM SCHOOL ========= */
								    echo "<td>
								        <div class='searchable-dropdown'>
								            <input type='hidden' name='tetra{$i}from' id='tetra{$i}from' value='".htmlspecialchars($fromVal)."'>
								            <input type='text'
								                   class='dropdown-search-input transfer-from'
								                   placeholder='Click or type to search school...'
								                   data-target='tetra{$i}from'
								                   autocomplete='off'
								                   value='".htmlspecialchars($fromVal)."'>
								            <div class='search-icon'><i class='fas fa-search'></i></div>
								            <div class='search-results'>";
								    
								    $schools->data_seek(0);
								    while ($s = $schools->fetch_assoc()) {
								echo "<div 
								        data-value='{$s['emis_code']}'
								        data-name='".htmlspecialchars($s['school_name'], ENT_QUOTES)."'>
								        ".htmlspecialchars($s['emis_code']." - ".$s['school_name'])."
								      </div>";
								
								    }
								
								    echo "</div></div></td>";
								
								    /* ========= TO SCHOOL ========= */
								    echo "<td>
								        <div class='searchable-dropdown'>
								            <input type='hidden' name='tetra{$i}to' id='tetra{$i}to' value='".htmlspecialchars($toVal)."'>
								            <input type='text'
								                   class='dropdown-search-input transfer-to'
								                   placeholder='Click or type to search school...'
								                   data-target='tetra{$i}to'
								                   autocomplete='off'
								                   value='".htmlspecialchars($toVal)."'>
								            <div class='search-icon'><i class='fas fa-search'></i></div>
								            <div class='search-results'>";
								    
								    $schools->data_seek(0);
								    while ($s = $schools->fetch_assoc()) {
								echo "<div 
								        data-value='{$s['emis_code']}'
								        data-name='".htmlspecialchars($s['school_name'], ENT_QUOTES)."'>
								        ".htmlspecialchars($s['emis_code']." - ".$s['school_name'])."
								      </div>";
								
								    }
								
								    echo "</div></div></td>";
								
								    /* ========= REASON ========= */
								    echo "<td>
								        <select name='tetra{$i}reason' class='transfer-select'>
								            <option value=''>Select Reason</option>";
								    
								    $reasons->data_seek(0);
								    while ($r = $reasons->fetch_assoc()) {
								        $sel = ($reason == $r['reason_id']) ? 'selected' : '';
								        echo "<option value='{$r['reason_id']}' $sel>{$r['reason_name']}</option>";
								    }
								
								    echo "</select></td>";
								
								    /* ========= DATE ========= */
								    echo "<td>
								        <input type='text'
								               name='tetra{$i}date'
								               class='transfer-date date-field'
								               placeholder='DD-MM-YYYY'
								               value='".htmlspecialchars($date)."'>
								    </td>";
								
								    echo "</tr>";
								}
								?>
						</tbody>
					</table>
					<!-- Form Actions -->
					<div class="form-actions">
						<button type="button" class="btn btn-secondary" onclick="window.location.href='emp6.php'">
						<i class="fas fa-arrow-left"></i> Previous
						</button>
						<button type="submit" class="btn btn-success">
						<i class="fas fa-check"></i> Submit Final Form
						</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 7
			document.addEventListener('DOMContentLoaded', function() {
			    <?php
				// Pre-fill form with saved data
				foreach ($formData as $field => $value) {
				    if ($field !== 'csrf_token' && $field !== 'step_7') {
				        echo "if(document.querySelector('[name=\"$field\"]')) document.querySelector('[name=\"$field\"]').value = '" . addslashes($value) . "';";
				    }
				}
				?>
			    
			    // Initialize datepickers
			    $('.date-field').datepicker({
			        dateFormat: 'dd-mm-yy',
			        changeMonth: true,
			        changeYear: true,
			        yearRange: '-50:+0',
			        maxDate: 0 // Cannot select future dates
			    });
			});
			
			function showDatePicker(fieldId) {
			    $('#' + fieldId).datepicker('show');
			}
			
			// Transfer Data Validation - OPTIONAL but must be complete if started
			function validateTransferData() {
			    let isValid = true;
			    
			    // Get all transfer rows
			    const transfers = [];
			    for (let i = 1; i <= 5; i++) {
			        transfers.push({
			            row: i,
			            fromSchool: document.querySelector(`[name="tetra${i}from"]`),
			            toSchool: document.querySelector(`[name="tetra${i}to"]`),
			            reason: document.querySelector(`[name="tetra${i}reason"]`),
			            transferDate: document.querySelector(`[name="tetra${i}date"]`)
			        });
			    }
			
			    // Validate each transfer record
			    for (let i = 0; i < transfers.length; i++) {
			        const transfer = transfers[i];
			        const hasFromSchool = transfer.fromSchool.value !== '';
			        const hasToSchool = transfer.toSchool.value !== '';
			        const hasReason = transfer.reason.value !== '';
			        const hasTransferDate = transfer.transferDate.value.trim() !== '';
			        
			        // If any field is filled, all must be filled
			        if (hasFromSchool || hasToSchool || hasReason || hasTransferDate) {
			            let missingFields = [];
			            
			            if (!hasFromSchool) missingFields.push('Transfer From School');
			            if (!hasToSchool) missingFields.push('Transfer To School');
			            if (!hasReason) missingFields.push('Reason of Transfer');
			            if (!hasTransferDate) missingFields.push('Date of Transfer');
			            
			            if (missingFields.length > 0) {
			                isValid = false;
			                alert(`ERROR: Transfer record ${transfer.row} is partially filled.\n\nPlease complete all fields for this transfer:\n• ${missingFields.join('\n• ')}\n\nOR remove all entries for this transfer.`);
			                return false;
			            }
			            
			            // Validate same school transfer
			            if (hasFromSchool && hasToSchool && transfer.fromSchool.value === transfer.toSchool.value) {
			                isValid = false;
			                alert(`ERROR: Transfer from and to schools cannot be the same in record ${transfer.row}.`);
			                transfer.fromSchool.focus();
			                return false;
			            }
			            
			            // Validate date format
			            if (hasTransferDate) {
			                const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
			                const match = transfer.transferDate.value.match(dateRegex);
			                
			                if (!match) {
			                    isValid = false;
			                    alert(`ERROR: Invalid date format in transfer record ${transfer.row}.\n\nPlease use DD-MM-YYYY format.`);
			                    transfer.transferDate.focus();
			                    return false;
			                }
			                
			                // Basic date validation
			                const day = parseInt(match[1], 10);
			                const month = parseInt(match[2], 10);
			                const year = parseInt(match[3], 10);
			                const currentYear = new Date().getFullYear();
			                
			                if (day < 1 || day > 31 || month < 1 || month > 12 || year < 1900 || year > currentYear) {
			                    isValid = false;
			                    alert(`ERROR: Invalid date in transfer record ${transfer.row}.\n\nPlease enter a valid date.`);
			                    transfer.transferDate.focus();
			                    return false;
			                }
			                
			                // Validate date is not in future
			                const transferDate = new Date(year, month - 1, day);
			                const today = new Date();
			                today.setHours(0, 0, 0, 0);
			                
			                if (transferDate > today) {
			                    isValid = false;
			                    alert(`ERROR: Transfer date in record ${transfer.row} cannot be in the future.`);
			                    transfer.transferDate.focus();
			                    return false;
			                }
			            }
			        }
			    }
			
			    if (!isValid) {
			        return false;
			    }
			
			    // Additional validation: Check chronological order (oldest first)
			    const filledTransfers = transfers
			        .map(transfer => ({
			            row: transfer.row,
			            date: transfer.transferDate.value,
			            dateObj: transfer.transferDate.value ? parseDate(transfer.transferDate.value) : null
			        }))
			        .filter(transfer => transfer.dateObj !== null)
			        .sort((a, b) => a.dateObj - b.dateObj); // Sort ascending (oldest first)
			
			    // Check if filled transfers are in correct order
			    for (let i = 0; i < filledTransfers.length - 1; i++) {
			        if (filledTransfers[i].dateObj > filledTransfers[i + 1].dateObj) {
			            const proceed = confirm('⚠️ WARNING: Transfers are not in chronological order (oldest first).\n\nDo you want to continue anyway?');
			            if (!proceed) {
			                return false;
			            }
			            break;
			        }
			    }
			
			    // Show warning if no transfers are filled (optional step)
			    const hasAnyTransfer = transfers.some(transfer => 
			        transfer.fromSchool.value !== '' ||
			        transfer.toSchool.value !== '' ||
			        transfer.reason.value !== '' ||
			        transfer.transferDate.value.trim() !== ''
			    );
			
			    if (!hasAnyTransfer) {
			        const proceed = confirm('⚠️ WARNING: No transfer records entered.\n\nTransfer history is optional and only required for employees with transfer history.\nDo you want to proceed to submit the form without entering any transfer records?');
			        if (!proceed) {
			            return false;
			        }
			    }
			
			    // Final confirmation before submission
			    const finalConfirm = confirm('🎉 FINAL CONFIRMATION\n\nYou are about to submit your employee profile.\n\nPlease ensure all information is correct before proceeding.\n\nClick OK to submit your profile.');
			    if (!finalConfirm) {
			        return false;
			    }
			
			    // Auto-save form data before final submission
			    const formData = new FormData(document.getElementById('teacherForm'));
			    
			    return fetch('save_emp_step_data.php', {
			        method: 'POST',
			        body: formData
			    }).then(response => {
			        if (!response.ok) {
			            throw new Error('Network response was not ok');
			        }
			        return true;
			    }).catch(error => {
			        console.error('Error saving form data:', error);
			        // Even if save fails, allow form submission
			        return true;
			    });
			}
			
			// Helper function to parse DD-MM-YYYY date
			function parseDate(dateStr) {
			    const parts = dateStr.split('-');
			    if (parts.length !== 3) return null;
			    const day = parseInt(parts[0], 10);
			    const month = parseInt(parts[1], 10) - 1; // Months are 0-indexed in JavaScript
			    const year = parseInt(parts[2], 10);
			    return new Date(year, month, day);
			}
			
			// Back button function
			function goBackToStep6() {
			const formData = new FormData(document.getElementById('teacherForm'));
			formData.append('step', '7'); // ✅ ADD THIS
			
			fetch('save_emp_step_data.php', {
			method: 'POST',
			body: formData
			}).then(response => response.json())
			.then(data => {
			if (data.success) {
			window.location.href = 'emp6.php?back=1';
			} else {
			alert('Error: ' + data.message);
			window.location.href = 'emp6.php?back=1';
			}
			}).catch(() => {
			window.location.href = 'emp6.php?back=1';
			});
			}
			
			// Real-time date format validation
			document.addEventListener('DOMContentLoaded', function() {
			    // Add input event listeners for date fields
			    const dateFields = document.querySelectorAll('.date-field');
			    dateFields.forEach(field => {
			        field.addEventListener('input', function() {
			            validateDateFormat(this);
			        });
			        field.addEventListener('blur', function() {
			            validateDateFormat(this);
			        });
			    });
			
			    // Prevent same school selection in transfer from and to
			    const fromSelects = document.querySelectorAll('.transfer-from');
			    const toSelects = document.querySelectorAll('.transfer-to');
			    
			    fromSelects.forEach((fromSelect, index) => {
			        fromSelect.addEventListener('change', function() {
			            const toSelect = toSelects[index];
			            if (this.value && this.value === toSelect.value) {
			                alert('⚠️ Transfer from and to schools cannot be the same.');
			                this.value = '';
			            }
			        });
			    });
			    
			    toSelects.forEach((toSelect, index) => {
			        toSelect.addEventListener('change', function() {
			            const fromSelect = fromSelects[index];
			            if (this.value && this.value === fromSelect.value) {
			                alert('⚠️ Transfer from and to schools cannot be the same.');
			                this.value = '';
			            }
			        });
			    });
			});
			
			function validateDateFormat(dateField) {
			    const errorElement = document.getElementById(dateField.id + '-error');
			    const dateValue = dateField.value.trim();
			    
			    if (dateValue === '') {
			        errorElement.style.display = 'none';
			        return true;
			    }
			    
			    const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
			    const match = dateValue.match(dateRegex);
			    
			    if (!match) {
			        errorElement.style.display = 'block';
			        return false;
			    }
			    
			    // Basic date validation
			    const day = parseInt(match[1], 10);
			    const month = parseInt(match[2], 10);
			    const year = parseInt(match[3], 10);
			    const currentYear = new Date().getFullYear();
			    
			    if (day < 1 || day > 31 || month < 1 || month > 12 || year < 1900 || year > currentYear) {
			        errorElement.style.display = 'block';
			        return false;
			    }
			    
			    errorElement.style.display = 'none';
			    return true;
			}
			
			// Enhanced datepicker functionality
			$(function() {
			    $('.date-field').datepicker({
			        dateFormat: 'dd-mm-yy',
			        changeMonth: true,
			        changeYear: true,
			        yearRange: '-50:+0',
			        maxDate: 0,
			        onSelect: function(dateText, inst) {
			            // Hide error message when date is selected from picker
			            const errorElement = document.getElementById(this.id + '-error');
			            if (errorElement) {
			                errorElement.style.display = 'none';
			            }
			        }
			    });
			});
			
			// Prevent form submission on Enter key in input fields
			document.addEventListener('DOMContentLoaded', function() {
			    const form = document.getElementById('teacherForm');
			    const inputs = form.querySelectorAll('input, select, textarea');
			    
			    inputs.forEach(input => {
			        input.addEventListener('keydown', function(e) {
			            if (e.key === 'Enter') {
			                e.preventDefault();
			                return false;
			            }
			        });
			    });
			});
		</script>
		<script>
			document.addEventListener('DOMContentLoaded', function () {
			
			    document.querySelectorAll('.dropdown-search-input').forEach(input => {
			
			        const wrapper = input.closest('.searchable-dropdown');
			        const results = wrapper.querySelector('.search-results');
			        const hidden  = document.getElementById(input.dataset.target);
			
			        /* OPEN FULL LIST ON CLICK */
			        input.addEventListener('focus', function () {
			            results.style.display = 'block';
			            results.querySelectorAll('div').forEach(d => d.style.display = 'block');
			        });
			
			        /* FILTER WHILE TYPING */
			        input.addEventListener('input', function () {
			            const term = this.value.toLowerCase();
			            let visible = false;
			
			            results.querySelectorAll('div').forEach(item => {
			                if (item.textContent.toLowerCase().includes(term)) {
			                    item.style.display = 'block';
			                    visible = true;
			                } else {
			                    item.style.display = 'none';
			                }
			            });
			
			            results.style.display = visible ? 'block' : 'none';
			        });
			
			        /* SELECT VALUE */
			        results.querySelectorAll('div').forEach(item => {
			            item.addEventListener('click', function () {
			                input.value = this.dataset.name;   // show ONLY school name
							hidden.value = this.dataset.value; // EMIS code stays hidden
			                results.style.display = 'none';
			            });
			        });
			
			        /* CLOSE WHEN CLICK OUTSIDE */
			        document.addEventListener('click', function (e) {
			            if (!wrapper.contains(e.target)) {
			                results.style.display = 'none';
			            }
			        });
			
			    });
			
			});
		</script>
	</body>
</html>