<?php

use App\System\Basic\beRouter;
use App\System\Controller\CartController;
use App\System\Model\AlertModel;
use App\System\Model\AttachmentModel;
use App\System\Model\CartModel;
use App\System\Model\CurrencyModel;
use App\System\Model\InvoiceModel;
use App\System\Model\MenuModel;
use App\System\Model\TicketModel;
use App\System\Model\UserGroupModel;
use App\System\Model\UserInfoModel;
use App\System\Model\UserProductModel;
use App\System\Vendor\Auth;
use App\System\Vendor\bePlugin;

function beStartTemplates($rhcontact = true,$rhcontactphone = false,$rfcontact = false,$contentup = ""){
    global $headerinclude,$header,$footer;
	$headerinclude = [];
	$header = [];
	$footer = [];
    $headerinclude = beGetView("header.headerinclude");
    $user = Auth::beGetUser();
	$uid = $user["uid"];
	bePlugin::beRunHook("template_preparation_pre");
	if($uid){
		if($user["money"] > 0){
			$header["hmoney"] = "({$user['money']}₺)";
		}
		if($user["group"]["ugpermissions"]["ticket_list"] == 1){
			$ticket_count = TicketModel::beSelect("COUNT(tid) as total")->beWhere("tstatus","active")->beWhere("tlastreply","user")->beGet()["total"];
			$header["ticketcount"] = $ticket_count;
		}
        $alerts = AlertModel::beWhere("uid",$uid)->beWhere("astatus","1")->beOrder("aid","ASC")->beLimit(5)->beGetAll();
        $alertcount = count($alerts);
        if($alertcount){
            $header["halerttext"] = "<span>{$alertcount}</span>";
        }
        $header["halerts"] = beGetView("header.alerts",["alerts" => $alerts,"alertcount" => $alertcount]);
		$header["haltlogout"] = "<li class=\"mm-listitem\"><a href=\"".beGetRoute("auth.logout")."\" onclick=\"return confirm('Çıkış yapmak istediğinize emin misiniz?')\" class=\"mm-listitem__text\">Çıkış Yap</a></li>";
		$temp["user"] = beGetView("header.member",["header" => $header]);
	}
	else{
		$temp["user"] = beGetView("header.guest");
	}
	$temp["contentup"] = $contentup;
	if($rhcontact){
		$contact = "";
		if($rhcontactphone){
            $contact = beGetView("header.phone");
		}
		else{
			global $navbits;
			if(!$navbits){
				$navbits = [];
			}
			array_unshift($navbits,["name" => beGetConfig("sitename"),"url" => beGetConfig("siteurl")]);
			$navcount = count($navbits);
			if($navcount){
				$navitems = "";
				for($i = 0; $i < $navcount; $i++){
					$nav = $navbits[$i];
					if($i != $navcount-1){
						$navitems .= beGetView("header.navitem",["nav" => $nav]);
					}
					else{
						$navitems .= beGetView("header.navitemlast",["nav" => $nav]);
					}
				}
				$contact = beGetView("header.breadcumb",["navitems" => $navitems]);
			}
			else{
				$contact = beGetView("header.phone");
			}
		}
        $temp["contact"] = $contact;
	}
	$menus = json_decode(beGetCache("menus".$user["lid"]),true);
	$temp["menus"] = $menus;
	$cart = new CartController();
	$temp["cart"] = $cart->get_user_cart();
    $header = beGetView("header.header",["temp" => $temp]);
	$header = bePlugin::beRunHook("template_preparation_header",["header" => $header])["header"];
    $temp = [];
	if($rfcontact){
        $temp["contact"] = beGetView("footer.contact");
	}
	$temp["menus"] = $menus;
    $footer = beGetView("footer.footer",["temp" => $temp]);
	$footer = bePlugin::beRunHook("template_preparation_footer",["footer" => $footer])["footer"];
	bePlugin::beRunHook("template_preparation_post");
}
function beGetRouteName(){
	return beRouter::$beActiveName;
}
function beConvertCurrencie($price,$cur1,$cur2){
	return CurrencyModel::beConvertCurrencie($price,$cur1,$cur2);
}
function beSetHeaderContent($contentup = "",$type = 0){
	if($type == 1){
		$user = Auth::beGetUser();
        $userinfo = UserInfoModel::beWhere("uid",$user["uid"])->beGet();
		$userinfo["uisettings"] = json_decode($userinfo["uisettings"],true);
		$currency = [];
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        foreach($currencies as $usercurrency){
            if($usercurrency["cid"] == $user["cid"]){
                $currency = $usercurrency;
            }
        }
		$product_count = UserProductModel::beSelect("COUNT(upid) as total")->beWhere("uid",$user["uid"])->beWhere("upstatus","-1","!=")->beGet()["total"];
        $ticket_count = TicketModel::beSelect("COUNT(tid) as total")->beWhere("uid",$user["uid"])->beWhere("tstatus","active")->beGet()["total"];
        $invoice_count = InvoiceModel::beSelect("COUNT(iid) as total")->beWhere("uid",$user["uid"])->beWhere("istatus","0")->beGet()["total"];
		$contentup = beGetView("clientarea.headercontent",["user" => $user,"userinfo" => $userinfo,"currency" => $currency,"ticket_count" => $ticket_count,"product_count" => $product_count,"invoice_count" => $invoice_count]);
	}
	if($contentup){
		beStartTemplates(true,false,false,$contentup);
	}
	else{
		beStartTemplates(true,false,true);
	}
}
function beGetAttachmentUrl($aid){
	$attachment = AttachmentModel::beSelect("aid,aslug")->beWhere("aid",$aid)->beGet();
	if(!$attachment){
		return "";
	}
	return beGetRoute("file.show",["slug" => $attachment["aslug"],"aid" => $attachment["aid"]]);
}
function beMoneyFormat($number,$dec = 2){
	return number_format($number,$dec,",",".");
}
function beReveseMoneyFormat($number){
	return (double)str_replace([".",","],["","."],$number);
}
function beDisplayTime($time,$timevalue = ""){
	if(!$time){
		$time =  BE_TIME;
	}
	return date("d.m.Y{$timevalue}",$time);
}
function beSpecialTime($time,$timevalue = ""){
	$timenow = BE_TIME;
	$today = strtotime("today");
	$diffrence = $timenow-$time;
	$yesterday = $today-86400;
	if($time > $today && $diffrence > 0){
		return "Bugün, ".date("H:i",$time);
	}
	if($time > $yesterday && $diffrence > 0){
		return "Dün, ".date("H:i",$time);
	}
	return date("d.m.Y{$timevalue}",$time);
}
function beConvertTime($time){
	if($time >= 31104000){
		return round($time/31104000)." yıl";
	}
	else if($time >= 2592000){
		return round($time/2592000)." ay";
	}
	else if($time >= 604800){
		return round($time/604800)." hafta";
	}
	else if($time >= 86400){
		return round($time/86400)." dakika";
	}
	else if($time >= 3600){
		return round($time/3600)." saat";
	}
	else if($time >= 60){
		return round($time/60)." dakika";
	}
	return $time." saniye";
}
function beCheckPermission($permission,$ugid){
	return UserGroupModel::beCheckPermission($ugid,$permission);
}
function beSelfLink($str){
    $str = mb_convert_encoding((string)$str,"UTF-8",mb_list_encodings());
    $char_map = [
		"@" => "at", "c#" => "c-sharp", "c++" => "cpp", "$" => "dolar", "?" => "try", "#" => "hashtag-",
        "À" => "A", "Á" => "A", "Â" => "A", "Ã" => "A", "Ä" => "A", "Å" => "A", "Æ" => "AE", "Ç" => "C",
        "È" => "E", "É" => "E", "Ê" => "E", "Ë" => "E", "Ì" => "I", "Í" => "I", "Î" => "I", "Ï" => "I",
        "?" => "D", "Ñ" => "N", "Ò" => "O", "Ó" => "O", "Ô" => "O", "Õ" => "O", "Ö" => "O", "O" => "O",
        "Ø" => "O", "Ù" => "U", "Ú" => "U", "Û" => "U", "Ü" => "U", "U" => "U", "Y" => "Y", "?" => "TH",
        "ß" => "ss",
        "à" => "a", "á" => "a", "â" => "a", "ã" => "a", "ä" => "a", "å" => "a", "æ" => "ae", "ç" => "c",
        "è" => "e", "é" => "e", "ê" => "e", "ë" => "e", "ì" => "i", "í" => "i", "î" => "i", "ï" => "i",
        "?" => "d", "ñ" => "n", "ò" => "o", "ó" => "o", "ô" => "o", "õ" => "o", "ö" => "o", "o" => "o",
        "ø" => "o", "ù" => "u", "ú" => "u", "û" => "u", "ü" => "u", "u" => "u", "y" => "y", "?" => "th",
        "ÿ" => "y",
        "©" => "(c)",
        "?" => "A", "?" => "B", "?" => "G", "?" => "D", "?" => "E", "?" => "Z", "?" => "H", "?" => "8",
        "?" => "I", "?" => "K", "?" => "L", "?" => "M", "?" => "N", "?" => "3", "?" => "O", "?" => "P",
        "?" => "R", "?" => "S", "?" => "T", "?" => "Y", "?" => "F", "?" => "X", "?" => "PS", "?" => "W",
        "?" => "A", "?" => "E", "?" => "I", "?" => "O", "?" => "Y", "?" => "H", "?" => "W", "?" => "I",
        "?" => "Y",
        "?" => "a", "ß" => "b", "?" => "g", "?" => "d", "?" => "e", "?" => "z", "?" => "h", "?" => "8",
        "?" => "i", "?" => "k", "?" => "l", "µ" => "m", "?" => "n", "?" => "3", "?" => "o", "?" => "p",
        "?" => "r", "?" => "s", "?" => "t", "?" => "y", "?" => "f", "?" => "x", "?" => "ps", "?" => "w",
        "?" => "a", "?" => "e", "?" => "i", "?" => "o", "?" => "y", "?" => "h", "?" => "w", "?" => "s",
        "?" => "i", "?" => "y", "?" => "y", "?" => "i",
        "Ş" => "S", "İ" => "I", "Ç" => "C", "Ü" => "U", "Ö" => "O", "Ğ" => "G",
        "ş" => "s", "ı" => "i", "ç" => "c", "ü" => "u", "ö" => "o", "ğ" => "g",
        "?" => "A", "?" => "B", "?" => "V", "?" => "G", "?" => "D", "?" => "E", "?" => "Yo", "?" => "Zh",
        "?" => "Z", "?" => "I", "?" => "J", "?" => "K", "?" => "L", "?" => "M", "?" => "N", "?" => "O",
        "?" => "P", "?" => "R", "?" => "S", "?" => "T", "?" => "U", "?" => "F", "?" => "H", "?" => "C",
        "?" => "Ch", "?" => "Sh", "?" => "Sh", "?" => "", "?" => "Y", "?" => "", "?" => "E", "?" => "Yu",
        "?" => "Ya",
        "?" => "a", "?" => "b", "?" => "v", "?" => "g", "?" => "d", "?" => "e", "?" => "yo", "?" => "zh",
        "?" => "z", "?" => "i", "?" => "j", "?" => "k", "?" => "l", "?" => "m", "?" => "n", "?" => "o",
        "?" => "p", "?" => "r", "?" => "s", "?" => "t", "?" => "u", "?" => "f", "?" => "h", "?" => "c",
        "?" => "ch", "?" => "sh", "?" => "sh", "?" => "", "?" => "y", "?" => "", "?" => "e", "?" => "yu",
        "?" => "ya",
        "?" => "Ye", "?" => "I", "?" => "Yi", "?" => "G",
        "?" => "ye", "?" => "i", "?" => "yi", "?" => "g",
        "C" => "C", "D" => "D", "E" => "E", "N" => "N", "R" => "R", "Š" => "S", "T" => "T", "U" => "U",
        "Z" => "Z",
        "c" => "c", "d" => "d", "e" => "e", "n" => "n", "r" => "r", "š" => "s", "t" => "t", "u" => "u",
        "z" => "z",
        "A" => "A", "C" => "C", "E" => "e", "L" => "L", "N" => "N", "Ó" => "o", "S" => "S", "Z" => "Z",
        "Z" => "Z",
        "a" => "a", "c" => "c", "e" => "e", "l" => "l", "n" => "n", "ó" => "o", "s" => "s", "z" => "z",
        "z" => "z",
        "A" => "A", "C" => "C", "E" => "E", "G" => "G", "I" => "i", "K" => "k", "L" => "L", "N" => "N",
        "Š" => "S", "U" => "u", "Z" => "Z",
        "a" => "a", "c" => "c", "e" => "e", "g" => "g", "i" => "i", "k" => "k", "l" => "l", "n" => "n",
        "š" => "s", "u" => "u", "z" => "z"
    ];
    $str = str_replace(array_keys($char_map),$char_map,$str);
    $str = preg_replace("/[^\p{L}\p{Nd}]+/u","-",$str);
    $str = preg_replace("/(".preg_quote("-","/")."){2,}/","$1",$str);
    $str = mb_substr($str,0,mb_strlen($str,"UTF-8"),"UTF-8");
    $str = trim($str,"-");
    return mb_strtolower($str,"UTF-8");
}
?>