/**
 * Insert users for contacts group into database
 *
 * @param integer/string Group ID or 'new'
 * @param string Users IDs separated with comma
 * @param string Name of input element with new group name
 * @return array/boolean Array( 'count_users', 'group_name' ) if success, else false
 */
function create_contacts_group_users($group, $users, $new_group_field_name = 'group_combo')
{
    global $DB, $current_User, $Messages;
    $users_IDs = explode(',', $users);
    if (count($users_IDs) == 0 || strlen($users) == 0) {
        // No selected users
        $Messages->add(T_('Please select at least one user.'), 'error');
        return false;
    }
    if ($group == 'new' || (int) $group < 0) {
        // Add new group
        if ((int) $group < 0) {
            // Default group
            $default_groups = get_contacts_groups_default();
            if (isset($default_groups[$group])) {
                // Get group name
                $group_name = $default_groups[$group];
            } else {
                // Error
                $Messages->add('No found this group.', 'error');
                return false;
            }
        } else {
            // New entered group
            $group_name = param($new_group_field_name, 'string', true);
            param_check_not_empty($new_group_field_name, T_('Please enter name for new group.'));
        }
        if ($group_ID = create_contacts_group($group_name)) {
            // Create group
            $Messages->add(T_('New contacts group has been created.'), 'success');
        } else {
            // Errors
            return false;
        }
    } else {
        // Existing group
        $group_ID = (int) $group;
        if ($group_ID == 0) {
            // No defined group ID
            return false;
        }
        $SQL = new SQL();
        $SQL->SELECT('cgr_name AS name');
        $SQL->FROM('T_messaging__contact_groups');
        $SQL->WHERE('cgr_user_ID = ' . $current_User->ID);
        $SQL->WHERE_and('cgr_ID = ' . $DB->quote($group_ID));
        $group = $DB->get_row($SQL->get());
        if (is_null($group)) {
            // User try use a group of another user
            return false;
        }
        $group_name = $group->name;
    }
    // Get all Users IDs of selected group in order to exclude duplicates
    $SQL = new SQL();
    $SQL->SELECT('cgu_user_ID, cgu_cgr_ID');
    $SQL->FROM('T_messaging__contact_groupusers');
    $SQL->WHERE_and('cgu_cgr_ID = ' . $DB->quote($group_ID));
    $users_already_grouped = $DB->get_assoc($SQL->get());
    $sql = 'INSERT INTO T_messaging__contact_groupusers ( cgu_user_ID, cgu_cgr_ID ) VALUES ';
    $records = array();
    foreach ($users_IDs as $user_ID) {
        $user_ID = (int) trim($user_ID);
        if ($user_ID == 0) {
            // User ID is empty
            continue;
        } else {
            if (isset($users_already_grouped[$user_ID])) {
                if ($users_already_grouped[$user_ID] == $group_ID) {
                    // This user already is added in selected group
                    continue;
                }
            }
        }
        $records[] = '( ' . $user_ID . ', ' . $DB->quote($group_ID) . ' )';
    }
    $sql .= implode(', ', $records);
    if (count($records) == 0) {
        // No data to add
        return false;
    }
    if ($DB->query($sql, 'Insert users for contacts group')) {
        // Success query
        return array('count_users' => count($records), 'group_name' => $group_name);
    } else {
        // Failed query
        return false;
    }
}
/**
 * Update contact groups for user in database
 *
 * @param string Users ID
 * @param array Group IDs
 * @param boolean TRUE to block the contact, FALSE to unblock, NULL to don't touch the contact block status
 * @return boolean TRUE if success, else FALSE
 */
function update_contacts_groups_user($user_ID, $groups, $blocked = NULL)
{
    global $DB, $current_User, $Messages;
    if (empty($user_ID)) {
        // No selected user
        return false;
    }
    if ($blocked !== NULL) {
        // Update the contact block status
        set_contact_blocked($user_ID, intval($blocked));
    }
    $insert_sql = 'REPLACE INTO T_messaging__contact_groupusers ( cgu_user_ID, cgu_cgr_ID ) VALUES ';
    $records = array();
    foreach ($groups as $group) {
        if ($group == 'new' || intval($group) < 0) {
            // Add new group
            if (intval($group) < 0) {
                // Default group
                $default_groups = get_contacts_groups_default();
                if (isset($default_groups[$group])) {
                    // Get group name
                    $group_name = $default_groups[$group];
                }
            } else {
                // New entered group
                $group_name = param('contact_group_new', 'string');
                if (empty($group_name)) {
                    $Messages->add(T_('Please enter name for new group.'), 'error');
                }
            }
            if ($group_ID = create_contacts_group($group_name)) {
                // Create new group
                $Messages->add(T_('New contacts group has been created.'), 'success');
            }
        } else {
            // Existing group
            $group_ID = intval($group);
        }
        if (empty($group_ID)) {
            // No defined group ID
            continue;
        }
        $records[] = '( ' . $user_ID . ', ' . $DB->quote($group_ID) . ' )';
    }
    $current_user_groups = get_contacts_groups_array(false);
    if (count($current_user_groups) > 0) {
        // Clear previous selected groups for the user before new updating, in order to delete the user from the unchecked groups
        $DB->query('DELETE FROM T_messaging__contact_groupusers
			WHERE cgu_user_ID = ' . $DB->quote($user_ID) . '
			  AND cgu_cgr_ID IN ( ' . $DB->quote(array_keys($current_user_groups)) . ' )');
    }
    if (count($records) == 0) {
        // No data to add
        return true;
    }
    $insert_sql .= implode(', ', $records);
    if ($DB->query($insert_sql, 'Insert user for contact groups')) {
        // Success query
        return true;
    } else {
        // Failed query
        return false;
    }
}