<?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="custom_fields".$config["table_prefix"];
$table_scf="scf".$config["table_prefix"];
$access=check_level("Custom Fields");

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

$message_list=array(
        1 => "{rs:MSG_CUSTOM_FIELD} {rs:MSG_CREATED}",
        2 => "{rs:MSG_CUSTOM_FIELD} {rs:MSG_UPDATED}",
        3 => "{rs:MSG_CUSTOM_FIELDS} {rs:MSG_DELETED}",
);

$type_list=array(
        "checkbox"      => "{rs:FIELDS_TYPE_CHECKBOX}",
        "password"      => "{rs:FIELDS_TYPE_PASSWORD}",
        "radio"         => "{rs:FIELDS_TYPE_RADIO}",
        "select"        => "{rs:FIELDS_TYPE_SELECT}",
        "text"          => "{rs:FIELDS_TYPE_TEXT}",
        "textarea"      => "{rs:FIELDS_TYPE_TEXTAREA}",
);

$validation_list=array(
        "0"     => "{rs:VALIDATION_TYPE_0}",
        "n"     => "{rs:VALIDATION_TYPE_N}",
        "c"     => "{rs:VALIDATION_TYPE_C}",
        "nc"    => "{rs:VALIDATION_TYPE_NC}",
        "mail"  => "{rs:VALIDATION_TYPE_MAIL}",
        "url"   => "{rs:VALIDATION_TYPE_URL}",
);

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

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

$message=new Message();
$error=new Message("error");
if (isset($_r)) $message->add($message_list[$_r]);
if (isset($del) and (isset($access["delete"]) or isset($access["admin"]))) {
        $del=(is_array($del) ? implode($del, ", ") : $del);
        $where="where id in ($del)";
        //if (!isset($access["admin"])) $where.=" and owner_id='".$ui["id"]."'";
        $sql="select id, position, owner_id from $table $where order by position desc";
        $rs=$db->select($sql);
        $del="";
        for ($i=0; $i<count($rs); $i++) {
                $sql="update $table set position=position-1 where position>".$rs[$i]["position"];//." and owner_id='".$rs[$i]["owner_id"]."'";
                $db->execute($sql);
                $del.=($del ? ", " : "").$rs[$i]["id"];
        }
        $sql=array();
        $sql[]="delete from $table where id in ($del)";
        $sql[]="delete from $table_scf where cusom_field_id in ($del)";
        $db->execute_all($sql);
        $link->add("_r", 3);
        $db->close();
        header("Location: ".$link->get());
        exit;
} elseif (isset($edit) and (isset($access["edit"]) or isset($access['view']) or isset($access["admin"]))) {
        $where="where id='$edit'";
        //if (!isset($access["admin"])) $where.=" and owner_id='".$ui["id"]."'";
        $sql="select * from $table $where";
        $rs=$db->select($sql);
        $data=$rs[0];
        if (!isset($data["id"])) {
                $edit=0;
                $sql="select count(*) from $table";// where owner_id='".$ui["id"]."'";
                $data["position"]=$db->count($sql, true);
                $data["type"]="text";
                $r["date_created"]=time();
                $r["owner_id"]=$ui["id"];
        } else {
                $edit=$data["id"];
                $r["date_created"]=$data["date_created"];
                $r["owner_id"]=$data["owner_id"];
        }
        if (isset($save) and $save) {
                $is_list_val=in_array($r["type"], array("radio", "select"));
                check_array($r);
                $r["position"]=check_position($r["position"], $r["owner_id"]);
                $r["type"]=(isset($type_list[$r["type"]]) ? $r["type"] : "text");
                $r["modify_user"]=$ui["id"];
                $r["modify_time"]=time();
                $r["enabled"]=isset($r["enabled"]);
                $r["not_null"]=isset($r["not_null"]);
                $def_value=validation($r["def_value"], $r["validation"]);
                if (!$r["title"]) $error->add("{rs:ERROR_TITLE}");
                if (!$r["list_val"] and $is_list_val) $error->add("{rs:ERROR_FIELDS}");
                if (!$def_value and $r["def_value"]) $error->add("{rs:ERROR_DEF_VALUE_FORMAT}");
		if (!$error->count and !isset($access["edit"]) and !isset($access["admin"])) $error->add('{rs:ERROR_ACCESS_RESTRICTED}');
                if (!$error->count) {
                        update_position($data["position"], $r["position"], $r["owner_id"]);
                        $r["def_value"]=$def_value;
                        $fields="position, title, type, validation, def_value, enabled, list_val, not_null, owner_id, modify_user, modify_time";
                        $sql=($edit ? get_sql_update($table, $fields, $r, "where id='$edit'") : get_sql_insert($table, $fields, $r));
                        $db->execute($sql);
                        $db->close();
                        $link->add("_r", ($edit ? 2 : 1));
                        header("Location: ".$link->get());
                        exit;
                } else {
                        $r["id"]=$edit;
                        $data=html_string($r, true);
                }
        } elseif (isset($save)) {
                $data=html_string($r, true);
        } else $data=html_string($data);
        $is_list_val=in_array($data["type"], array("radio", "select"));
        get_row_from_array("TYPE_SELECT", $type_list, $data["type"]);
        get_row_from_array("VALIDATION_SELECT", $validation_list, $data["validation"]);
        $data["is_list_val"]=$is_list_val;
        $data["BACK_LINK"]=($link->get() ? $link->get() : './');
        $data["BACK_TITLE"]="{rs:TITLE_CUSTOM_FIELDS}";
	$data["WINDOW_TITLE"]="{rs:EDIT_CUSTOM_FIELDS}";
        $page->section("CUSTOM_FIELDS_EDIT");
        $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("CUSTOM_FIELDS");
        //$where=(!isset($access["admin"]) ? "where owner_id='".$ui["id"]."'" : "");
        $sql="select count(*) from $table $where";
        $rs=$db->select($sql);
        $count=$rs[0][0];
        $i=ceil($count/$n)-1;
        $offset=(($offset>$i) ? $i : ($offset<0 ? 0 : $offset));
        $sql="select * from $table $where order by position, title limit ".($offset*$n). ", $n";
        $rs = $db->select($sql);
        for ($i=0; $i<count($rs); $i++) {
                $data=$rs[$i];
                $data["disabled"]=!$data["enabled"];
                $page->addrow("LINE", $data);
        }
        $page->assign(array(
                "count"         => $count,
                "offset"        => get_new_offsets($count, $n, $offset_link->get(), $offset),
                "BACK_LINK"     => $PATH."subscribers/",
                "BACK_TITLE"    => "{rs:TITLE_SUBSCRIBERS}",
		"WINDOW_TITLE"	=> "{rs:TITLE_CUSTOM_FIELDS}",
        ));
} else {
        $page->section("ACCESS_DENIED");
        $error->add("{rs:ERROR_ACCESS_RESTRICTED}");
}
add_to_tree("{rs:TITLE_SUBSCRIBERS}", "subscribers/");
add_to_tree("{rs:TITLE_CUSTOM_FIELDS}", "subscribers/custom_fields/");
$db->close();
$page->assign(array(
        "TITLE"                 => "{rs:TITLE_CUSTOM_FIELDS}",
        "ERROR"                 => ($error->count ? $error->get() : ""),
        "MESSAGE"               => ($message->count ? $message->get() : ""),
        "LINK"                  => $link->get(),
        "FILTER_LINK"           => $filter_link->get(),
        "is_subscribers"        => 1,
        "IMG"                   => "custom_fields.gif",
));
print $page->evaluate();
?>