<?php

function db_has_groups() {
    return check_empty_result("SELECT COUNT(*) FROM " . TB_PREF . "per_groups");
}

//--------------------------------------------------------------------------

function write_group(Group $group) {
    if (!$group->id) {
        $sql = "INSERT INTO " . TB_PREF . "per_groups (
`name`,`description`,`type`,`status`) VALUES ("
                . db_escape($group->name) . ", "
                . db_escape($group->description) . ", "
                . db_escape($group->type) . ", "
                . db_escape($group->status) 
                . ")";
    } else {
        $sql = "UPDATE " . TB_PREF . "per_groups SET 
                `name` = " . db_escape($group->name) . ",
                `description` = " . db_escape($group->description) . ",
                `type` = " . db_escape($group->type) . ",
                `status` = " . db_escape($group->status) . "
                WHERE `id` = " . db_escape($group->id);
    }

    db_query($sql, _('Could not write Group data'));
}

//--------------------------------------------------------------------------

function get_groups($id = 0, $name = '', $type = '',$SQL = FALSE) {

    $sql = "SELECT * FROM " . TB_PREF . "per_groups WHERE 1 ";
    $where = '';
    if (!empty($name))
        $where .= " AND name like " . db_escape('%'.$name.'%')." " ;
    if (!empty($type))
        $where .= " AND type=" . db_escape($type) ;
    if ($id)
        $where .= " AND id=" . db_escape($id);
    
    if ($id && !$SQL) {
        $result = db_query($sql.$where, _('Could not get member data.'));
        $row = db_fetch($result);
        $group = new Group();
        $group->name = $row['name'];
        $group->description = $row['description'];
        $group->type = $row['type'];
        $group->status = $row['status'];
        $group->id = $row['id'];
        return $group;
    } else {
        return $sql . $where;
    }
}

function get_group_name($group_id)
{
	$sql = "SELECT name "
                . " FROM ".TB_PREF."per_groups WHERE id=".db_escape($group_id);

	$result = db_query($sql, "could not get member");

	$row = db_fetch_row($result);

	return $row[0];
}

function get_group_id($group_name)
{
	$sql = "SELECT id "
                . " FROM ".TB_PREF."per_groups WHERE name=".db_escape($group_name);

	$result = db_query($sql, "could not get member");

	$row = db_fetch_row($result);

	return $row[0];
}

//--------------------------------------------------------------------------

function delete_group($id) {
    $sql = "DELETE FROM " . TB_PREF . "per_groups WHERE id = " . db_escape($id);
    db_query($sql, _('Could not delete group data.'));
}

function can_delete_group($id) {
    $sql = "select count(*) FROM " . TB_PREF . "per_groups_rltn WHERE group = " . db_escape($id);
    return !check_empty_result($sql);
}

