/**
 * Update an existing field group or create new one.
 *
 * @param array $group
 * @param string $post_type
 * @return int Group ID.
 */
function wpcf_admin_fields_save_group($group, $post_type = TYPES_CUSTOM_FIELD_GROUP_CPT_NAME, $which_fields = 'none')
{
    if (!isset($group['name']) || empty($group['name'])) {
        return false;
    }
    $post = array('post_status' => 'publish', 'post_type' => $post_type, 'post_title' => sanitize_text_field($group['name']), 'post_name' => sanitize_text_field($group['name']), 'post_content' => empty($group['description']) ? '' : $group['description']);
    if (empty($post['post_title'])) {
        wpcf_admin_message(__('Please set name', 'wpcf'), 'error');
        return false;
    }
    $update = false;
    $slug_pre_save = false;
    if (isset($group['id']) && !empty($group['id'])) {
        $update = true;
        $post_to_update = get_post($group['id']);
        if (empty($post_to_update) || $post_to_update->post_type != $post_type) {
            return false;
        }
        $post['ID'] = $post_to_update->ID;
        $slug_pre_save = $post_to_update->post_name;
        $post['post_status'] = $post_to_update->post_status;
    }
    if ($update) {
        $group_id = wp_update_post($post);
        if (!$group_id) {
            return false;
        }
        update_post_meta($group_id, TOOLSET_EDIT_LAST, time());
    } else {
        $group_id = wp_insert_post($post, true);
        if (is_wp_error($group_id)) {
            return false;
        }
    }
    if (isset($group['admin_styles'])) {
        wpcf_admin_fields_save_group_admin_styles($group_id, $group['admin_styles']);
    }
    if (!empty($group['filters_association'])) {
        update_post_meta($group_id, '_wp_types_group_filters_association', $group['filters_association']);
    } else {
        delete_post_meta($group_id, '_wp_types_group_filters_association');
    }
    // WPML register strings
    if (function_exists('icl_register_string')) {
        try {
            // Legacy function gives us only the underlying post type of the field group.
            $group_factory = Types_Field_Utils::get_group_factory_by_post_type($post_type);
            $field_group = $group_factory->load_field_group(sanitize_title($group['name']));
            // Skip registering if the group does not exist.
            if (null != $field_group) {
                $group_wpml = new Types_Wpml_Field_Group($field_group);
                $group_wpml->register($slug_pre_save);
            }
        } catch (InvalidArgumentException $e) {
            // Something is seriously wrong - there's no field group factory for given post type, bail.
        }
    }
    // admin message
    wpcf_admin_fields_save_message($update, $which_fields);
    return $group_id;
}