<?php

    namespace App\System\Plugin;

    use App\System\Basic\beCache;
    use App\System\Basic\beModel;
    use App\System\Basic\beRouter;
    use App\System\Controller\ConnectionController;
    use App\System\Model\AttachmentModel;
    use App\System\Model\UserInfoModel;
    use App\System\Model\SettingModel;
    use App\System\Model\SettingGroupsModel;
    use App\System\Vendor\Auth;
    use App\System\Vendor\beLanguage;
    use App\System\Vendor\beModule;
    use App\System\Vendor\bePlugin;

    class useridentity {
        public function plugin_info(){
            return [
                "name" => "TC Kullanıcı Verileri",
                "description" => "Kullanıcıların bireysel mi kurumsal mı olduğunu ayıklar ve bilgi verir",
                "version" => "1.0",
                "vercode" => 1,
                "author" => "ITenGriTR"
            ];
        }
        public function plugin_hooks(){
            return [
                "routes_start" => "my_routes_insert",
                "auth_reset_password_pre" => "my_auth_reset_password_pre",
                "router_route_start_post" => "my_router_route_start_post",
                "admin_user_show_tabs" => "my_admin_user_show_tabs",
                "clientarea_userinfo_start" => "my_clientarea_userinfo_start",
                "admin_dashboard_start" => "my_admin_dashboard_start",
                "page_show_pre" => "my_page_show_pre",
            ];
        }
        public function plugin_install(){
            $sgid = bePlugin::beCreateSettingGroup("useridentity","Üyelik Doğrulama","Üyelik doğrulama modülü için gerekli ayarları ekler");
            bePlugin::beCreateSetting($sgid,"useridentity_tcno_status","TC Doğrulama","Türk vatandaşları için TC kimlik onaylama sistemini zorunlu kıl.","select\n0=Kapalı\n1=Açık","1");
            bePlugin::beCreateSetting($sgid,"useridentity_global_status","TC Dışı Doğrulama","Türk vatandaşları harici ülkeler için kimlik bilgisini yüklemeyi zorunlu kıl.","select\n0=Kapalı\n1=Açık","1");
            beModel::beQuery("CREATE TABLE `be_user_identity_other` (`uid` int(11) NOT NULL,`aids` varchar(32) NOT NULL,`uiname` varchar(64) NOT NULL,`uisurname` varchar(64) NOT NULL,`uiaddress` varchar(512) NOT NULL,`uistatus` enum('-1','0','1') NOT NULL,`uidateline` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;ALTER TABLE `be_user_identity_other` ADD PRIMARY KEY (`uid`);ALTER TABLE `be_user_identity_other`MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT;COMMIT;")->beExecute();
            beModel::beQuery("CREATE TABLE be_user_identity (uid int(11) NOT NULL,uitype enum('1','2') NOT NULL,acid int(11) NOT NULL,adid int(11) NOT NULL,apid int(11) NOT NULL,uitcno varchar(11) NOT NULL,uiname varchar(64) NOT NULL,uisurname varchar(64) NOT NULL,uibirthdate varchar(11) NOT NULL,uititle varchar(64) NOT NULL,uitaxno varchar(64) NOT NULL,uitaxadmin varchar(64) NOT NULL,uiaddress int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;ALTER TABLE be_user_identity ADD PRIMARY KEY (uid);ALTER TABLE be_user_identity MODIFY uid int(11) NOT NULL AUTO_INCREMENT; COMMIT;")->beExecute();
            return ["status" => true,"message" => "Başarılı bir şekilde eklenti kuruldu!"];
        }
        public function plugin_remove(){
            $sgid = SettingGroupsModel::beSelect("sgid")->beWhere("sgcode","useridentity")->beGet()["sgid"];
            SettingGroupsModel::beDelete()->beWhere("sgid",$sgid)->beExecute();
            SettingModel::beDelete()->beWhere("sgid",$sgid)->beExecute();
            beModel::beQuery("DROP TABLE be_user_identity,be_user_identity_other")->beExecute();
            return ["status" => true,"message" => "Başarılı bir şekilde eklenti silindi!"];
        }
        public static function my_routes_insert(){
            beRouter::beName("useridentity.")->beGroup(function(){
                beRouter::beRoute("/useridentity-insert","useridentity@insert_post","post")->beName("insert.post")->beSpecial()->beMiddleWare("Auth");
                beRouter::beRoute("/useridentity-insertother","useridentity@insertother_post","post")->beName("insert.other.post")->beSpecial()->beMiddleWare("Auth");
                beRouter::beRoute("/useridentity-set-status","useridentity@setstatus_post","post")->beName("set.status.post")->beSpecial()->beMiddleWare(["Auth","Admin"]);
                beRouter::beRoute("/useridentity-get-district","useridentity@getdistrict_post","post")->beName("get.district.post")->beSpecial()->beMiddleWare("Auth");
                beRouter::beRoute("/useridentity-get-provience","useridentity@getprovience_post","post")->beName("get.province.post")->beSpecial()->beMiddleWare("Auth");
                beRouter::beRoute("/useridentity-reset-user","useridentity@resetuser_post","post")->beName("reset.user.post")->beSpecial()->beMiddleWare(["Auth","Admin"]);
            });
        }
        public static function my_clientarea_userinfo_start($params){
            $params["plugindata"]["useridentity"] = beModel::beTable("be_user_identity")->beWhere("uid",$params["user"]["uid"])->beGet();
            $params["plugindata"]["pluginstemplate"][] = beGetView("plugins.useridentity.clientarea-identity",$params);
            return $params;
        }
        public static function my_admin_dashboard_start($data = []){
            $useridentities = beModel::beTable("be_user_identity_other as uio")->beSelect("uio.uid,u.name,u.surname,u.email")->beWhere("uistatus","0")->beJoin("INNER JOIN be_users as u ON u.uid = uio.uid")->beGetAll();
            if($useridentities){
                $data["pluginstemplate"][] = beGetView("plugins.useridentity.activation",["useridentities" => $useridentities]);
            }
            return $data;
        }
        public static function my_page_show_pre($data){
            if($data["slug"] == "auth.forgetpassword"){
                $data["plugindata"]["pluginstemplate"][] = beGetView("plugins.useridentity.auth-resetpassword",$data);
            }
            return $data;
        }
        public static function my_auth_reset_password_pre($data){
            $uid = $data["user"]["uid"];
            $userinfo = UserInfoModel::beSelect("acid")->beWhere("uid",$uid)->beGet();
            if($userinfo["acid"] == 218){
                $useridentity = beModel::beTable("be_user_identity")->beSelect("uitcno")->beWhere("uid",$uid)->beGet();
                $tcno = $_POST["tcno"];
                if($useridentity && $useridentity["uitype"] != "2" && $useridentity["uitcno"] != $tcno){
                    echo beAjaxError(["message" => "Belirtilen TC kimlik numarası doğru değil!"]);
                    exit;
                }
            }
        }
        public static function my_router_route_start_post($data){
            $user = Auth::beGetUser();
            if(($data["route_name"] == "client.invoice.invoice" && $_GET["action"] == "pay") || $data["route_name"] == "client.userproduct.userproducts"){
                $user = Auth::beGetUser();
                $useridentity = beModel::beTable("be_user_identity")->beWhere("uid",$user["uid"])->beGet();
                if(!$useridentity){
                    beLanguage::beReadLang("form");
                    $settings = SettingModel::beGetSettings("useridentity_tcno_status,useridentity_global_status");
                    $userinfo = UserInfoModel::beSelect("acid")->beWhere("uid",$user["uid"])->beGet();
                    if($settings["useridentity_tcno_status"] == 1 && $userinfo["acid"] == 218){
                        global $be;
                        $defcountry = $be->settings["system_country"];
                        $countries = beModel::beTable("be_address_country")->beGetAll();
                        $districs = beModel::beTable("be_address_district")->beWhere("acid",$defcountry)->beGetAll();
                        return ["view" => beGetView("plugins.useridentity.identity",["countries" => $countries,"defcountry" => $defcountry,"districs" => $districs])];
                    }
                    if($settings["useridentity_global_status"] == 1 && $userinfo["acid"] != 218){
                        $useridentity = beModel::beTable("be_user_identity_other")->beSelect("uid,uistatus")->beWhere("uid",$user["uid"])->beGet();
                        if($useridentity["uistatus"] != 1){
                            return ["view" => beGetView("plugins.useridentity.identityfile",["useridentity" => $useridentity])];
                        }
                    }
                }
            }
            return $data;
        }
        public function getdistrict_post(){
            $acid = (int)$_POST["country"];
            $districs = beModel::beTable("be_address_district")->beSelect("adid,adname")->beWhere("acid",$acid)->beGetAll();
            return beAjaxSuccess(["message" => "Belirtilen ülkeye ait ilçeler","districs" => $districs]);
        }
        public function getprovience_post(){
            $adid = (int)$_POST["district"];
            $provinces = beModel::beTable("be_address_province")->beSelect("apid,apname")->beWhere("adid",$adid)->beGetAll();
            return beAjaxSuccess(["message" => "Belirtilen ile ait ilçeler","provinces" => $provinces]);
        }
        public function insert_post(){
            $user = Auth::beGetUser();
            $type = $_POST["usertype"];
            switch($type){
                case "individual" :
                    $name = htmlspecialchars($_POST["name"]);
                    $surname = htmlspecialchars($_POST["surname"]);
                    $tcno = htmlspecialchars($_POST["tcno"]);
                    $birthdate = explode("-",htmlspecialchars($_POST["birthdate"]));
                    $year = $birthdate[0];
                    $birthdate = $birthdate[2].".".$birthdate[1].".".$birthdate[0];
                    $acid = (int)$_POST["country"];
                    $adid = (int)$_POST["district"];
                    $apid = (int)$_POST["province"];
                    $country = beModel::beTable("be_address_country")->beSelect("acid")->beWhere("acid",$acid)->beGet();
                    if(!$country){
                        return beAjaxError(["message" => "Belirtilen ülke sistem üzerinde bulunamadı!"]);
                    }
                    $distric = beModel::beTable("be_address_district")->beSelect("adid")->beWhere("acid",$acid)->beWhere("adid",$adid)->beGet();
                    if(!$distric){
                        return beAjaxError(["message" => "Belirtilen il sistem üzerinde bulunamadı!"]);
                    }
                    $province = beModel::beTable("be_address_province")->beSelect("apid,adid")->beWhere("apid",$apid)->beGet();
                    if($province["adid"] != $adid){
                        return beAjaxError(["message" => "Belirtilen ilçe sistem üzerinde bulunamadı!"]);
                    }
                    $address = htmlspecialchars($_POST["address"]);
                    if(!$name || !$surname || !$tcno || !$birthdate || !$address){
                        return beAjaxError(["message" => "Lütfen tüm alanları eksiksiz bir şekilde doldurun!"]);
                    }
                    /*switch($acid){
                        case 218 :
                            $response = ConnectionController::beSendRequest([
                                "method" => "tcno",
                                "data" => [
                                    "name" => $name,
                                    "surname" => $surname,
                                    "tcno" => $tcno,
                                    "year" => $year
                                ]
                            ]);
                            if(!$response["status"]){
                                return beAjaxError(["message" => "Belirtilen bilgilere ait bir vatandaş bulunamadı!"]);
                            }
                            break;
                    }*/
                    beModel::beInsert([
                        "uid" => $user["uid"],
                        "uitype" => "1",
                        "acid" => $acid,
                        "adid" => $adid,
                        "apid" => $apid,
                        "uitcno" => $tcno,
                        "uiname" => $name,
                        "uisurname" => $surname,
                        "uibirthdate" => $birthdate,
                        "uiaddress" => $address
                    ],"be_user_identity");
                    break;
                case "institutional" :
                    $name = htmlspecialchars($_POST["name"]);
                    $taxno = $_POST["taxno"];
                    if(strlen($taxno) > 11){
                        return beAjaxError(["message" => "Girdiğiniz vergi numarası çok uzun lütfen eksiksiz biçimde yazın!"]);
                    }
                    $taxadmin = htmlspecialchars($_POST["taxadmin"]);
                    $address = htmlspecialchars($_POST["address"]);
                    $gibplugin = bePlugin::beGetPlugin("gib_helper");
                    if($gibplugin["status"]){
                        $gib = beModule::beLoadModule("invoice.gib");
                        if($gib["status"]){
                            $settings = SettingModel::beGetSettings("gib_username,gib_password");
                            if($settings["gib_username"] && $settings["gib_password"]){
                                $logindata = beModule::beRunModuleFunction("gib","login");
                                if($logindata["status"]){
                                    $response = beModule::beRunModuleFunction("gib","get_company",["token" => $logindata["token"],"taxno" => $taxno]);
                                    if(!$response["status"]){
                                        return beAjaxError(["message" => "Belirtilen Vergi Kimlik numarası sistem üzerinde onaylanamadı!"]);
                                    }
                                }
                            }
                        }
                    }
                    $acid = (int)$_POST["country"];
                    $adid = (int)$_POST["district"];
                    $apid = (int)$_POST["province"];
                    $distric = beModel::beTable("be_address_district")->beSelect("adid")->beWhere("acid",$acid)->beWhere("adid",$adid)->beGet();
                    if(!$distric){
                        return beAjaxError(["message" => "Belirtilen il sistem üzerinde bulunamadı!"]);
                    }
                    $province = beModel::beTable("be_address_province")->beSelect("apid,adid")->beWhere("apid",$apid)->beGet();
                    if($province["adid"] != $adid){
                        return beAjaxError(["message" => "Belirtilen ilçe sistem üzerinde bulunamadı!"]);
                    }
                    if(!$name || !$taxadmin || !$address){
                        return beAjaxError(["message" => "Lütfen tüm alanları eksiksiz bir şekilde doldurun!"]);
                    }
                    beModel::beInsert([
                        "uid" => $user["uid"],
                        "uitype" => "2",
                        "acid" => $acid,
                        "adid" => $adid,
                        "apid" => $apid,
                        "uititle" => $name,
                        "uitaxno" => $taxno,
                        "uitaxadmin" => $taxadmin,
                        "uiaddress" => $address
                    ],"be_user_identity");
                    break;
            }
            return beAjaxSuccess(["message" => "Başarılı bir şekilde üyelik bilgleriniz sisteme kaydedildi!","refresh" => true]);
        }
        public function insertother_post(){
            beLanguage::beReadLang("form");
            $user = Auth::beGetUser();
            $useridentity = beModel::beTable("be_user_identity_other")->beSelect("*")->beWhere("uid",$user["uid"])->beGet();
            if($useridentity){
                return beAjaxError(["message" => "Hali hazırda zaten başvurunuz bulunuyor. Bir daha başvuru yapamazsınız lütfen destek ekibi ile iletişime geçiniz."]);
            }
            $name = htmlspecialchars($_POST["name"]);
            $surname = htmlspecialchars($_POST["surname"]);
            $address = htmlspecialchars($_POST["address"]);
            if(!$name || !$surname || !$address){
                return beAjaxError(["message" => beGetLang("form_not_full")]);
            }
            $aids = explode(",",$_POST["aids"]);
            $aidlist = [];
            foreach($aids as $aid){
                $aid = (int)$aid;
                $attachment = AttachmentModel::beSelect("aid")->beWhere("aid",$aid)->beWhere("uid",$user["uid"])->beGet();
                if(!$attachment){
                    return beAjaxError(["message" => "Belirtilen kimlik dosyası sisteme yüklenmedi."]);
                }
                $aidlist[] = (int)$attachment["aid"];
            }
            beModel::beInsert([
                "uid" => $user["uid"],
                "aids" => json_encode($aidlist),
                "uiname" => $name,
                "uisurname" => $surname,
                "uiaddress" => $address,
                "uistatus" => "0",
                "uidateline" => BE_TIME
            ],"be_user_identity_other");
            $waitinguser = (int)beCache::beGetCache("useridentity_usercount");
            beCache::beSetCache("useridentity_usercount",$waitinguser+1);
            return beAjaxSuccess(["message" => "Başarılı bir şekilde formunuz inceleme için oluşturuldu. Lütfen belirli aralıklarla kontrol sağlayınız.","refresh" => 1]);
        }
        public function setstatus_post(){
            beLanguage::beReadLang("user");
            $uid = (int)$_POST["uid"];
            $user = Auth::beGetUser($uid,"uid");
            if(!$user){
                return beAjaxError(["message" => beGetLang("user_not_found")]);
            }
            $status = (int)$_POST["status"];
            if(!in_array($status,[-1,0,1])){
                return beAjaxError(["message" => "Belirtilen durum sistem içerisinde bulunamadı!"]);
            }
            beModel::beUpdate(["uistatus" => $status],"be_user_identity_other")->beWhere("uid",$user["uid"])->beExecute();
            return beAjaxSuccess(["message" => "Başarılı bir şekilde işlem sağlandı!"]);
        }
        public function resetuser_post(){
            beLanguage::beReadLang("user");
            $uid = (int)$_POST["uid"];
            $user = Auth::beGetUser($uid,"uid");
            if(!$user){
                return beAjaxError(["message" => beGetLang("user_not_found")]);
            }
            beModel::beDelete("be_user_identity")->beWhere("uid",$user["uid"])->beExecute();
            beModel::beDelete("be_user_identity_other")->beWhere("uid",$user["uid"])->beExecute();
            return beAjaxSuccess(["message" => "Başarılı bir şekilde işlem sağlandı!"]);
        }
        public function my_admin_user_show_tabs($params){
            $useridentity = beModel::beTable("be_user_identity")->beWhere("uid",$params["user"]["uid"])->beGet();
            $useridentityother = beModel::beTable("be_user_identity_other")->beSelect("*")->beWhere("uid",$params["user"]["uid"])->beGet();
            if($useridentityother){
                $attachments = AttachmentModel::beSelect("aid,aname,aslug,asize,adateline")->beWhere("aid",json_decode($useridentityother["aids"],true),"IN")->beGetAll();
                $useridentityother["attachments"] = $attachments;
            }
            $params["tabs"]["useridentity"] = [
                "name" => "Fatura Bilgileri",
                "template" => beGetView("plugins.useridentity.show",["user" => $params["user"],"useridentity" => $useridentity,"useridentityother" => $useridentityother])
            ];
            return $params;
        }
    }

?>