<?php

    namespace App\System\Basic;
    use PDO,PDOException;

    class beModel {
        public static $beInstance = null,$beDB = null,$beQuery = "",$beValues = [];
        public static $beOrder = "",$beOrderType = "";
        public static $beLimitStart = 0,$beLimitEnd = 0;
        public static $beWhere = [],$beGrouping = false,$beGroupID = 1,$beGroupGlue = "";
        public static $beJoin = "";
        public static $beVars = [
            "primary_key" => "id",
            "datelines" => true,
            "dateline_method" => "systime"
        ];
        //@ioncube.dk beEncrypt("be_diyocp","beTable") -> "eb6b70f4b14ccf7e66b468bc57863d7a" RANDOM
        public static function beTable($table = ""){
            if(!self::$beInstance){
                self::beLoadInstance(get_called_class());
                self::$beInstance = new self();
            }
            $query = "SELECT * FROM ".$table;
            self::$beQuery = $query;
            self::$beWhere = [];
            return self::$beInstance;
        }
        //@ioncube.dk beEncrypt("be_diyocp","beSelect") -> "4f12393b40b95e4f6bc496728f28986c" RANDOM
        public static function beSelect($select = ""){
            if(!self::$beInstance){
                self::beLoadInstance(get_called_class());
                self::$beInstance = new self();
            }
            if(!self::$beQuery){
                $query = "SELECT ".$select." FROM ".self::$beVars["table"];
                self::$beQuery = $query;
            }
            else{
                self::$beQuery = str_replace("*",$select,self::$beQuery);
            }
            return self::$beInstance;
        }
        //@ioncube.dk beEncrypt("be_diyocp","beInsert") -> "4ff0e0611c84be86f3d3f3ce04de67f5" RANDOM
        public static function beInsert($data = [],$table = ""){
            if(!self::$beInstance){
                self::beLoadInstance(get_called_class());
                self::$beInstance = new self();
            }
            if($table){
                self::$beVars["table"] = $table;
            }
            $query = "INSERT INTO ".self::$beVars["table"]." SET ";
            foreach($data as $key => $value){
                $query .= $key." = ?,";
                self::$beValues[] = $value;
            }
            $query = substr($query,0,-1);
            self::$beQuery = $query;
            self::beGenereteQuery();
            self::$beInstance = null;
            return (int)self::beGetInsertID();
        }
        //@ioncube.dk beEncrypt("be_diyocp","beUpdate") -> "f87212fb20d7983c7e708e780df5681f" RANDOM
        public static function beUpdate($data = [],$table = ""){
            if(!self::$beInstance){
                self::beLoadInstance(get_called_class());
                self::$beInstance = new self();
            }
            if($table){
                self::$beVars["table"] = $table;
            }
            $query = "UPDATE ".self::$beVars["table"]." SET ";
            foreach($data as $key => $value){
                $query .= $key." = ?,";
                self::$beValues[] = $value;
            }
            $query = substr($query,0,-1);
            self::$beQuery = $query;
            self::$beWhere = [];
            return self::$beInstance;
        }
        //@ioncube.dk beEncrypt("be_diyocp","beDelete") -> "853c6891a689a83669eb334762d6c865" RANDOM
        public static function beDelete($table = ""){
            if(!self::$beInstance){
                self::beLoadInstance(get_called_class());
                self::$beInstance = new self();
            }
            if($table){
                self::$beVars["table"] = $table;
            }
            self::$beQuery = "DELETE FROM ".self::$beVars["table"];
            return self::$beInstance;
        }
        //@ioncube.dk beEncrypt("be_diyocp","beOrder") -> "702d5ad68cae1c81ddbe77abc631538d" RANDOM
        public static function beOrder($columns = "",$order = "DESC"){
            self::$beOrder = $columns;
            self::$beOrderType = $order;
            return self::$beInstance;
        }
        //@ioncube.dk beEncrypt("be_diyocp","beLimit") -> "446926df10da1faee594a2613a247d64" RANDOM
        public static function beLimit($start = 0,$end = 0){
            self::$beLimitStart = $start;
            self::$beLimitEnd = $end;
            return self::$beInstance;
        }
        //@ioncube.dk beEncrypt("be_diyocp","beJoin") -> "a81ee4b439670b8f15936a7c4e15b743" RANDOM
        public static function beJoin($query){
            self::$beJoin = $query;
            return self::$beInstance;
        }
        //@ioncube.dk beEncrypt("be_diyocp","beWhere") -> "4227824b1f5018afa4385f8c726b3b94" RANDOM
        public static function beWhere($column,$value,$marker = "=",$glue = "&&"){
            if(!self::$beInstance){
                self::beLoadInstance(get_called_class());
                self::$beQuery = "SELECT * FROM ".self::$beVars["table"];
                self::$beInstance = new self();
            }
            self::$beWhere[] = [
                "column" => $column,
                "value" => $value,
                "marker" => $marker,
                "glue" => $glue,
                "group" => self::$beGrouping ? self::$beGroupID:0,
                "groupglue" => self::$beGrouping ? self::$beGroupGlue:""
            ];
            return self::$beInstance;
        }
        public static function beWhereGroup($closure,$glue = "&&"){
            if(!self::$beInstance){
                self::beLoadInstance(get_called_class());
                self::$beQuery = "SELECT * FROM ".self::$beVars["table"];
                self::$beInstance = new self();
            }
            self::$beGrouping = true;
            self::$beGroupGlue = $glue;
            call_user_func($closure,self::$beInstance);
            self::$beGrouping = false;
            self::$beGroupID += 1;
            return self::$beInstance;
        }
        //@ioncube.dk beEncrypt("be_diyocp","bePrepareQuery") -> "785e88201a51e17a87f0cdc5b2347921" RANDOM
        public static function bePrepareQuery(){
            self::prepareJoin();
            self::prepareWhere();
            self::prepareOrderBy();
            self::prepareLimit();
        }
        //@ioncube.dk beEncrypt("be_diyocp","prepareWhere") -> "46fc42e8b75404f9342f80ea86b16f86" RANDOM
        public static function prepareWhere(){
            $where = self::$beWhere;
            if($where){
                $query = self::$beQuery;
                $query .= " WHERE ";
                $activegroup = 0;
                $activegroupglue = "";
                $isrouping = false;
                foreach($where as $value){
                    if(!$isrouping && $value["group"]){
                        $isrouping = true;
                        $activegroup = $value["group"];
                        $activegroupglue = $value["groupglue"];
                        $query .= "( ";
                    }
                    if($isrouping && $activegroup != $value["group"]){
                        $query = rtrim($query,"||");
                        $query = rtrim($query,"&&");
                        $query .= ") ";
                        $query .= " {$activegroupglue} ";
                        $isrouping = false;
                    }
                    switch($value["marker"]){
                        case "IN":
                            $count = count($value["value"]);
                            $quest = "";
                            for($i = 0; $i < $count; $i++){
                                $quest .= "?,";
                                self::$beValues[] = $value["value"][$i];
                            }
                            $quest = substr($quest,0,-1);
                            $query .= "{$value['column']} IN ({$quest})";
                            break;
                        case "NOT IN":
                            $count = count($value["value"]);
                            $quest = "";
                            for($i = 0; $i < $count; $i++){
                                $quest .= "?,";
                                self::$beValues[] = $value["value"][$i];
                            }
                            $quest = substr($quest,0,-1);
                            $query .= "{$value['column']} NOT IN ({$quest})";
                            break;
                        case "LIKE":
                            $query .= "{$value['column']} LIKE ?";
                            self::$beValues[] = "%".$value["value"]."%";
                            break;
                        case "NOT LIKE":
                            $query .= "{$value['column']} NOT LIKE ?";
                            self::$beValues[] = "%".$value["value"]."%";
                            break;
                        default :
                            $query .= "{$value['column']} {$value['marker']} ?";
                            self::$beValues[] = $value["value"];
                            break;
                    }
                    $query .= " {$value['glue']} ";
                }
                $query = substr($query,0,-1);
                $query = rtrim($query,"||");
                $query = rtrim($query,"&&");
                if($isrouping){
                    $query .= ")";
                }
                $query = preg_replace("/\(\s+(\|\||&&)/","(",$query);
                $query = preg_replace("/(\|\||&&)\s+\)/",")",$query);
                self::$beWhere = [];
                self::$beQuery = $query;
            }
        }
        //@ioncube.dk beEncrypt("be_diyocp","prepareOrderBy") -> "50a9faf981c2c0d28850e4a2d8c4224e" RANDOM
        public static function prepareOrderBy(){
            if(self::$beOrder){
                $query = self::$beQuery;
                $query .= " ORDER BY ".self::$beOrder;
                if(self::$beOrderType){
                    $query .= " ".self::$beOrderType;
                }
                self::$beQuery = $query;
            }
        }
        //@ioncube.dk beEncrypt("be_diyocp","prepareLimit") -> "1225f246e84b1d831e45e8e9dee8678b" RANDOM
        public static function prepareLimit(){
            if(self::$beLimitStart){
                $query = self::$beQuery;
                if(self::$beLimitEnd){
                    $query .= " LIMIT ".self::$beLimitStart.",".self::$beLimitEnd;
                }
                else{
                    $query .= " LIMIT ".self::$beLimitStart;
                }
                self::$beQuery = $query; 
            }
        }
        //@ioncube.dk beEncrypt("be_diyocp","prepareJoin") -> "163155291d71738206f57e570af7b022" RANDOM
        public static function prepareJoin(){
            if(self::$beJoin){
                self::$beQuery .= " ".self::$beJoin;
            }
        }
        //@ioncube.dk beEncrypt("be_diyocp","beExecute") -> "9d0cfddb513751730fd446428e5e6756" RANDOM
        public static function beExecute(){
            self::bePrepareQuery();
            $data = self::beGenereteQuery();
            self::$beInstance = null;
            return $data;
        }
        //@ioncube.dk beEncrypt("be_diyocp","beGet") -> "60def4df95dfcf4f8a40c3086bf97771" RANDOM
        public static function beGet(){
            self::bePrepareQuery();
            $query = self::beGenereteQuery();
            self::$beInstance = null;
            return $query->fetch(PDO::FETCH_ASSOC);
        }
        public static function beDebugSQL(){
            self::bePrepareQuery();
            return self::$beQuery;
        }
        //@ioncube.dk beEncrypt("be_diyocp","beGetAll") -> "d1a68234e65d5c85d7390195e38408a5" RANDOM
        public static function beGetAll(){
            if(!self::$beInstance){
                self::beLoadInstance(get_called_class());
                self::$beQuery = "SELECT * FROM ".self::$beVars["table"];
                self::$beInstance = new self();
            }
            self::bePrepareQuery();
            $query = self::beGenereteQuery();
            self::$beInstance = null;
            return $query->fetchAll(PDO::FETCH_ASSOC);
        }
        //@ioncube.dk beEncrypt("be_diyocp","beQuery") -> "85126a0d57ece3ab95876568d2fe59df" RANDOM
        public static function beQuery($query){
            self::$beQuery = $query;
            self::$beInstance = new self();
            return self::$beInstance;
        }
        //@ioncube.dk beEncrypt("be_diyocp","beGenereteQuery") -> "3b5d97cbb041d8513afb239ac7881331" RANDOM
        public static function beGenereteQuery(){
            try{
                $query = self::$beDB->prepare(self::$beQuery);
                $query->execute(self::$beValues);
            }
            catch(PDOException $e){
                $data = [
                    "message" => $e->getMessage(),
                    "query" => self::$beQuery,
                    "values" => print_r(self::$beValues,true)
                ];
                self::$beValues = [];
                self::$beInstance = new self();
                self::$beInstance->beInsert([
                    "uid" => 0,
                    "sltitle" => "Kritik SQL Hatası",
                    "slcontent" => "SQL sorgusunda bir sorun oluştu ve sistem devam edemiyor",
                    "sldata" => json_encode($data,JSON_UNESCAPED_UNICODE),
                    "sldateline" => BE_TIME
                ],"be_system_logs");
                echo beAjaxError(["message" => "Şuanda işleminize devam edilemiyor lütfen yönetici ile iletişime geçiniz!"]);
                exit;
            }
            self::$beQuery = "";
            self::$beOrder = "";
            self::$beOrderType = "";
            self::$beJoin = "";
            self::$beWhere = [];
            self::$beLimitEnd = self::$beLimitStart = 0;
            self::$beValues = [];
            return $query;
        }
        //@ioncube.dk beEncrypt("be_diyocp","beGetInsertID") -> "dd221b2f95061311e978333474e6add6" RANDOM
        public static function beGetInsertID(){
            return self::$beDB->lastInsertId();
        }
        //@ioncube.dk beEncrypt("be_diyocp","beLoadInstance") -> "4431b4cd72c9f655b86369370211fb5f" RANDOM
        public static function beLoadInstance($class = ""){
            if(self::$beDB == null){
                $database = beGetConfig("database");
                try {
                    self::$beDB = new PDO("mysql:host={$database["host"]};dbname={$database["database"]};charset=utf8",$database["user"],$database["password"]);
                }
                catch(PDOException $exception){
                    echo $exception->getMessage();
                    exit;
                }
                self::$beDB->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
            }
            if($class[11] != "B"){
                $vars = get_class_vars($class);
                self::$beVars["table"] = $vars["table"]; 
                if(isset($vars["primary_key"])){
                    self::$beVars["primary_key"] = $vars["primary_key"];
                }
                if(isset($vars["datelines"])){
                    self::$beVars["datelines"] = $vars["datelines"];
                }
                if(isset($vars["dateline_method"])){
                    self::$beVars["dateline_method"] = $vars["dateline_method"];
                }
            }
        }
    }
?>