<?php
include_once "../../tools/inc.php";
$page = include("../common.php");
include("../tools/function.string.php");
include("../tools/function.sql.php");
$n=$settings["rec_count"];
$table="mailing_groups".$config["table_prefix"];
$table_sg="subscribers_group".$config["table_prefix"];
$table_s="subscribers".$config["table_prefix"];
$table_um="users_mailing_groups".$config["table_prefix"];
$access=check_level("Mailing Groups");
$IMG="mailing_groups.gif";

$filter_link=new Link($link->get());
$link->add("_search");
$offset_link=new Link($link->get());
$link->add("offset");

$message_list=array(
        1 => "{rs:MSG_MAILING_GROUP} {rs:MSG_CREATED}",
        2 => "{rs:MSG_MAILING_GROUP} {rs:MSG_UPDATED}",
        3 => "{rs:MSG_MAILING_GROUP} {rs:MSG_DELETED}",
        4 => "{rs:MSG_ALL_SUBSCRIBERS} {rs:MSG_REMOVED}",
        5 => "{rs:MSG_ALL_SUBSCRIBERS} {rs:MSG_DELETED}",
);

function check_position($new) {
        global $db, $table, $edit;
        $sql="select count(*) from $table";
        $count=$db->count($sql, true)-($edit ? 1 : 0);
        return ($new<0 ? 0 : ($new>$count ? $count : $new));
}

function update_position($old, $new) {
        global $db, $table;
        $sql=array();
        $sql[]="update $table set position=position-1 where position>$old";
        $sql[]="update $table set position=position+1 where position>=$new";
        $db->execute_all($sql);
}

$message=new Message();
$error=new Message("error");
if (isset($_r)) $message->add($message_list[$_r]);
if ($act=='delete' and (isset($access["delete"]) or isset($access["admin"]))) {
        $id=(is_array($id) ? implode($id, ", ") : $id);
        $where="where id in ($id)".(isset($user_permissions['groups_list']) ? " and id in (".$user_permissions['groups_list'].")" : "");
        $sql="select * from $table $where";
        $rs=$db->select($sql);
        for ($i=0; $i<count($rs); $i++) {
                $sql=array();
                $sql[]="update $table set position=position-1 where position>".$rs[$i]["position"];
                $sql[]="delete from $table_sg where group_id='".$rs[$i]["id"]."'";
                $sql[]="delete from $table_um where group_id='".$rs[$i]["id"]."'";
                $sql[]="delete from $table where id='".$rs[$i]["id"]."'";
                $db->execute_all($sql);
        }
        $link->add("_r", 3);
        $db->close();
        header("Location: ".$link->get());
        exit;
} elseif (in_array($act, array('delete_s', 'remove_s')) and (isset($access["delete"]) or isset($access["admin"]))) {
        $id=(is_array($id) ? implode($id, ", ") : $id);
        $sql=array();
        if ($act=='delete_s') {
                $s_id=implode(', ', $db->get_array("$table_s s, $table_sg sg", '', 's.id', "where s.id=sg.subscribers_id and sg.group_id in ($id)".(isset($user_permissions['groups_list']) ? " and sg.group_id in (".$user_permissions['groups_list'].")" : "").(!isset($access["delete"]) ? " and s.owner_id='".$ui['id']."'" : "")));
                $sql[]="delete from $table_s where id in ($s_id)";
                $sql[]="delete from $table_sg where subscribers_id in ($s_id)";
        }
        $sql[]="delete from $table_sg where group_id in ($id)".(isset($user_permissions['groups_list']) ? " and group_id in (".$user_permissions['groups_list'].")" : "");
        $db->execute_all($sql);
        $link->add("_r", ($act=='delete_s' ? 5 : 4));
        $db->close();
        header("Location: ".$link->get());
        exit;
} elseif (isset($edit) and (isset($access["edit"]) or isset($access['view']) or isset($access["admin"]))) {
        $IMG="mailing_groups_edit.gif";
        $where="where id='$edit'".(isset($user_permissions['groups_list']) ? " and id in (".$user_permissions['groups_list'].")" : "");
        $sql="select * from $table $where";
        $rs=$db->select($sql);
        $data=$rs[0];
        if (!isset($data["id"])) {
                $edit=0;
                $sql="select count(*) from $table";
                $data["position"]=$db->count($sql, true);
                $data["enabled"]=1;
                $data["visible"]=1;
                $data["allow_subscriptions"]=1;
                $data["allow_unsubscriptions"]=1;
                $r["date_created"]=time();
                $r["owner_id"]=$ui["id"];
		if ($user_permissions['max_groups']>0 and $db->count($sql." where owner_id='".$ui['id']."'", true)>=$user_permissions['max_groups']) $error->add('{rs:ERROR_LIMIT} {rs:ERROR_LIMIT_MAX_GROUPS}');
        } else {
                $edit=$data["id"];
                $r["date_created"]=$data["date_created"];
                $r["owner_id"]=$data["owner_id"];
        }
        if (isset($save)) {
                $r["title"]=check_string($r["title"], 1);
                $r["position"]=check_position($r["position"]);
                $r["description"]=check_string($r["description"], 1);
                $r["enabled"]=(isset($r["enabled"]) ? 1 : 0);
                $r["visible"]=(isset($r["visible"]) ? 1 : 0);
                $r["allow_subscriptions"]=(isset($r["allow_subscriptions"]) ? 1 : 0);
                $r["allow_unsubscriptions"]=(isset($r["allow_unsubscriptions"]) ? 1 : 0);
                $r["modify_user"]=$ui["id"];
                $r["modify_time"]=time();

                if (!$r["title"]) $error->add("{rs:ERROR_TITLE}");
		if (!$error->count and !isset($access["edit"]) and !isset($access["admin"])) $error->add('{rs:ERROR_ACCESS_RESTRICTED}');
                if (!$error->count) {
                        $fields="date_created, title, position, description, enabled, visible, allow_subscriptions, allow_unsubscriptions, owner_id, modify_user, modify_time";
                        update_position($data["position"], $r["position"]);
                        $sql=($edit ? get_sql_update($table, $fields, $r, "where id='$edit'") : get_sql_insert($table, $fields, $r));
                        $db->execute($sql);
                        $link->add("_r", ($edit ? 2 : 1));
                        if (!$edit and !isset($access["admin"])) {
                                $r=array(
                                        "user_id"       => $ui["id"],
                                        "group_id"      => mysql_insert_id(),
                                );
                                $sql=get_sql_insert($table_um, "user_id, group_id", $r);
                                $db->execute($sql);
                        }
                        $db->close();
                        header("Location: ".$link->get());
                        exit;
                } else {
                        $r["id"]=$edit;
                        $data=html_string($r, true);
                }
        } else $data=html_string($data);
        $page->section("MAILING_GROUPS_EDIT");
        $data["BACK_LINK"]=($link->get() ? $link->get() : './');
        $data["BACK_TITLE"]="{rs:TITLE_MAILING_GROUPS}";
	$data["WINDOW_TITLE"]="{rs:EDIT_MAILING_GROUPS}";
        $data["is_back"]=1;
        $page->assign($data);
} elseif (isset($access["view"]) or isset($access["admin"])) {
        if (isset($edit) or isset($del) or isset($permission)) $error->add("{rs:ERROR_ACCESS_RESTRICTED}");
        $page->section("MAILING_GROUPS");
        $where=get_search_where("title", $_search);
        if (isset($user_permissions['groups_list'])) $where.=($where ? " and " : "where ")."mg.id in (".$user_permissions['groups_list'].")";
        $sql="select count(*) from $table mg $where";
        $count=$db->count($sql, true);
        $i=ceil($count/$n)-1;
        $offset=(($offset>$i) ? $i : ($offset<0 ? 0 : $offset));
        $sql="select mg.*, count(s.id) as count from $table mg
                LEFT JOIN $table_sg sg ON sg.group_id=mg.id
                LEFT JOIN $table_s s ON sg.subscribers_id=s.id
                $where
                group by mg.id
                order by position
                limit ".($offset*$n). ", $n";
        $rs = $db->select($sql);
        for ($i=0; $i<count($rs); $i++) {
                $data=$rs[$i];
                $data["disabled"]=(!$data["visible"] or !$data["enabled"]);
                $page->addrow("LINE", $data);
        }
        $page->assign(array(
                "count"         => $count,
                "offset"        => get_new_offsets($count, $n, $offset_link->get(), $offset),
                "search"        => html_string($_search),
                "BACK_LINK"     => $PATH,
                "BACK_TITLE"    => "{rs:TITLE_MAIN_MENU}",
		"WINDOW_TITLE"	=> "{rs:TITLE_MAILING_GROUPS}",
        ));
        $page->section("SHOW_SEARCH");
} else {
        $page->section("ACCESS_DENIED");
        $error->add("{rs:ERROR_ACCESS_RESTRICTED}");
}
add_to_tree("{rs:TITLE_MAILING_GROUPS}", "mailing_groups/");
$db->close();
$page->assign(array(
        "TITLE"                 => "{rs:TITLE_MAILING_GROUPS}",
        "ERROR"                 => ($error->count ? $error->get() : ""),
        "MESSAGE"               => ($message->count ? $message->get() : ""),
        "LINK"                  => $link->get(),
        "FILTER_LINK"           => $filter_link->get(),
        "is_mailing_groups"     => 1,
        "IMG"                   => $IMG,
));
print $page->evaluate();
?>