<?php

$__super__allow_multiblock__ = [
    "chat"  =>  [
        "name"  =>  "Чат",
        "table" =>  "chat",
        "ai"    =>  "cid",
        "row"   =>  ["uid", "sms", "timeadd"],
    ],
    "gb"  =>  [
        "name"  =>  "Гостевая книга",
        "table" =>  "gb",
        "ai"    =>  "gid",
        "row"   =>  ["uid", "name", "sms", "timeadd", "moder",  "ip", "ua"],
    ],
    "forum_message" =>  [
        "name"  =>  "Форум (сообщения)",
        "table" =>  "forum_message",
        "ai"    =>  "mid",
        "row"   =>  ["cid", "tid", "uid", "name", "sms", "timeadd"],
    ],
    "forum_topics"  =>  [
        "name"  =>  "Форум (темы)",
        "table" =>  "forum_topics",
        "ai"    =>  "tid",
        "row"   =>  ["cid", "uid", "name", "sms", "timeadd", "lastUpdate", "closed", "close_txt", "close_who", "close_time"],
    ],
    "news" =>  [
        "name"  =>  "Новости",
        "table" =>  "news",
        "ai"    =>  "nid",
        "row"   =>  ["uid", "ntitle", "ntext", "ntime"],
    ],
    "users" =>  [
        "name"  =>  "Пользователи",
        "table" =>  "users",
        "ai"    =>  "id",
        "row"   =>  ["id", "login", "email", "ip", "ua", "ipreg"],
    ],
];
# SELECT * FROM `gb` WHERE `sid` = '1' AND `sms` = "actsddsf" ORDER BY `gid` LIMIT 10

function __super_content_chat($super, $mb, $sql){
    global $db, $core;
    $elements	  = [];
    $data         = $db->Query($sql); 
    while ($elem = mysqli_fetch_assoc($data)){
        $elements[] = [
            "id"		=>	$elem["cid"],
            "time"		=>	$elem["timeadd"],
            "message"	=> 	$core->drawString($elem["sms"]),
            "user"		=>	getUserInfo($elem["uid"])
        ];
    }
    return $elements;
}

function __super_content_gb($super, $mb, $sql){
    global $db, $core;
    $elements	  = [];
    $data         = $db->Query($sql); 
    while ($elem = mysqli_fetch_assoc($data)){
        $elements[] = [
            "id"		=>	$elem["gid"],
            "time"		=>	$elem["timeadd"],
            "name"		=>	$elem["name"],
            "message"	=> 	$core->drawString($elem["sms"]),
            "user"		=>	getUserInfo($elem["uid"]),
            "ip"		=>	$elem["ip"],
            "ua"		=>	$elem["ua"],
            "isAuthor"	=>	($core->sverIPUA($elem["ip"], $elem["ua"], $user->uid, $elem["uid"])?1:0),
            "isModer"	=>	($elem["moder"] == 1?true:false),
        ];
    }
    return $elements;
}

function __super_content_news($super, $mb, $sql){
    global $db, $core;
    $elements	  = [];
    $data         = $db->Query($sql); 
    while ($elem = mysqli_fetch_assoc($data)){
        $elements[] = [
            "id"		=>	$elem["nid"],
            "time"		=>	$elem["ntime"],
            "title"		=> 	$core->drawString($elem["ntitle"]),
            "message"	=> 	$core->drawString($elem["ntext"]),
            "user"		=>	getUserInfo($elem["uid"]),
        ];
    }
    return $elements;
}

function __super_content_users($super, $mb, $sql){
    global $db, $core;
    $elements	  = [];
    $data         = $db->Query($sql); 
    while ($elem = mysqli_fetch_assoc($data)){
        $usr = getUserInfo($elem["id"]);
	    $elements[$elem["id"]] = getUserInfo($elem["id"]);
    }
    return $elements;
}

function __super_multiblock__($super = []){
    global $core, $site, $db, $__super__allow_multiblock__;
    if (!isset($__super__allow_multiblock__[$super["multiblock"]])) return [];
    $mb     = $__super__allow_multiblock__[$super["multiblock"]];
    $sql    = "SELECT * FROM `".$mb["table"]."` WHERE `sid` = '".$site->id."'";
    if ($super["isSelected"] and in_array($super["selectKey"], $mb["row"])){
        $input  = "";
        $xin    = $super["selectVal"];
        if ($super["selectMet"] == "POST"){
            $input  = isset($_POST[$xin])?$core->FilterString($_POST[$xin]):"";
        } else {
            $input  = isset($_GET[$xin])?$core->FilterString($_GET[$xin]):"";
        }
        $sql   .= " AND `".$super["selectKey"]."` ".($super["selectHard"]?"= '".$input."'":"LIKE '%".$input."%'");
    }

    $sql .= " ORDER BY `".$mb["ai"]."` ".($super["sort"] == "DESC"?"DESC":"ASC");
    if ($super["limit"] > 0){
        $sql .= " LIMIT ".intval($super["limit"]);
    }
    #echo ellynet($sql);
    $is_fun = function_exists("__super_content_".$mb["table"]);
    if ($is_fun){
        $fun = "__super_content_".$mb["table"];
        return $fun($super, $mb, $sql);
    } else {
        echo ellynet("Функционал для <var>".$mb["name"]."</var> на данный момент еще не реализован. Следите за обновлениями.");
        return [];
    }
}

function __super_default__(){
    $array = [];
    #$array["blockID"]           = "MyBlockID";         ///! Стандартный ID блока
    $array["path"]              = "/default.lm";        ///! Наименование пути по-умолчанию
    $array["limit"]             = 10;                   ///! Кол-во элементов которое выводится
    $array["multiblock"]        = "default";            ///! Колонка в БД которую обрабатываем
    $array["isSelected"]        = false;                ///! Делаем ли выборку?
    $array["selectKey"]         = "";                   ///! Выборка ключа из таблицы
    $array["selectVal"]         = "";                   ///! Выборка значения по методу
    $array["selectMet"]         = "GET";                ///! Метод для выборки (GET || POST)
    $array["selectHard"]        = true;                 ///! Жесткий поиск или легкий
    $array["sort"]              = "ASC";                ///! Выбор сортировки данных
    return $array;
}

function __super_load__($blockID = "MyBlockID", $array = []){
    global $core;
    $reset = __super_default__();
    if ($array == NULL) return $reset;
    foreach ($array as $key => $val){
        if (!isset($reset[$key])) continue;
        $reset[$key] = $core->FilterString($val);
    }

    $reset["blockID"]           = $blockID;    
    $reset["data"]              = [];                   ///! Конечные данные
    return $reset;
}

function addon_twig_super($blockID){
	global $db, $core, $site;
	$siteID 	= intval($site->id);
	$blockID 	= $core->FilterString($blockID);
	$block 		= $db->getObject("SELECT `config` FROM `superblock` WHERE `sid` = '".$siteID."' AND `blockID` = '".$blockID."' LIMIT 1");
	if ($block == NULL){
		return ellynet("Блок <var>".$blockID."</var> не найден.");
	}
	if ($block->config == NULL){
		return ellynet("Блок <var>".$blockID." </var> поврежден. Выполните реконфигурацию блока.");
	}
	$super = json_decode($block->config, true);
	if ($super == NULL || !isset($super["path"])){
		return ellynet("Блок <var>".$blockID."</var> поврежден. Выполните реконфигурацию блока.");
	}

    $super      = __super_load__($blockID, $super);     ///! Выполняем прогрузку значений по-умолчанию а также прогружаем конфигурацию
	$mb         = __super_multiblock__($super);         ///! Генерируем контент
	$pathinfo = pathinfo($super["path"], PATHINFO_EXTENSION);
	if ($pathinfo != "html") return ellynet("Файл <var>".$super["path"]."</var> не является html-страницей");
	twig($super["path"], [
        "elems" =>  $mb,
        "count" =>  count($mb)
    ], true, false);
	return false;
}