<?php

namespace App\System\Controller;

use App\System\Basic\beCache;
use App\System\Basic\beContoller;
use App\System\Basic\beModel;
use App\System\Basic\beRouter;
use App\System\Basic\beViewer;
use App\System\Model\LanguageModel;
use App\System\Model\PageModel;
use App\System\Model\PageTranslationsModel;
use App\System\Model\ProductCategoriesModel;
use App\System\Model\ThemePageModel;
use App\System\Vendor\Auth;
use App\System\Vendor\Basic\beCookie;
use App\System\Vendor\beLanguage;
use App\System\Vendor\bePlugin;

class PageController extends beContoller {
    public function list(){
        $languages = LanguageModel::beGetLanguages("lid,lname");
        $pagetypes = PageModel::beGetPageTypes();
        return beGetView("admin.page.list",["languages" => $languages,"pagetypes" => $pagetypes]);
    }
    public function add(){
        global $be;
        $languages = LanguageModel::beGetLanguages("lid,lname");
        $systemlid = $be->settings["system_language"];
        return beGetView("admin.page.add",["languages" => $languages,"systemlid" => $systemlid]);
    }
    public function add_post(){
        global $be;
        beLanguage::beReadLang("page");
        $pid = PageModel::beInsert([
            "tid" => (int)$be->settings["system_theme"],
            "ptype" => "special",
            "pgroups" => "",
            "predirect" => "",
            "pdefault" => "0",
            "pdateline" => BE_TIME
        ]);
        $languages = LanguageModel::beSelect("lid,lname")->beWhere("lstatus",1)->beGetAll();
        foreach($languages as $language){
            $ptcode = $_POST["ptcode"][(int)$language["lid"]];
            $slug = $_POST["ptslug"][(int)$language["lid"]] ? $_POST["ptslug"][(int)$language["lid"]]:beSelfLink($_POST["pttitle"][(int)$language["lid"]]);
            if($slug[0] != "/"){
                $slug = "/".$slug;
            }
            if($ptcode){
                PageTranslationsModel::beInsert([
                    "lid" => $language["lid"],
                    "pid" => $pid,
                    "ptcode" => $ptcode,
                    "ptname" => $_POST["ptname"][(int)$language["lid"]],
                    "pttitle" => $_POST["pttitle"][(int)$language["lid"]],
                    "ptdescription" => $_POST["ptdescription"][(int)$language["lid"]],
                    "ptslug" => $slug,
                    "pteval" => $_POST["pteval"][(int)$language["lid"]],
                    "ptheader" => $_POST["ptheader"][(int)$language["lid"]],
                    "ptcontentup" => $_POST["ptcontentup"][(int)$language["lid"]],
                    "ptcontent" => $_POST["ptcontent"][(int)$language["lid"]],
                    "ptjavascript" => $_POST["ptjavascript"][(int)$language["lid"]],
                    "ptdateline" => BE_TIME
                ]);
            }
        }
        return beAjaxSuccess(["message" => beGetLang("page_created")]);
    }
    public function delete_post(){
        beLanguage::beReadLang("page");
        $pid = (int)$_POST["pid"];
        $page = PageModel::beSelect("pid")->beWhere("pid",$pid)->beGet();
        if(!$page){
            return beAjaxError(["message" => beGetLang("page_not_found")]);
        }
        PageModel::beDelete()->beWhere("pid",$page["pid"])->beExecute();
        PageTranslationsModel::beDelete()->beWhere("pid",$page["pid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("page_deleted_successfully")]);
    }
    public function show($pid){
        beLanguage::beReadLang("page");
        global $be;
        $page = PageModel::beWhere("pid",$pid)->beGet();
        if(!$page){
            beError(beGetLang("page"),beGetLang("page_not_found"));
        }
        $pagetranslations = PageTranslationsModel::beWhere("pid",$page["pid"])->beGetAll();
        $languages = LanguageModel::beGetLanguages("lid,lname");
        $systemlid = $be->settings["system_language"];
        $themepage = [];
        $category = [];
        if($page["pcid"]){
            $category = ProductCategoriesModel::beWhere("pcid",$page["pcid"])->beGet();
            $themepage = ThemePageModel::beSelect("tppagedata")->beWhere("tpid",$category["pcpagetype"])->beGet();
            $themepage["tppagedata"] = json_decode($themepage["tppagedata"],true);
            foreach($pagetranslations as $key => $pagetranslation){
                $ptdata = json_decode($pagetranslation["ptdata"],true);
                foreach($ptdata as $position => $item){
                    $itemdatatext = "";
                    foreach($themepage["tppagedata"]["pageitems"] as $itemkey => $itemdata){
                        if($item["mainkey"] == $itemkey){
                            $itemdatatext .= $this->beRenderOption($pagetranslation["lid"],$itemkey,$position,0,$item,$itemdata["keys"]);
                            $ptdata[$position]["html"] = beGetView("admin.page.themepagearea",["lid" => $pagetranslation["lid"],"position" => $position,"itemkey" => $item["mainkey"],"itemdatatext" => $itemdatatext,"baseitem" => $itemdata]);
                            break;
                        }
                    }
                }
                $pagetranslations[$key]["ptdata"] = $ptdata;
            }
        }
        $editortype = $_GET["editor"];
        if(!$editortype){
            $editortype = "tiny";
        }
        return beGetView("admin.page.show",["page" => $page,"category" => $category,"pagetranslations" => $pagetranslations,"themepage" => $themepage,"editortype" => $editortype,"languages" => $languages,"systemlid" => $systemlid]);
    }
    private function beRenderOption($lid,$itemkey,$position,$cycletime,$item,$itemdatakeys,$mask = "",$createmode = false){
        $itemdata = "";
        $altarray = isset($itemdatakeys["altarray"]) ? $itemdatakeys["altarray"]:"";
        $multpile = isset($itemdatakeys["multpile"]) ? $itemdatakeys["multpile"]:"";
        foreach($itemdatakeys as $itemdatakey => $itemdatakeyvalue){
            if($itemdatakey == "altarray" || $itemdatakey == "multpile" || $itemdatakey == "mainkey"){
                continue;
            }
            if($itemdatakey == $altarray){
                if($multpile == $altarray){
                    $cycletime += 1;
                    $extracss = "";
                    $breakfor = false;
                    $itemdata .= '<div id="area-'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']">';
                    foreach($item[$altarray] as $altitemkey => $altitemvalue){
                        if($cycletime == 2){
                            $extracss = " bg-light";
                        }
                        if(is_string($altitemkey)){
                            $altitemkey = 0;
                            $breakfor = true;
                        }
                        $itemdata .= '<div class="card my-3 py-3'.$extracss.'" id="area-'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$altitemkey.']"><div class="row mb-9 px-10">';
                        if(is_string($altitemvalue)){
                            $altitemvalue = $itemdatakeys[$altarray];
                        }
                        $itemdata .= $this->beRenderOption($lid,$itemkey,$position,$cycletime,$altitemvalue,$itemdatakeys[$altarray],$mask.'['.$itemdatakey.']['.$altitemkey.']',$createmode);
                        switch($cycletime){
                            case 1 : 
                                $itemdata .= '<div class="d-flex flex-center my-3">';
                                $itemdata .= '<button class="btn btn-danger beDeleteArea col-md-4 mx-3" data-areaname="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$altitemkey.']">Sil</button>';
                                $itemdata .= '</div>';
                                break;
                            case 2 : 
                                $itemdata .= '<div class="d-flex flex-center my-3">';
                                $itemdata .= '<button class="btn btn-danger beDeleteArea col-md-1 mx-3" data-areaname="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$altitemkey.']">Sil</button>';
                                $itemdata .= '</div>';
                                break;
                            
                        }
                        $itemdata .= '</div></div>';
                        if($breakfor){
                            break;
                        }
                    }
                    $itemdata .= '</div>';
                    switch($cycletime){
                        case 1 : 
                            $itemdata .= '<div class="d-flex flex-center">';
                            $itemdata .= '<button class="btn btn-primary copyAreaLine col-md-4 mx-3" data-areaname="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'" data-lastitem="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$altitemkey.']" data-lastitemkey="['.$itemdatakey.']['.$altitemkey.']" data-lastkey="'.$altitemkey.'">Yeni Satır Ekle</button>';
                            $itemdata .= '</div>';
                            break;
                        case 2 : 
                            $itemdata .= '<div class="d-flex flex-center">';
                            $itemdata .= '<button class="btn btn-success copyAreaLine col-md-4 mx-3" data-areaname="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'" data-lastitem="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$altitemkey.']" data-lastitemkey="['.$itemdatakey.']['.$altitemkey.']" data-lastkey="'.$altitemkey.'">Yeni Satır Ekle</button>';
                            $itemdata .= '</div>';
                            break;                         
                    }
                }
                continue;
            }
            if($altarray == "" && $multpile == $itemdatakey){
                $itemdata .= '<div class="row mb-9 px-10" id="area-'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']">';
                if($createmode == false){
                    foreach($item[$itemdatakey] as $altitemkey => $altitemvalue){
                        if($itemdatakeyvalue["type"] == "textarea"){
                            $itemdata .= '<div class="'.$itemdatakeyvalue["class"].' mb-1" id="area-'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$altitemkey.']"><label class="fs-6 fw-semibold mb-2 text-gray-500">'.$itemdatakeyvalue["name"].'</label><div class="d-flex flex-center"><textarea class="form-control" rows="4" name="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$altitemkey.']">'.$item[$itemdatakey].'</textarea><a data-bs-toggle="tooltip" class="btn btn-danger beDeleteArea mx-3" data-areaname="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$altitemkey.']" data-kt-initialized="1"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="15" fill="currentColor"><path fill="none" d="M0 0h24v24H0z"></path><path d="M7 4V2h10v2h5v2h-2v15a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6H2V4h5zM6 6v14h12V6H6zm3 3h2v8H9V9zm4 0h2v8h-2V9z"></path></svg></a></div></div>';
                        }
                        else{
                            $itemdata .= '<div class="'.$itemdatakeyvalue["class"].'" id="area-'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$altitemkey.']"><label class="fs-6 fw-semibold mb-2 text-gray-500">'.$itemdatakeyvalue["name"].'</label><div class="d-flex flex-center"><input type="text" class="form-control" name="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$altitemkey.']" value="'.$altitemvalue.'"><a data-bs-toggle="tooltip" class="btn btn-danger beDeleteArea mx-3" data-areaname="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$altitemkey.']" data-kt-initialized="1"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="15" fill="currentColor"><path fill="none" d="M0 0h24v24H0z"></path><path d="M7 4V2h10v2h5v2h-2v15a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6H2V4h5zM6 6v14h12V6H6zm3 3h2v8H9V9zm4 0h2v8h-2V9z"></path></svg></a></div></div>';
                        }
                    }
                }
                else{
                    $counter = 0;
                    foreach($item[$itemdatakey] as $altitemkey => $altitemvalue){
                        if($itemdatakeyvalue["type"] == "textarea"){
                            $itemdata .= '<div class="'.$itemdatakeyvalue["class"].' mb-1" id="area-'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$counter.']"><label class="fs-6 fw-semibold mb-2 text-gray-500">'.$itemdatakeyvalue["name"].'</label><div class="d-flex flex-center"><textarea class="form-control" rows="4" name="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$counter.']">'.$item[$itemdatakey].'</textarea><a data-bs-toggle="tooltip" class="btn btn-danger beDeleteArea mx-3" data-areaname="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$counter.']" data-kt-initialized="1"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="15" fill="currentColor"><path fill="none" d="M0 0h24v24H0z"></path><path d="M7 4V2h10v2h5v2h-2v15a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6H2V4h5zM6 6v14h12V6H6zm3 3h2v8H9V9zm4 0h2v8h-2V9z"></path></svg></a></div></div>';
                        }
                        else{
                            $itemdata .= '<div class="'.$itemdatakeyvalue["class"].'" id="area-'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$counter.']"><label class="fs-6 fw-semibold mb-2 text-gray-500">'.$itemdatakeyvalue["name"].'</label><div class="d-flex flex-center"><input type="text" class="form-control" name="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$counter.']" value="'.$altitemvalue.'"><a data-bs-toggle="tooltip" class="btn btn-danger beDeleteArea mx-3" data-areaname="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']['.$counter.']" data-kt-initialized="1"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="15" fill="currentColor"><path fill="none" d="M0 0h24v24H0z"></path><path d="M7 4V2h10v2h5v2h-2v15a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6H2V4h5zM6 6v14h12V6H6zm3 3h2v8H9V9zm4 0h2v8h-2V9z"></path></svg></a></div></div>';
                        }
                        $counter += 1;
                        break;
                    }
                }
                $itemdata .= '</div>';
                if($createmode == false){
                    $itemdata .= '<button class="btn btn-success d-block m-auto addNewLine col-md-4" data-labelname="'.$itemdatakeyvalue["name"].'" data-type="'.$itemdatakeyvalue["type"].'" data-class="'.$itemdatakeyvalue["class"].'" data-lastkeydata="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']" data-lastkey="'.$altitemkey.'">Yeni Veri Ekle</button>';
                }
                else{
                    $itemdata .= '<button class="btn btn-success d-block m-auto addNewLine col-md-4" data-labelname="'.$itemdatakeyvalue["name"].'" data-type="'.$itemdatakeyvalue["type"].'" data-class="'.$itemdatakeyvalue["class"].'" data-lastkeydata="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']" data-lastkey="'.$counter.'">Yeni Veri Ekle</button>';    
                }
                continue;
            }
            if($itemdatakeyvalue["type"] == "textarea"){
                $itemdata .= '<div class="'.$itemdatakeyvalue["class"].' mb-1"><label class="fs-6 fw-semibold mb-2 text-gray-500">'.$itemdatakeyvalue["name"].'</label><textarea class="form-control" rows="4" name="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']">'.$item[$itemdatakey].'</textarea></div>';
            }
            else{
                $itemdata .= '<div class="'.$itemdatakeyvalue["class"].' mb-1"><label class="fs-6 fw-semibold mb-2 text-gray-500">'.$itemdatakeyvalue["name"].'</label><input type="text" class="form-control" name="'.'itemdata['.$lid.']'.'['.$position.']['.$itemkey.']'.$mask.'['.$itemdatakey.']" value="'.$item[$itemdatakey].'"></div>';
            }
        }
        return $itemdata;
    }
    public function edit_post(){
        beLanguage::beReadLang("page");
        $pid = (int)$_POST["pid"];
        $page = PageModel::beWhere("pid",$pid)->beGet();
        if(!$page){
            return beAjaxError(["message" => beGetLang("page_not_found")]);
        }
        $languages = LanguageModel::beSelect("lid,lname")->beWhere("lstatus",1)->beGetAll();
        if($page["pcid"]){
            $category = ProductCategoriesModel::beWhere("pcid",$page["pcid"])->beGet();
            $themepage = ThemePageModel::beSelect("tppagedata")->beWhere("tpid",$category["pcpagetype"])->beGet();
            $tppagedata = json_decode($themepage["tppagedata"],true);
            $queque = $_POST["queque"];
            $maked = false;
            foreach($languages as $language){
                if($_POST["advancemode"][$language["lid"]] == 0){
                    $pagetranslation = PageTranslationsModel::beSelect("ptid")->beWhere("pid",$page["pid"])->beWhere("lid",$language["lid"])->beGet();
                    $ptcode = $_POST["ptcode"][(int)$language["lid"]];
                    $slug = $_POST["ptslug"][(int)$language["lid"]] ? $_POST["ptslug"][(int)$language["lid"]]:beSelfLink($_POST["pttitle"][(int)$language["lid"]]);
                    if($slug[0] != "/"){
                        $slug = "/".$slug;
                    }
                    beRouter::$beRouteNames[$ptcode] = $slug;
                    if($pagetranslation){
                        PageTranslationsModel::beUpdate([
                            "ptcode" => $ptcode,
                            "ptname" => $_POST["ptname"][(int)$language["lid"]],
                            "pttitle" => $_POST["pttitle"][(int)$language["lid"]],
                            "ptdescription" => $_POST["ptdescription"][(int)$language["lid"]],
                            "ptslug" => $slug,
                            "pteval" => $_POST["pteval"][(int)$language["lid"]],
                            "ptheader" => $_POST["ptheader"][(int)$language["lid"]],
                            "ptcontentup" => $_POST["ptcontentup"][(int)$language["lid"]],
                            "ptjavascript" => htmlspecialchars_decode($_POST["ptjavascript"][(int)$language["lid"]])
                        ])->beWhere("ptid",$pagetranslation["ptid"])->beExecute();
                    }
                    else{
                        PageTranslationsModel::beInsert([
                            "lid" => $language["lid"],
                            "pid" => $page["pid"],
                            "ptcode" => $ptcode,
                            "ptname" => $_POST["ptname"][(int)$language["lid"]],
                            "pttitle" => $_POST["pttitle"][(int)$language["lid"]],
                            "ptdescription" => $_POST["ptdescription"][(int)$language["lid"]],
                            "ptslug" => $slug,
                            "pteval" => $_POST["pteval"][(int)$language["lid"]],
                            "ptheader" => $_POST["ptheader"][(int)$language["lid"]],
                            "ptcontentup" => $_POST["ptcontentup"][(int)$language["lid"]],
                            "ptjavascript" => htmlspecialchars_decode($_POST["ptjavascript"][(int)$language["lid"]]),
                            "ptdateline" => BE_TIME
                        ]);
                    }
                    $quequelang = $queque[$language["lid"]];
                    $pagedatalang = [];
                    foreach($quequelang as $position => $itemname){
                        $itemname = explode("-",$itemname);
                        foreach($tppagedata["pageitems"] as $key => $ptitemvalue){
                            if($itemname[2] != $key){
                                continue;
                            }
                            $pagedatalang[$position] = $_POST["itemdata"][$language["lid"]][$itemname[1]][$key];
                            $pagedatalang[$position]["mainkey"] = $key;
                        }
                    }
                    PageTranslationsModel::beUpdate(["ptdata" => json_encode($pagedatalang,JSON_UNESCAPED_UNICODE)])->beWhere("pid",$page["pid"])->beWhere("lid",$language["lid"])->beExecute();
                    $category = new CategoryController();
                    $category->beRender($language["lid"],$page["pcid"]);
                    $maked = true;
                }
                else{
                    $ptcode = $_POST["ptcode"][(int)$language["lid"]];
                    if($ptcode){
                        $pagetranslation = PageTranslationsModel::beSelect("ptid")->beWhere("lid",$language["lid"])->beWhere("pid",$page["pid"])->beGet();
                        $slug = $_POST["ptslug"][(int)$language["lid"]] ? $_POST["ptslug"][(int)$language["lid"]]:beSelfLink($_POST["pttitle"][(int)$language["lid"]]);
                        if($slug[0] != "/"){
                            $slug = "/".$slug;
                        }
                        beRouter::$beRouteNames[$ptcode] = $slug;
                        if($pagetranslation){
                            PageTranslationsModel::beUpdate([
                                "ptcode" => $ptcode,
                                "ptname" => $_POST["ptname"][(int)$language["lid"]],
                                "pttitle" => $_POST["pttitle"][(int)$language["lid"]],
                                "ptdescription" => $_POST["ptdescription"][(int)$language["lid"]],
                                "ptslug" => $slug,
                                "pteval" => $_POST["pteval"][(int)$language["lid"]],
                                "ptheader" => $_POST["ptheader"][(int)$language["lid"]],
                                "ptcontentup" => $_POST["ptcontentup"][(int)$language["lid"]],
                                "ptcontent" => $_POST["ptcontent"][(int)$language["lid"]],
                                "ptjavascript" => htmlspecialchars_decode($_POST["ptjavascript"][(int)$language["lid"]])
                            ])->beWhere("ptid",$pagetranslation["ptid"])->beExecute();
                        }
                        else{
                            PageTranslationsModel::beInsert([
                                "lid" => $language["lid"],
                                "pid" => $page["pid"],
                                "ptcode" => $ptcode,
                                "ptname" => $_POST["ptname"][(int)$language["lid"]],
                                "pttitle" => $_POST["pttitle"][(int)$language["lid"]],
                                "ptdescription" => $_POST["ptdescription"][(int)$language["lid"]],
                                "ptslug" => $slug,
                                "pteval" => $_POST["pteval"][(int)$language["lid"]],
                                "ptheader" => $_POST["ptheader"][(int)$language["lid"]],
                                "ptcontentup" => $_POST["ptcontentup"][(int)$language["lid"]],
                                "ptcontent" => $_POST["ptcontent"][(int)$language["lid"]],
                                "ptjavascript" => htmlspecialchars_decode($_POST["ptjavascript"][(int)$language["lid"]]),
                                "ptdateline" => BE_TIME
                            ]);
                        }
                    }
                }
            }
            $menu = new MenuController;
            $menu->beRenderMenus();
            if($maked){
                return beAjaxSuccess(["message" => beGetLang("page_updated_with_cache")]);
            }
        }
        else{
            foreach($languages as $language){
                $ptcode = $_POST["ptcode"][(int)$language["lid"]];
                if($ptcode){
                    $pagetranslation = PageTranslationsModel::beSelect("ptid")->beWhere("lid",$language["lid"])->beWhere("pid",$page["pid"])->beGet();
                    $slug = $_POST["ptslug"][(int)$language["lid"]] ? $_POST["ptslug"][(int)$language["lid"]]:beSelfLink($_POST["pttitle"][(int)$language["lid"]]);
                    if($slug[0] != "/"){
                        $slug = "/".$slug;
                    }
                    beRouter::$beRouteNames[$ptcode] = $slug;
                    if($pagetranslation){
                        PageTranslationsModel::beUpdate([
                            "ptcode" => $ptcode,
                            "ptname" => $_POST["ptname"][(int)$language["lid"]],
                            "pttitle" => $_POST["pttitle"][(int)$language["lid"]],
                            "ptdescription" => $_POST["ptdescription"][(int)$language["lid"]],
                            "ptslug" => $slug,
                            "pteval" => $_POST["pteval"][(int)$language["lid"]],
                            "ptheader" => $_POST["ptheader"][(int)$language["lid"]],
                            "ptcontentup" => $_POST["ptcontentup"][(int)$language["lid"]],
                            "ptcontent" => $_POST["ptcontent"][(int)$language["lid"]],
                            "ptjavascript" => htmlspecialchars_decode($_POST["ptjavascript"][(int)$language["lid"]])
                        ])->beWhere("ptid",$pagetranslation["ptid"])->beExecute();
                    }
                    else{
                        PageTranslationsModel::beInsert([
                            "lid" => $language["lid"],
                            "pid" => $page["pid"],
                            "ptcode" => $ptcode,
                            "ptname" => $_POST["ptname"][(int)$language["lid"]],
                            "pttitle" => $_POST["pttitle"][(int)$language["lid"]],
                            "ptdescription" => $_POST["ptdescription"][(int)$language["lid"]],
                            "ptslug" => $slug,
                            "pteval" => $_POST["pteval"][(int)$language["lid"]],
                            "ptheader" => $_POST["ptheader"][(int)$language["lid"]],
                            "ptcontentup" => $_POST["ptcontentup"][(int)$language["lid"]],
                            "ptcontent" => $_POST["ptcontent"][(int)$language["lid"]],
                            "ptjavascript" => htmlspecialchars_decode($_POST["ptjavascript"][(int)$language["lid"]]),
                            "ptdateline" => BE_TIME
                        ]);
                    }
                }
                beCache::beDeleteCache([$ptcode.$language["lid"]."_info",$ptcode.$language["lid"]."_content"]);
            }
            $menu = new MenuController;
            $menu->beRenderMenus();
        }
        return beAjaxSuccess(["message" => beGetLang("page_updated")]);
    }
    public function newarea_post(){
        $tpid = (int)$_POST["tpid"];
        $lid = (int)$_POST["lid"];
        $itemname = $_POST["itemname"];
        $position = $_POST["lastblock"];
        $themepage = ThemePageModel::beSelect("tppagedata")->beWhere("tpid",$tpid)->beGet();
        $tppagedata = json_decode($themepage["tppagedata"],true);
        $itemdata = $tppagedata["pageitems"][$itemname];
        $itemtext = $this->beRenderOption($lid,$itemname,$position,0,$itemdata["keys"],$itemdata["keys"],"",true);
        $itemhtml = beGetView("admin.page.themepagearea",["lid" => $lid,"position" => $position,"itemkey" => $itemname,"itemdatatext" => $itemtext,"baseitem" => $itemdata]);
        $itemhtml = preg_replace_callback('/value="(.*?)"/',function($data){
            return 'value=""';
        },$itemhtml);
        $itemhtml = preg_replace_callback('/<textarea (.*?)>(.*?)<\/textarea>/',function($data){
            return '<textarea '.$data[1].'></textarea>';
        },$itemhtml);
        return beAjaxSuccess(["html" => $itemhtml]);
    }
    public function deletealt_post(){
        beLanguage::beReadLang("page");
        $ptid = (int)$_POST["ptid"];
        $pagetranslation = PageTranslationsModel::beSelect("ptid")->beWhere("ptid",$ptid)->beGet();
        if(!$pagetranslation){
            return beAjaxError(["message" => beGetLang("page_language_not_found")]);
        }
        PageTranslationsModel::beDelete()->beWhere("ptid",$pagetranslation["ptid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("page_language_deleted")]);
    }
    public function search_post(){
        $sort = (int)$_POST["sort"];
        if(!$sort){
            $sort = 1;
        }
        $page = (int)$_POST["page"];
        if(!$page){
            $page = 1;
        }
        $type = $_POST["type"];
        $lid = (int)$_POST["language"];
        if(!$lid){
            $user = Auth::beGetUser();
            $lid = $user["lid"];
        }
        $itemsearch = beModel::beTable("be_pages as p")->beSelect("COUNT(ptid) as total");
        if($type != "0"){
            $itemsearch = $itemsearch->beWhere("p.ptype",$type);
        }
        if($lid){
            $itemsearch = $itemsearch->beWhere("pt.lid",$lid);
        }
        $itemcount = (int)$itemsearch->beJoin("INNER JOIN be_pages_translations as pt ON p.pid = pt.pid")->beGet()["total"];
        $paganation = bePaganation($page,$itemcount,"");
        $items = beModel::beTable("be_pages as p")->beSelect("p.pid,p.ptype,p.pdefault,pt.ptid,pt.lid,pt.ptname,pt.ptviewuser,pt.ptviewvisitor,pt.ptdateline");
        if($type != "0"){
            $items = $items->beWhere("p.ptype",$type);
        }
        if($lid){
            $items = $items->beWhere("pt.lid",$lid);
        }
        if($paganation["itemstart"] == 0){
            $items = $items->beLimit($paganation["itemlimit"]);
        }
        else{
            $items = $items->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
        }
        $orderkey = "ptid";
        switch($sort){
            case 1 :
                $items = $items->beOrder($orderkey,"DESC");
                break;
            case 2 :
                $items = $items->beOrder($orderkey,"ASC");
                break;
        }
        $items = $items->beJoin("INNER JOIN be_pages_translations as pt ON p.pid = pt.pid")->beGetAll();
        $pagetypes = PageModel::beGetPageTypes();
        $languages = LanguageModel::beGetLanguages("lid,lname");
        $itemhtml = beGetView("admin.page.listrows",["items" => $items,"pagetypes" => $pagetypes,"languages" => $languages]);
        return beAjaxSuccess(["html" => $itemhtml,"paganation" => $paganation["paganation"],"itemcount" => $itemcount]);
    }
    public function page(){
        $user = Auth::beGetUser();
        $slug = beRouter::$beActiveName;
        $url = beGetConfig("siteurl").beRouter::beGetUrl();
        $cachename = $slug.$user["lid"];
        if($_GET["ref"]){
            $uid = (int)$_GET["uid"];
            if($uid){
                beCookie::beCreateCookie("be_refcode",$_GET["ref"]."_".$_GET["uid"],true,true,BE_TIME+86400);
            }
        }
        if(!beCache::beCacheExist($cachename."_info")){
            $page = PageModel::beSelect("be_pages.pid,ptype,pgroups,ptname,pttitle,ptdescription,pteval,ptheader,ptcontentup,ptcontent,ptjavascript,predirect,ptcachetime")->beWhere("lid",$user["lid"])->beWhere("ptcode",$slug)->beJoin("INNER JOIN be_pages_translations as pt ON pt.pid = be_pages.pid")->beGet();
            if($page["predirect"]){
                beRouter::beRedirect($page["predirect"],301);
            }
            $page["cachetime"] = $page["ptcachetime"];
            beCache::beSetCache($cachename."_info",json_encode([
                "pid" => $page["pid"],
                "ptname" => $page["ptname"],
                "pttitle" => $page["pttitle"],
                "ptdescription" => $page["ptdescription"],
                "pteval" => $page["pteval"],
                "ptheader" => $page["ptheader"],
                "ptcontentup" => $page["ptcontentup"],
                "ptjavascript" => $page["ptjavascript"],
                "cachetime" => $page["cachetime"] ? (BE_TIME+$page["cachetime"]):0
            ],JSON_UNESCAPED_UNICODE));
            beCache::beSetCache($cachename."_content",$page["ptcontent"]);
        }
        else{
            $page = json_decode(beCache::beGetCache($cachename."_info"),JSON_UNESCAPED_UNICODE);
            $page["ptcontent"] = beCache::beGetCache($cachename."_content");
            if($page["cachetime"] && BE_TIME > $page["cachetime"]){
                beCache::beDeleteCache([$cachename."_info",$cachename."_content"]);
            }
        }
        if($page["pteval"]){
            eval($page["pteval"]);
        }
        $page["plugindata"] = bePlugin::beRunHook("page_show_pre",["user" => $user,"slug" => $slug,"page" => $page])["plugindata"];
        $page["ptheader"] = beViewer::beGetViewRaw($page["ptheader"],$page);
        $page["ptdescription"] = beViewer::beGetViewRaw($page["ptdescription"],$page);
        $page["ptjavascript"] = beViewer::beGetViewRaw($page["ptjavascript"],$page);
        $page["ptcontent"] = beViewer::beGetViewRaw($page["ptcontent"],$page);
        if($page["pttitle"]){
            NavController::beAddBreadcumb($page["pttitle"]);
            $title = $page["pttitle"]." - ".beGetConfig("siteshortname");
        }
        else{
            $title = beGetConfig("sitename");
        }
        beSetHeaderContent($page["ptcontentup"]);
        $page["content"] = beGetView("page",["page" => $page,"url" => $url,"title" => $title]);
        $page = bePlugin::beRunHook("page_show_post",["slug" => $slug,"page" => $page])["page"];
        if(!$page["pid"]){
            $page["pid"] = 0;
        }
        if($user["uid"] > 0){
            beModel::beQuery("UPDATE be_pages_translations SET ptviewuser = ptviewuser+1 WHERE lid = {$user['lid']} && pid = {$page['pid']}")->beExecute();
        }
        else{
            beModel::beQuery("UPDATE be_pages_translations SET ptviewvisitor = ptviewvisitor+1 WHERE lid = {$user['lid']} && pid = {$page['pid']}")->beExecute();
        }
        return $page["content"];
    }
}

?>