<?php
/**
 * Auto-Save Employee Field API
 * Saves individual fields as user types
 */

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

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['auto_save'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

try {
    $employeeId = (int)($_POST['employee_id'] ?? 0);
    $field = sanitize($_POST['field'] ?? '');
    $value = sanitize($_POST['value'] ?? '');
    
    if ($employeeId <= 0 || empty($field)) {
        echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
        exit;
    }
    
    $db = getDB();
    $siteId = getCurrentSiteId();
    $userId = getCurrentUserId();
    
    // Whitelist of allowed fields for security
    $allowedFields = [
        'pan_number', 'aadhar_number', 'remarks', 'esic_number', 'uan_number',
        'first_name', 'last_name', 'middle_name', 'email', 'phone',
        'bank_name', 'bank_account_number', 'bank_ifsc'
    ];
    
    if (!in_array($field, $allowedFields)) {
        echo json_encode(['success' => false, 'message' => 'Field not allowed']);
        exit;
    }
    
    // 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 in database']);
        exit;
    }
    
    // Update the 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) {
        $affectedRows = $stmt->rowCount();
        echo json_encode([
            'success' => true, 
            'message' => 'Auto-saved successfully',
            'affected_rows' => $affectedRows
        ]);
    } else {
        $errorInfo = $stmt->errorInfo();
        echo json_encode([
            'success' => false, 
            'message' => 'Save failed: ' . ($errorInfo[2] ?? 'Unknown error')
        ]);
    }
    
} catch (Exception $e) {
    error_log("Auto-save error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

