<?php
/**
 * Employee Edit with Auto-Save Feature
 * This is an alternative version with auto-save functionality
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();
requirePermission('EMPLOYEE_EDIT');

$pageTitle = 'Edit Employee (Auto-Save)';
$currentModule = 'employee';

$siteId = getCurrentSiteId();
$employeeId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($employeeId <= 0) {
    redirect(BASE_URL . '/modules/employee/list.php', 'Invalid employee ID.', 'error');
}

// Handle AJAX auto-save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['auto_save'])) {
    header('Content-Type: application/json');
    
    try {
        $db = getDB();
        $userId = getCurrentUserId();
        $field = sanitize($_POST['field'] ?? '');
        $value = sanitize($_POST['value'] ?? '');
        
        // Check if column exists
        $stmt = $db->query("SHOW COLUMNS FROM employees LIKE '{$field}'");
        if ($stmt->rowCount() == 0) {
            echo json_encode(['success' => false, 'message' => 'Field does not exist']);
            exit;
        }
        
        // Update single field
        $sql = "UPDATE employees SET {$field} = ?, updated_by = ?, updated_at = CURRENT_TIMESTAMP WHERE employee_id = ? AND site_id = ?";
        $stmt = $db->prepare($sql);
        $result = $stmt->execute([$value ?: null, $userId, $employeeId, $siteId]);
        
        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Auto-saved successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Save failed']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// Regular page load - same as edit.php but with auto-save JS
// For now, redirect to regular edit page
redirect(BASE_URL . '/modules/employee/edit.php?id=' . $employeeId);

