<?php

namespace App\System\Controller;
use App\System\Basic\beContoller;
use App\System\Model\CurrencyModel;
use App\System\Model\LanguageModel;
use App\System\Model\ProductAddonGroupModel;
use App\System\Model\ProductAddonModulesModel;
use App\System\Model\ProductAddonsModel;
use App\System\Model\ProductAddonTranslationsModel;
use App\System\Model\ProductModel;
use App\System\Vendor\Auth;
use App\System\Vendor\beLanguage;
use App\System\Vendor\beModule;

class AddonController extends beContoller {
    public function list(){
        $languages = LanguageModel::beGetLanguages("lid,lname");
        return beGetView("admin.addon.list",["languages" => $languages]);
    }
    public function add(){
        global $be;
        beLanguage::beReadLang("addon");
        $productaddongroups = ProductAddonGroupModel::beGetAll();
        $languages = LanguageModel::beGetLanguages("lid,lname");
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        $systemlid = $be->settings["system_language"];
        $systemcid = $be->settings["system_currency"];
        $periods = ProductModel::beGetPeriods();
        return beGetView("admin.addon.add",["productaddongroups" => $productaddongroups,"periods" => $periods,"languages" => $languages,"currencies" => $currencies,"systemlid" => $systemlid,"systemcid" => $systemcid]); 
    }
    public function add_post(){
        beLanguage::beReadLang("addon");
        $data = $_POST;
        unset($_POST);
        $pagid = (int)$data["pagid"];
        if($pagid){
            $productaddongroup = ProductAddonGroupModel::beSelect("pagid")->beWhere("pagid",$pagid)->beGet();
            if(!$productaddongroup){
                return beAjaxError(["message" => beGetLang("addon_not_found")]);
            }
        }
        else{
            $productaddongroup = [
                "pagid" => 0
            ];
        }
        $paid = ProductAddonsModel::beInsert([
            "pagid" => $productaddongroup["pagid"],
            "padateline" => BE_TIME
        ]);
        $itemcount = $data["itemCount"];
        foreach($itemcount as $lid => $count){
            if(!$data["paname"][$lid]){
                continue;
            }
            $options = [];
            for($i = 1; $i < $count; $i++){
                if(!$data["rowName"][$lid][$i]){
                    continue;
                }
                $options[$data["rowId"][$lid][$i]] = [
                    "oname" => $data["rowName"][$lid][$i],
                    "operiodtime" => (int)$data["rowTime"][$lid][$i],
                    "operiod" => $data["rowTimeType"][$lid][$i],
                    "oprice" => $data["rowPrice"][$lid][$i],
                    "ocid" => (int)$data["rowCurrency"][$lid][$i],
                ];
            }
            if(!in_array($data["patype"][$lid],["select","radio","range"])){
                return beAjaxError(["message" => beGetLang("addon_type_not_found")]);
            }
            ProductAddonTranslationsModel::beInsert([
                "lid" => $lid,
                "paid" => $paid,
                "paname" => $data["paname"][$lid],
                "pacode" => $data["pacode"][$lid],
                "padescription" => $data["padescription"][$lid],
                "patype" => $data["patype"][$lid],
                "paoptions" => json_encode($options,JSON_UNESCAPED_UNICODE),
                "pastatus" => $data["pastatus"][$lid],
                "paposition" => $data["paposition"][$lid],
                "pacompulsory" => $data["pacompulsory"][$lid],
                "paovveridecurrency" => $data["paovveridecurrency"][$lid],
                "pamatchperiod" => $data["pamatchperiod"][$lid]
            ]);
        }
        return beAjaxSuccess(["message" => beGetLang("addon_created"),"url" => beGetRoute("admin.addon.list",["paid" => $paid])]);
    }
    public function show($paid){
        global $be;
        beLanguage::beReadLang("addon");
        $productaddongroups = ProductAddonGroupModel::beGetAll();
        $productaddon = ProductAddonsModel::beSelect("paid,pagid")->beWhere("paid",$paid)->beGet();
        if(!$productaddon){
            beError(beGetLang("addon"),beGetLang("addon_not_found"));
        }
        $productaddontranslations = ProductAddonTranslationsModel::beWhere("paid",$paid)->beGetAll();
        $languages = LanguageModel::beGetLanguages("lid,lname");
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        $systemlid = $be->settings["system_language"];
        $systemcid = $be->settings["system_currency"];
        $periods = ProductModel::beGetPeriods();
        $modules = beModule::beLoadModules("product");
        $moduleaddons = [];
        foreach($modules as $key => $module){
            $moduleaddons[$key] = [
                "info" => $module["info"],
                "addonconfigs" => beModule::beModuleAddonConfig($key)
            ];
        }
        $productaddonmodules = ProductAddonModulesModel::beWhere("paid",$productaddon["paid"])->beGetAll();
        return beGetView("admin.addon.show",["productaddongroups" => $productaddongroups,"productaddon" => $productaddon,"productaddontranslations" => $productaddontranslations,"productaddonmodules" => $productaddonmodules,"periods" => $periods,"languages" => $languages,"currencies" => $currencies,"moduleaddons" => $moduleaddons,"systemlid" => $systemlid,"systemcid" => $systemcid]); 
    }
    public function edit_post(){
        beLanguage::beReadLang("addon");
        $data = $_POST;
        unset($_POST);
        $paid = (int)$data["paid"];
        $productaddon = ProductAddonsModel::beSelect("paid")->beWhere("paid",$paid)->beGet();
        if(!$productaddon){
            return beAjaxError(["message" => beGetLang("addon_not_found")]);
        }
        $pagid = (int)$data["pagid"];
        if($pagid){
            $productaddongroup = ProductAddonGroupModel::beSelect("pagid")->beWhere("pagid",$pagid)->beGet();
            if(!$productaddongroup){
                return beAjaxError(["message" => beGetLang("addon_not_found")]);
            }
        }
        else{
            $productaddongroup = [
                "pagid" => 0
            ];
        }
        $itemcount = $data["itemCount"];
        ProductAddonsModel::beUpdate((["pagid" => $productaddongroup["pagid"]]))->beWhere("paid",$productaddon["paid"])->beExecute();
        foreach($itemcount as $lid => $count){
            if(!$data["paname"][$lid]){
                continue;
            }
            $options = [];
            for($i = 1; $i < $count; $i++){
                if(!$data["rowName"][$lid][$i]){
                    continue;
                }
                $options[$data["rowId"][$lid][$i]] = [
                    "oname" => $data["rowName"][$lid][$i],
                    "operiodtime" => (int)$data["rowTime"][$lid][$i],
                    "operiod" => $data["rowTimeType"][$lid][$i],
                    "oprice" => $data["rowPrice"][$lid][$i],
                    "ocid" => (int)$data["rowCurrency"][$lid][$i],
                ];
            }
            if(!in_array($data["patype"][$lid],["select","radio","range"])){
                return beAjaxError(["message" => beGetLang("addon_type_not_found")]);
            }
            $productaddontranslation = ProductAddonTranslationsModel::beSelect("patid")->beWhere("lid",$lid)->beWhere("paid",$productaddon["paid"])->beGet();
            if($productaddontranslation){
                ProductAddonTranslationsModel::beUpdate([
                    "paname" => $data["paname"][$lid],
                    "pacode" => $data["pacode"][$lid],
                    "padescription" => $data["padescription"][$lid],
                    "patype" => $data["patype"][$lid],
                    "paoptions" => json_encode($options,JSON_UNESCAPED_UNICODE),
                    "pastatus" => $data["pastatus"][$lid],
                    "paposition" => $data["paposition"][$lid],
                    "pacompulsory" => $data["pacompulsory"][$lid],
                    "paovveridecurrency" => $data["paovveridecurrency"][$lid],
                    "pamatchperiod" => $data["pamatchperiod"][$lid]
                ])->beWhere("patid",$productaddontranslation["patid"])->beExecute();
            }
            else{
                ProductAddonTranslationsModel::beInsert([
                    "lid" => $lid,
                    "paid" => $productaddon["paid"],
                    "paname" => $data["paname"][$lid],
                    "pacode" => $data["pacode"][$lid],
                    "padescription" => $data["padescription"][$lid],
                    "patype" => $data["patype"][$lid],
                    "paoptions" => json_encode($options,JSON_UNESCAPED_UNICODE),
                    "pastatus" => $data["pastatus"][$lid],
                    "paposition" => $data["paposition"][$lid],
                    "pacompulsory" => $data["pacompulsory"][$lid],
                    "paovveridecurrency" => $data["paovveridecurrency"][$lid],
                    "pamatchperiod" => $data["pamatchperiod"][$lid]
                ]);
            }
        }
        return beAjaxSuccess(["message" => beGetLang("addon_updated")]);
    }
    public function addonmoduleedit_post(){
        beLanguage::beReadLang("addon");
        $item = explode("-",$_POST["item"]);
        $patid = (int)$item[0];
        $itemkey = (int)$item[1];
        $productaddontranslation = ProductAddonTranslationsModel::beWhere("patid",$patid)->beGet();
        if(!$productaddontranslation){
            return beAjaxError(["message" => beGetLang("addon_option_not_found")]);
        }
        $paoptions = json_decode($productaddontranslation["paoptions"],true); 
        if(!array_key_exists($itemkey,$paoptions)){
            return beAjaxError(["message" => beGetLang("addon_option_key_not_found")]);
        }
        $moduledata = $_POST["moduledata"];
        foreach($moduledata as $name => $data){
            foreach($data as $key => $value){
                $productaddonmodule = ProductAddonModulesModel::beSelect("pamid")->beWhere("patid",$productaddontranslation["patid"])->beWhere("pamodule",$name)->beWhere("pamodulekey",$key)->beWhere("pakey",$itemkey)->beGet();
                if($productaddonmodule){
                    ProductAddonModulesModel::beUpdate(["pavalue" => $value,"padateline" => BE_TIME])->beWhere("pamid",$productaddonmodule["pamid"])->beExecute();
                }
                else{
                    if(empty($value)){
                        continue;
                    }
                    ProductAddonModulesModel::beInsert([
                        "paid" => $productaddontranslation["paid"],
                        "patid" => $productaddontranslation["patid"],
                        "pamodule" => $name,
                        "pamodulekey" => $key,
                        "pakey" => $itemkey,
                        "pavalue" => $value,
                        "padateline" => BE_TIME
                    ]);
                }
            }
        }
        return beAjaxSuccess(["message" => beGetLang("addon_updated")]);
    }
    public function delete_post(){
        $paid = (int)$_POST["paid"];
        $productaddon = ProductAddonsModel::beSelect("paid")->beWhere("paid",$paid)->beGet();
        if(!$productaddon){
            return beAjaxError(["message" => beGetLang("addon_not_found")]);
        }
        ProductAddonsModel::beDelete()->beWhere("paid",$productaddon["paid"])->beExecute();
        ProductAddonTranslationsModel::beDelete()->beWhere("paid",$productaddon["paid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("addon_deleted")]);
    }
    public function search_post(){
        $sort = (int)$_POST["sort"];
        if(!$sort){
            $sort = 1;
        }
        $page = (int)$_POST["page"];
        if(!$page){
            $page = 1;
        }
        $name = $_POST["name"];
        $lid = (int)$_POST["language"];
        if(!$lid){
            $user = Auth::beGetUser();
            $lid = $user["lid"];
        }
        $itemsearch = ProductAddonTranslationsModel::beSelect("COUNT(patid) as total");
        if($name){
            $itemsearch = $itemsearch->beWhere("paname",$name);
        }
        if($lid){
            $itemsearch = $itemsearch->beWhere("lid",$lid);
        }
        $itemcount = (int)$itemsearch->beGet()["total"];
        $paganation = bePaganation($page,$itemcount,"");
        $items = ProductAddonTranslationsModel::beSelect("*");
        if($name){
            $items = $items->beWhere("paname",$name);
        }
        if($lid){
            $items = $items->beWhere("lid",$lid);
        }
        if($paganation["itemstart"] == 0){
            $items = $items->beLimit($paganation["itemlimit"]);
        }
        else{
            $items = $items->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
        }
        $orderkey = "paid";
        switch($sort){
            case 1 :
                $items = $items->beOrder($orderkey,"DESC");
                break;
            case 2 :
                $items = $items->beOrder($orderkey,"ASC");
                break;
        }
        $items = $items->beGetAll();
        $languages = LanguageModel::beGetLanguages("lid,lname");
        $addonstatus = ProductAddonsModel::beGetAddonStatus();
        $itemhtml = beGetView("admin.addon.listrows",["items" => $items,"addonstatus" => $addonstatus,"languages" => $languages]);
        return beAjaxSuccess(["html" => $itemhtml,"paganation" => $paganation["paganation"],"itemcount" => $itemcount]);
    }
}

?>