<?php

namespace App\System\Controller;

use App\System\Basic\beCache;
use App\System\Basic\beContoller;
use App\System\Basic\beViewer;
use App\System\Model\CurrencyModel;
use App\System\Model\LanguageModel;
use App\System\Model\PageModel;
use App\System\Model\PageTranslationsModel;
use App\System\Model\ProductCategoriesModel;
use App\System\Model\ProductModel;
use App\System\Model\ThemePageModel;
use App\System\Vendor\beLanguage;

class CategoryController extends beContoller {
    public function list(){
        global $be;
        beLanguage::beReadLang("category");
        $tid = $be->settings["system_theme"];
        $categories = ProductCategoriesModel::beGetAll();
        $themepages = [];
        $themepageslist = ThemePageModel::beSelect("tpid,tpname")->beWhere("tid",$tid)->beGetAll();
        foreach($themepageslist as $themepage){
            $themepages[(int)$themepage["tpid"]] = $themepage;
        }
        return beGetView("admin.category.list",["categories" => $categories,"themepages" => $themepages]);
    }
    public function add(){
        global $be;
        beLanguage::beReadLang("category");
        $tid = $be->settings["system_theme"];
        $themepages = [];
        $themepageslist = ThemePageModel::beSelect("tpid,tpname")->beWhere("tid",$tid)->beGetAll();
        foreach($themepageslist as $themepage){
            $themepages[(int)$themepage["tpid"]] = $themepage;
        }
        return beGetView("admin.category.add",["themepages" => $themepages]);
    }
    public function add_post(){
        global $be;
        beLanguage::beReadLang("category");
        beLanguage::beReadLang("form");
        $tid = $be->settings["system_theme"];
        $lid = $be->settings["system_language"];
        $themepages = [];
        $themepageslist = ThemePageModel::beSelect("tpid")->beWhere("tid",$tid)->beGetAll();
        foreach($themepageslist as $themepage){
            $themepages[(int)$themepage["tpid"]] = $themepage;
        }
        $pcname = $_POST["pcname"];
        $pname = $_POST["pname"];
        $pcode = $_POST["pcode"];
        $pcpagetype = (int)$_POST["pcpagetype"];
        $pcpagetabletype = (int)$_POST["pcpagetabletype"];
        $pcpageitemtype = (int)$_POST["pcpageitemtype"];
        if(!$pcname || !$themepages[$pcpagetype] || !$themepages[$pcpagetabletype] || !$themepages[$pcpageitemtype]){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        $pcid = ProductCategoriesModel::beInsert([
            "pcname" => $pcname,
            "pcpagetype" => $pcpagetype,
            "pcpagetabletype" => $pcpagetabletype,
            "pcpageitemtype" => $pcpageitemtype,
            "pcdateline" => BE_TIME
        ]);
        $pid = PageModel::beInsert([
            "tid" => $tid,
            "pcid" => $pcid,
            "ptype" => "category",
            "pgroups" => "",
            "predirect" => "",
            "pdefault" => "0",
            "pdateline" => BE_TIME
        ]);
        $themepagesmain = ThemePageModel::beWhere("tpid",[$pcpagetype,$pcpagetabletype,$pcpageitemtype],"IN")->beGetAll();
        $tpeval = "";
        $tpheader = "";
        $tpcontentup = "";
        $tpjavascript = "";
        foreach($themepagesmain as $themepage){
            $tpeval .= $themepage["tpeval"];
            $tpheader .= $themepage["tpheader"];
            $tpcontentup .= $themepage["tpcontentup"];
            $tpjavascript .= $themepage["tpjavascript"];
        }
        PageTranslationsModel::beInsert([
            "lid" => $lid,
            "pid" => $pid,
            "ptcode" => $pcode,
            "ptname" => $pname,
            "pttitle" => $pname,
            "ptdescription" => "",
            "ptslug" => "/".beSelfLink($pname),
            "pteval" => $tpeval,
            "ptheader" => $tpheader,
            "ptcontentup" => $tpcontentup,
            "ptjavascript" => $tpjavascript,
            "ptdata" => "[]",
            "ptcachetime" => 86400,
            "ptviewuser" => 0,
            "ptviewvisitor" => 0,
            "ptupdatedateline" => BE_TIME,
            "ptdateline" => BE_TIME
        ]);
        $response = $this->beRender($lid,$pcid);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        return beAjaxSuccess(["message" => beGetLang("category_created"),"url" => beGetRoute("admin.category.edit",["pcid" => $pcid])]);
    }
    public function edit($pcid){
        beLanguage::beReadLang("category");
        global $be;
        $tid = $be->settings["system_theme"];
        $category = ProductCategoriesModel::beWhere("pcid",$pcid)->beGet();
        if(!$category){
            beError(beGetLang("category"),beGetLang("category_not_found"));
        }
        $pagetranslations = PageTranslationsModel::beTable("be_pages_translations as pt")->beSelect("p.pid,pt.ptid,pt.lid,pt.ptname,pt.ptdateline")->beWhere("p.pcid",$category["pcid"])->beWhere("tid",$tid)->beJoin("INNER JOIN be_pages as p ON p.pid = pt.pid")->beGetAll();
        $themepages = [];
        $themepageslist = ThemePageModel::beSelect("tpid,tpname")->beWhere("tid",$tid)->beGetAll();
        foreach($themepageslist as $themepage){
            $themepages[(int)$themepage["tpid"]] = $themepage;
        }
        $languages = LanguageModel::beGetLanguages("lid,lname");
        return beGetView("admin.category.edit",["category" => $category,"pagetranslations" => $pagetranslations,"themepages" => $themepages,"languages" => $languages]);
    }
    public function edit_post(){
        beLanguage::beReadLang("category");
        $pcid = (int)$_POST["pcid"];
        $category = ProductCategoriesModel::beSelect("pcid")->beWhere("pcid",$pcid)->beGet();
        if(!$category){
            return beAjaxError(["message" => beGetLang("category_not_found")]);
        }
        ProductCategoriesModel::beUpdate([
            "pcname" => $_POST["pcname"],
            "pcpagetype" => (int)$_POST["pcpagetype"],
            "pcpagetabletype" => (int)$_POST["pcpagetabletype"],
            "pcpageitemtype" => (int)$_POST["pcpageitemtype"]
        ])->beWhere("pcid",$category["pcid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("category_updated")]);
    }
    public function delete_post(){
        beLanguage::beReadLang("category");
        $pcid = (int)$_POST["pcid"];
        $category = ProductCategoriesModel::beSelect("pcid")->beWhere("pcid",$pcid)->beGet();
        if(!$category){
            return beAjaxError(["message" => beGetLang("category_not_found")]);
        }
        $pages = PageModel::beSelect("pid")->beWhere("pcid",$category["pcid"])->beGetAll();
        foreach($pages as $page){
            PageModel::beDelete()->beWhere("pid",$page["pid"])->beExecute();
            PageTranslationsModel::beDelete()->beWhere("pid",$page["pid"])->beExecute();
        }
        ProductCategoriesModel::beDelete()->beWhere("pcid",$category["pcid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("category_deleted")]);
    }
    public function render_post(){
        $lid = (int)$_POST["lid"];
        $pcid = (int)$_POST["pcid"];
        $response = $this->beRender($lid,$pcid);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        return beAjaxSuccess(["message" => $response["message"]]);
    }
    public function beRenderAll(){
        $languages = LanguageModel::beGetLanguages("lid");
        $categories = ProductCategoriesModel::beSelect("pcid")->beGetAll();
        foreach($languages as $language){
            foreach($categories as $category){
                $result = $this->beRenderCategory($language["lid"],$category["pcid"]);
                beCache::beDeleteCache([$result["cachename"]."_info",$result["cachename"]."_content"]);
            }
        }
        return ["status" => true,"message" => "Başarılı bir şekilde tüm kategori ön belleği güncellendi"];
    }
    public function beRender($lid,$pcid){
        beLanguage::beReadLang("category");
        beLanguage::beReadLang("language");
        $category = ProductCategoriesModel::beSelect("pcid")->beWhere("pcid",$pcid)->beGet();
        if(!$category){
            return ["status" => false,"message" => beGetLang("category_not_found")];
        }
        $language = LanguageModel::beGetLanguages("lid",$lid);
        if(!$language){
            return ["status" => false,"message" => beGetLang("language_not_found")];
        }
        $result = $this->beRenderCategory($language["lid"],$category["pcid"]);
        if(!$result["status"]){
            return ["status" => false,"message" => $result["message"]];
        }
        beCache::beDeleteCache([$result["cachename"]."_info",$result["cachename"]."_content"]);
        return ["status" => true,"message" => $result["message"]];
    }
    private function beRenderCategory($lid = 1,$pcid = 1,$first = false){
        beLanguage::beReadLang("category");
        $productcategory = ProductCategoriesModel::beWhere("pcid",$pcid)->beGet();
        $pagetranslation = PageTranslationsModel::beTable("be_pages_translations as pt")->beSelect("p.*,pt.ptid,pt.pttitle,pt.ptdescription,pt.ptcode,pt.ptdata")->beWhere("p.pcid",$productcategory["pcid"])->beWhere("lid",$lid)->beJoin("INNER JOIN be_pages as p ON p.pid = pt.pid")->beGet();
        $ptdata = json_decode($pagetranslation["ptdata"],true);
        $currencies = CurrencyModel::beGetCurrencies("cid,ccode,cicon");
        $products = ProductModel::beTable("be_products as p")->beSelect("p.pid,p.pcids,p.pimage,p.pperiods,p.pstock,pt.pname,pt.pdescription,pt.pfeatures,pt.pslug")->beWhere("p.psecret","0")->beWhere("pt.lid",$lid)->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = p.pid")->beGetAll();
        foreach($products as $key => $product){
            $pcids = json_decode($product["pcids"],true);
            if(!$pcids){
                $pcids = [];
            }
            if(!in_array($productcategory["pcid"],$pcids)){
                unset($products[$key]);
            }
        }
        $themepagecategory = ThemePageModel::beWhere("tpid",$productcategory["pcpagetype"])->beGet();
        $pageitems = "";
        $pageproductrichtextitems = "";
        $themepageitem = ThemePageModel::beWhere("tpid",$productcategory["pcpageitemtype"])->beGet();
        foreach($products as $item){
            $item["pperiods"] = json_decode($item["pperiods"],true);
            if(empty($item["pperiods"][$lid])){
                return ["status" => false,"message" => beGetLang("category_product_times_not_found")." ".$item["pname"]];
            }
            $item["periods"] = $item["pperiods"][$lid][array_key_first($item["pperiods"][$lid])];
            $item["periods"]["operiod"] = ProductModel::beGetPeriods()[$item["periods"]["operiod"]];
            $item["periodsmax"] = end($item["pperiods"][$lid]);
            $item["periodsmax"]["operiod"] = ProductModel::beGetPeriods()[$item["periods"]["operiod"]];
            $item["pfeatures"] = json_decode($item["pfeatures"],true);
            $item["url"] = beGetRoute("product.product",["slug" => $item["pslug"]]);
            $pageproductrichtextitems .= beGetView("pageproductrichtext-item",["item" => $item,"currencies" => $currencies]).",";
            $pageitems .= beViewer::beGetViewRaw($themepageitem["tpcontent"],["item" => $item,"currencies" => $currencies]);
        }
        $pageproductrichtextitems = substr($pageproductrichtextitems,0,-1);
        $pageproductrichtext = '<script type="application/ld+json">';
        $pageproductrichtext .= beGetView("pageproductrichtext",["pagetranslation" => $pagetranslation,"pageproductrichtextitems" => $pageproductrichtextitems]);
        $pageproductrichtext .= '</script>';
        $themepagetable = ThemePageModel::beWhere("tpid",$productcategory["pcpagetabletype"])->beGet();
        $pagetable = beViewer::beGetViewRaw($themepagetable["tpcontent"],["pageitems" => $pageitems]);
        $page = beViewer::beGetViewRaw($themepagecategory["tpcontent"],["pagetable" => $pagetable,"ptdata" => $ptdata,"pageproductrichtext" => $pageproductrichtext]);
        if($first){
            $themepagecategory["tpheader"] .= $themepageitem["tpheader"];
            $themepagecategory["tpcontentup"] .= $themepageitem["tpcontentup"];
            $themepagecategory["tpjavascript"] .= $themepageitem["tpjavascript"];
            $themepagecategory["tpheader"] .= $themepagetable["tpheader"];
            $themepagecategory["tpcontentup"] .= $themepagetable["tpcontentup"];
            $themepagecategory["tpjavascript"] .= $themepagetable["tpjavascript"];
            PageTranslationsModel::beUpdate(["ptheader" => $themepagecategory["tpheader"],"ptcontentup" => $themepagecategory["tpcontentup"],"ptjavascript" => $themepagecategory["tpjavascript"],"ptcontent" => $page])->beWhere("ptid",$pagetranslation["ptid"])->beExecute();
        }
        else{
            PageTranslationsModel::beUpdate(["ptcontent" => $page])->beWhere("ptid",$pagetranslation["ptid"])->beExecute();
        }
        return ["status" => true,"message" => beGetLang("category_updated_with_cache"),"cachename" => $pagetranslation["ptcode"].$lid];
    }
}

?>