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

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

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['userId'], $input['first_name'], $input['last_name'])) {
    echo json_encode(['success' => false, 'message' => 'Missing parameters']);
    exit;
}

$userId = (int)$input['userId'];
$firstName = trim($input['first_name']);
$lastName = trim($input['last_name']);

if ($firstName === '' || $lastName === '') {
    echo json_encode(['success' => false, 'message' => 'First and last names cannot be empty']);
    exit;
}

function updateUserSettings($userId, $data) {
    global $pdo;
    $table_name = PREFIX . 'users';

    $allowedFields = [
        'user_login', 'first_name', 'last_name', 'user_email',
        'group_id', 'display_name', 'user_nicename', 'user_url'
    ];

    $updates = [];
    $params = [];
    foreach ($allowedFields as $field) {
        if (isset($data[$field])) {
            $updates[] = "$field = ?";
            $params[] = $data[$field];
        }
    }

    if (empty($updates)) {
        return false;
    }

    $params[] = $userId;
    $sql = "UPDATE $table_name SET " . implode(', ', $updates) . " WHERE ID = ?";
    $stmt = $pdo->prepare($sql);
    return $stmt->execute($params);
}

$updateData = [
    'first_name' => $firstName,
    'last_name' => $lastName
];

if (updateUserSettings($userId, $updateData)) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Database update failed']);
}
