<?php

namespace App\System\Controller;
use App\System\Basic\beContoller;
use App\System\Basic\beModel;
use App\System\Model\AuthModel;
use App\System\Model\UserGroupModel;
use App\System\Model\UserGroupPermissionModel;
use App\System\Vendor\Auth;
use App\System\Vendor\beLanguage;
use App\System\Vendor\beModule;

class UserGroupController extends beContoller {
    public function list(){
        $usergroups = UserGroupModel::beGetAll();
        $groupusers = beModel::beQuery("SELECT usergroup,COUNT(uid) as totaluser FROM be_users GROUP BY usergroup")->beGetAll();
        foreach($usergroups as $key => $usergroup){
            $usergroups[$key]["usercount"] = 0;
            foreach($groupusers as $groupuser){
                if($groupuser["usergroup"] == $usergroup["ugid"]){
                    $usergroups[$key]["usercount"] = (int)$groupuser["totaluser"];
                }
            }
        }
        return beGetView("admin.usergroup.list",["usergroups" => $usergroups]);
    }
    public function add(){
        $user = Auth::beGetUser();
        beLanguage::beReadLang("usergroup");
        $grouppermissions = UserGroupPermissionModel::beWhere("ugpstatus","useable")->beGetAll();
        $usergroupcategories = UserGroupPermissionModel::$defaultgrouppermissions;
        $modules = beModule::beLoadModules("product");
        foreach($modules as $name => $module){
            if(beModule::beCheckModuleFunction($name,"permissions")){
                $modulepermissions = beModule::beRunModuleFunction($name,"permissions",["lid" => $user["lid"]]);
                beLanguage::$lang_data["usergroup_category_".$name] = $module["info"]["name"];
                $usergroupcategories[] = $name;
                foreach($modulepermissions as $permission){
                    beLanguage::$lang_data["usergroup_".$permission["ugpcode"]] = $permission["ugpname"];
                }
                $grouppermissions = array_merge($grouppermissions,$modulepermissions);
            }
        }
        return beGetView("admin.usergroup.add",["grouppermissions" => $grouppermissions,"usergroupcategories" => $usergroupcategories]);
    }
    public function add_post(){
        $user = Auth::beGetUser();
        beLanguage::beReadLang("usergroup");
        beLanguage::beReadLang("form");
        $ugname = $_POST["ugname"];
        $ugdescription = $_POST["ugdescription"];
        $ugnamestyle = $_POST["ugnamestyle"];
        if(empty($ugname) || empty($ugnamestyle)){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        $userpermissions = [];
        $grouppermissions = UserGroupPermissionModel::beWhere("ugpstatus","useable")->beGetAll();
        $modules = beModule::beLoadModules("product");
        foreach($modules as $name => $module){
            if(beModule::beCheckModuleFunction($name,"permissions")){
                $modulepermissions = beModule::beRunModuleFunction($name,"permissions",["lid" => $user["lid"]]);
                $grouppermissions = array_merge($grouppermissions,$modulepermissions);
            }
        }
        foreach($grouppermissions as $grouppermission){
            switch($grouppermission["ugptype"]){
                case "bool" :
                    if($_POST[$grouppermission["ugpcode"]] == 1){
                        $userpermissions[$grouppermission["ugpcode"]] = 1;
                    }
                    break;
                case "number" :
                    $userpermissions[$grouppermission["ugpcode"]] = $_POST[$grouppermission["ugpcode"]];
                    break;
            }
        }
        UserGroupModel::beInsert([
            "ugname" => $ugname,
            "ugdescription" => $ugdescription,
            "ugnamestyle" => $ugnamestyle,
            "ugpermissions" => json_encode($userpermissions,JSON_UNESCAPED_UNICODE),
            "ugdateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("usergroup_created"),"url" => beGetRoute("admin.user.group.list")]);
    }
    public function edit($ugid){
        $user = Auth::beGetUser();
        beLanguage::beReadLang("usergroup");
        $usergroup = UserGroupModel::beWhere("ugid",$ugid)->beGet();
        if(!$usergroup){
            beError(beGetLang("usergroup"),beGetLang("usergroup_not_found"));
        }
        $usergroup["ugpermissions"] = json_decode($usergroup["ugpermissions"],true);
        $grouppermissions = UserGroupPermissionModel::beWhere("ugpstatus","useable")->beGetAll();
        $usergroupcategories = UserGroupPermissionModel::$defaultgrouppermissions;
        $modules = beModule::beLoadModules("product");
        foreach($modules as $name => $module){
            if(beModule::beCheckModuleFunction($name,"permissions")){
                $modulepermissions = beModule::beRunModuleFunction($name,"permissions",["lid" => $user["lid"]]);
                beLanguage::$lang_data["usergroup_category_".$name] = $module["info"]["name"];
                $usergroupcategories[] = $name;
                foreach($modulepermissions as $permission){
                    beLanguage::$lang_data["usergroup_".$permission["ugpcode"]] = $permission["ugpname"];
                }
                $grouppermissions = array_merge($grouppermissions,$modulepermissions);
            }
        }
        return beGetView("admin.usergroup.edit",["usergroup" => $usergroup,"grouppermissions" => $grouppermissions,"usergroupcategories" => $usergroupcategories]);
    }
    public function edit_post(){
        $user = Auth::beGetUser();
        beLanguage::beReadLang("usergroup");
        beLanguage::beReadLang("form");
        $ugid = (int)$_POST["ugid"];
        $usergroup = UserGroupModel::beWhere("ugid",$ugid)->beGet();
        if(!$usergroup){
            return beAjaxError(["message" => beGetLang("usergroup_not_found")]);
        }
        $ugname = $_POST["ugname"];
        $ugdescription = $_POST["ugdescription"];
        $ugnamestyle = $_POST["ugnamestyle"];
        if(empty($ugname) || empty($ugnamestyle)){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        $userpermissions = [];
        $grouppermissions = UserGroupPermissionModel::beWhere("ugpstatus","useable")->beGetAll();
        $modules = beModule::beLoadModules("product");
        foreach($modules as $name => $module){
            if(beModule::beCheckModuleFunction($name,"permissions")){
                $modulepermissions = beModule::beRunModuleFunction($name,"permissions",["lid" => $user["lid"]]);
                $grouppermissions = array_merge($grouppermissions,$modulepermissions);
            }
        }
        foreach($grouppermissions as $grouppermission){
            switch($grouppermission["ugptype"]){
                case "bool" :
                    if($_POST[$grouppermission["ugpcode"]] == 1){
                        $userpermissions[$grouppermission["ugpcode"]] = 1;
                    }
                    break;
                case "number" :
                    $userpermissions[$grouppermission["ugpcode"]] = $_POST[$grouppermission["ugpcode"]];
                    break;
            }
        }
        UserGroupModel::beUpdate([
            "ugname" => $ugname,
            "ugdescription" => $ugdescription,
            "ugnamestyle" => $ugnamestyle,
            "ugpermissions" => json_encode($userpermissions,JSON_UNESCAPED_UNICODE),
        ])->beWhere("ugid",$usergroup["ugid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("usergroup_updated")]);
    }
    public function delete_post(){
        beLanguage::beReadLang("usergroup");
        $ugid = (int)$_POST["ugid"];
        $usergroup = UserGroupModel::beWhere("ugid",$ugid)->beGet();
        if(!$usergroup){
            return beAjaxError(["message" => beGetLang("usergroup_not_found")]);
        }
        UserGroupModel::beDelete()->beWhere("ugid",$usergroup["ugid"])->beExecute();
        AuthModel::beUpdate(["usergroup" => 2])->beWhere("usergroup",$usergroup["ugid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("usergroup_deleted")]);
    }
}