<?php

namespace App\System\Controller;
use App\System\Basic\beContoller;
use App\System\Basic\beModel;
use App\System\Basic\beRouter;
use App\System\Model\AuthModel;
use App\System\Model\CurrencyModel;
use App\System\Model\LanguageModel;
use App\System\Model\TicketAdminSignatureModel;
use App\System\Model\UserGroupModel;
use App\System\Model\UserInfoModel;
use App\System\Model\UserLogModel;
use App\System\Model\UserProductLogsModel;
use App\System\Model\UserProductModel;
use App\System\Vendor\Auth;
use App\System\Vendor\Basic\beCookie;
use App\System\Vendor\beLanguage;
use App\System\Vendor\bePlugin;

class UserController extends beContoller {
    public function list(){
        return beGetView("admin.user.list");
    }
    public function add(){
        global $be;
        $usergroups = UserGroupModel::beSelect("ugid,ugname")->beGetAll();
        $languages = LanguageModel::beGetLanguages("lid,lname,lcode");
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        $countries = beModel::beTable("be_address_country")->beGetAll();
        $system_country = $be->settings["system_country"];
        return beGetView("admin.user.add",["languages" => $languages,"currencies" => $currencies,"usergroups" => $usergroups,"countries" => $countries,"system_country" => $system_country]);
    }
    public function add_post(){
        beLanguage::beReadLang("auth");
        beLanguage::beReadLang("form");
        $name = htmlspecialchars($_POST["name"]);
        $surname = htmlspecialchars($_POST["surname"]);
        $email = htmlspecialchars($_POST["email"]);
        $district = htmlspecialchars($_POST["district"]);
        $province = htmlspecialchars($_POST["province"]);
        $address = htmlspecialchars($_POST["address"]);
        $password = $_POST["password"];
        $money = floatval($_POST["money"]);
        $ugid = (int)$_POST["usergroup"];
        $lid = (int)$_POST["language"];
        $cid = (int)$_POST["currency"];
        $acid = (int)$_POST["country"];
        $dial = $_POST["dial"];
        $phone = $_POST["phone"];
        if(preg_match("/ /",$surname)){
            return beAjaxError(["message" => beGetLang("surname_space")]);
        }
        if(strlen($address) > 256){
            $address = substr($address,0,256);
        }
        $phone = str_replace([" ","(",")","-"],"",$_POST["phone"]);
        if(!preg_match('/^[0-9]+$/',$phone)){
            return beAjaxError(["message" => beGetLang("only_numbers_in_phone")]);
        }
        $dial = (int)str_replace("+","",$_POST["dial"]);
        if(!preg_match('/^[0-9]+$/',$dial)){
            return beAjaxError(["message" => beGetLang("only_numbers_in_phone")]);
        }
        if(!$address){
            $address = "-";
        }
        $userinfo = UserInfoModel::beSelect("uid")->beWhere("uiphone",$phone)->beGet();
        if($userinfo){
            return beAjaxError(["message" => beGetLang("phone_number_using")]);
        }
        $country = beModel::beTable("be_address_country")->beSelect("acid")->beWhere("acid",$acid)->beGet();
        if(!$country){
            return beAjaxError(["message" => beGetLang("country_not_found")]);
        }
        $settings = [
            "sms_alert" => 1,
            "mail_alert" => 1,
            "notification_alert" => 1,
            "order_auto_pay" => 0,
            "never_suspend" => 0,
            "never_terminate" => 0,
            "invoice_tax_exemption" => 0,
            "invoice_latefee" => 1,
            "ticket_create" => 1,
            "ticket_onlyone" => 0,
            "ticket_files" => 1,
            "invoiceinfo" => 1,
            "productinfo" => 1,
        ];
        if(empty($name) || empty($surname) || empty($email) || empty($password)){
            return beAjaxError(["message" => beGetLang("not_full")]);
        }
        if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
            return beAjaxError(["message" => beGetLang("not_email")]);
        }
        $checkmail = AuthModel::beSelect("uid")->beWhere("email",$email)->beGet();
        if($checkmail){
            return beAjaxError(["message" => beGetLang("email_using")]);
        }
        $user = Auth::beCreateUser(["name" => $name,"surname" => $surname,"email" => $email,"password" => $password,"extradata" => ["lid" => $lid,"cid" => $cid,"money" => $money,"usergroup" => $ugid,"status" => "1"]]);
        if(!$user["status"]){
            return beAjaxError(["message" => $user["message"]]);
        }
        UserInfoModel::beInsert([
            "uid" => $user["uid"],
            "acid" => $acid,
            "uidistrict" => $district,
            "uiprovince" => $province,
            "uidial" => $dial,
            "uiphone" => $phone,
            "uiaddress" => $address,
            "uisettings" => json_encode($settings,JSON_UNESCAPED_UNICODE)
        ]);
        return beAjaxSuccess(["message" => beGetLang("user_created_successfully"),"url" => beGetRoute("admin.user.list")]);
    }
    public function show($uid){
        beLanguage::beReadLang("user");
        $user = AuthModel::beWhere("uid",$uid)->beGet();
        if(!$user){
            beError("Bulunamadı!",beGetLang("user_not_found"));
        }
        $tabs = [];
        $tabs = bePlugin::beRunHook("admin_user_show_tabs",["user" => $user,"tabs" => $tabs])["tabs"];
        $userinfo = UserInfoModel::beWhere("uid",$user["uid"])->beGet();
        $uisettings = json_decode($userinfo["uisettings"],true);
        unset($userinfo["uisettings"]);
        $usergroups = UserGroupModel::beSelect("ugid,ugname,ugnamestyle")->beGetAll();
        foreach($usergroups as $usergroup){
            if($usergroup["ugid"] == $user["usergroup"]){
                $user["group"] = $usergroup;
                break;
            }
        }
        $user["username"] = UserGroupModel::beRenderUserName($user["name"]." ".$user["surname"],$usergroup["ugnamestyle"]);
        $userlogs = UserLogModel::beSelect("lid,ltype,ldata,lipaddress,ldateline")->beWhere("uid",$user["uid"])->beGetAll();
        $this->beSetUserMessages($user["lid"],$userlogs);
        $ticketadminsignatures = [];
        $ticketadminsignaturestypes = TicketAdminSignatureModel::beGetTicketAdminSignatureTimes();
        if(beCheckPermission("admin_ticket_message_add",$user["group"]["ugid"])){
            $ticketadminsignatures = TicketAdminSignatureModel::beSelect("tasid,lid,tastime,tasdateline")->beWhere("uid",$user["uid"])->beGetAll();
        }
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        $usercurrencie = [];
        foreach($currencies as $currencie){
            if($currencie["cid"] == $user["cid"]){
                $usercurrencie = $currencie;
                break;
            }
        }
        $languages = LanguageModel::beGetLanguages("lid,lname,lcode");
        $userlanguage = [];
        foreach($languages as $language){
            if($language["lid"] == $language["lid"]){
                $userlanguage = $language;
                break;
            }
        }
        $countries = beModel::beTable("be_address_country")->beGetAll();
        $userstatus = AuthModel::beGetUserStatus(); 
        return beGetView("admin.user.show",["user" => $user,"usergroups" => $usergroups,"userstatus" => $userstatus,"userinfo" => $userinfo,"uisettings" => $uisettings,"ticketadminsignatures" => $ticketadminsignatures,"ticketadminsignaturestypes" => $ticketadminsignaturestypes,"usergroup" => $usergroup,"currencies" => $currencies,"usercurrencie" => $usercurrencie,"countries" => $countries,"languages" => $languages,"userlanguage" => $userlanguage,"userlogs" => $userlogs,"tabs" => $tabs]);
    }
    public function save_post(){
        beLanguage::beReadLang("auth");
        beLanguage::beReadLang("user");
        beLanguage::beReadLang("usergroup");
        beLanguage::beReadLang("currency");
        beLanguage::beReadLang("language");
        beLanguage::beReadLang("form");
        $admin = Auth::beGetUser();
        $uid = (int)$_POST["uid"];
        $user = Auth::beGetUser($uid,"uid");
        if(!$user){
            return beAjaxError(["message" => beGetLang("user_not_found")]);
        }
        $name = htmlspecialchars($_POST["name"]);
        $surname = htmlspecialchars($_POST["surname"]);
        $email = htmlspecialchars($_POST["email"]);
        $password = htmlspecialchars($_POST["password"]);
        $ugid = (int)$_POST["usergroup"];
        $acid = (int)$_POST["country"];
        $lid = (int)$_POST["language"];
        $cid = (int)$_POST["currencie"];
        $phone_dial = htmlspecialchars($_POST["dial"]);
        $phone = htmlspecialchars($_POST["phone"]);
        $address = htmlspecialchars($_POST["address"]);
        if(empty($name) || empty($surname) || empty($email)){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
            return beAjaxError(["message" => beGetLang("incorrect_email_format")]);
        }
        $checkmail = AuthModel::beSelect("uid")->beWhere("email",$email)->beGet();
        if($checkmail && $checkmail["uid"] != $user["uid"]){
            return beAjaxError(["message" => beGetLang("email_address_using")]);
        }
        $usergroup = UserGroupModel::beSelect("ugid")->beWhere("ugid",$ugid)->beGet();
        if(!$usergroup){
            return beAjaxError(["message" => beGetLang("usergroup_not_found")]);
        }
        $country = beModel::beTable("be_address_country")->beSelect("acid")->beWhere("acid",$acid)->beGet();
        if(!$country){
            return beAjaxError(["message" => beGetLang("country_not_found")]);
        }
        $currencie = CurrencyModel::beGetCurrencies("cid",$cid);
        if(!$currencie){
            return beAjaxError(["message" => beGetLang("currency_not_found")]);
        }
        $language = LanguageModel::beGetLanguages("lid",$lid);
        if(!$language){
            return beAjaxError(["message" => beGetLang("language_not_found")]);
        }
        if(!preg_match('/^[0-9]+$/',$phone_dial)){
            return beAjaxError(["message" => beGetLang("only_numbers_in_phone")]);
        }
        if(!preg_match('/^[0-9]+$/',$phone)){
            return beAjaxError(["message" => beGetLang("only_numbers_in_phone")]);
        }
        if(strlen($address) > 256){
            $address = substr($address,0,256);
        }
        if($password){
            $response = Auth::beUpdatePassword($user["uid"],$password);
            if(!$response){
                return beAjaxError(["message" => beGetLang("password_change_failed_admin")]);
            }
        }
        AuthModel::beUpdate([
            "lid" => $language["lid"],
            "cid" => $currencie["cid"],
            "name" => $name,
            "surname" => $surname,
            "email" => $email,
            "usergroup" => $usergroup["ugid"]
        ])->beWhere("uid",$user["uid"])->beExecute();
        UserInfoModel::beUpdate([
            "acid" => $acid,
            "uidial" => $phone_dial,
            "uiphone" => $phone,
            "uiaddress" => $address
        ])->beWhere("uid",$user["uid"])->beExecute();
        UserLogModel::beInsert([
            "uid" => $user["uid"],
            "ltype" => "user_edit",
            "lipaddress" => beRouter::$beUserIP,
            "ldata" => json_encode(["admin" => (int)$admin["uid"]]),
            "ldateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("user_edit_successfully")]);
    }
    public function notesave_post(){
        beLanguage::beReadLang("user");
        $admin = Auth::beGetUser();
        $uid = (int)$_POST["uid"];
        $user = Auth::beGetUser($uid,"uid");
        if(!$user){
            return beAjaxError(["message" => beGetLang("user_not_found")]);
        }
        $note = htmlspecialchars($_POST["note"]);
        UserInfoModel::beUpdate([
            "uinote" => $note
        ])->beWhere("uid",$user["uid"])->beExecute();
        UserLogModel::beInsert([
            "uid" => $user["uid"],
            "ltype" => "note_edit",
            "lipaddress" => beRouter::$beUserIP,
            "ldata" => json_encode(["admin" => (int)$admin["uid"]]),
            "ldateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("user_edit_successfully")]);
    }
    public function namesave_post(){
        beLanguage::beReadLang("user");
        $admin = Auth::beGetUser();
        $uid = (int)$_POST["uid"];
        $user = Auth::beGetUser($uid,"uid");
        if(!$user){
            return beAjaxError(["message" => beGetLang("user_not_found")]);
        }
        $name = htmlspecialchars($_POST["name"]);
        $surname = htmlspecialchars($_POST["surname"]);
        $email = htmlspecialchars($_POST["email"]);
        $password = htmlspecialchars($_POST["password"]);
        if(empty($name) || empty($surname) || empty($email)){
            return beAjaxError(["message" => "Lütfen zorunlu olan tüm alanları doldurun!"]);
        }
        $update = [
            "name" => $name,
            "surname" => $surname,
            "email" => $email
        ];
        if($password){
            $salt = substr(md5(BE_TIME),0,16);
            $loginkey = md5($salt);
            $response = Auth::beRequestPassword($salt,$password);
            if(!$response["status"]){
                return beAjaxError(["message" => "Sistemde erişim sorunu lütfen sistemi kontrol edin!"]);
            }
            $update["salt"] = $salt;
            $update["loginkey"] = $loginkey;
            $update["password"] = $response["password"];
        }
        AuthModel::beUpdate($update)->beWhere("uid",$user["uid"])->beExecute();
        UserLogModel::beInsert([
            "uid" => $user["uid"],
            "ltype" => "info_edit",
            "lipaddress" => beRouter::$beUserIP,
            "ldata" => json_encode(["admin" => (int)$admin["uid"]]),
            "ldateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("user_edit_successfully")]);
    }
    public function phonesave_post(){
        beLanguage::beReadLang("user");
        $admin = Auth::beGetUser();
        $uid = (int)$_POST["uid"];
        $user = Auth::beGetUser($uid,"uid");
        if(!$user){
            return beAjaxError(["message" => beGetLang("user_not_found")]);
        }
        $phone = str_replace([" ","(",")"],"",$_POST["phone"]);
        if(!preg_match('/^[0-9]+$/',$phone)){
            return beAjaxError(["message" => "Telefon numaraları sadece rakamlardan oluşuyor!"]);
        }
        UserInfoModel::beUpdate([
            "uiphone" => $phone
        ])->beWhere("uid",$user["uid"])->beExecute();
        UserLogModel::beInsert([
            "uid" => $user["uid"],
            "ltype" => "phone_edit",
            "lipaddress" => beRouter::$beUserIP,
            "ldata" => json_encode(["admin" => (int)$admin["uid"]]),
            "ldateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("user_edit_successfully")]);
    }
    public function settingsave_post(){
        beLanguage::beReadLang("user");
        $admin = Auth::beGetUser();
        $uid = (int)$_POST["uid"];
        $user = Auth::beGetUser($uid,"uid");
        if(!$user){
            return beAjaxError(["message" => beGetLang("user_not_found")]);
        }
        $settings = [
            "sms_alert","mail_alert","notification_alert",
            "order_auto_pay",
            "never_suspend","never_terminate",
            "invoice_tax_exemption","invoice_latefee",
            "ticket_create","ticket_onlyone","ticket_files"
        ];
        $datalist = [];
        foreach($settings as $setting){
            if($_POST[$setting] == 1){
                $datalist[$setting] = 1;
                continue;
            }
            $datalist[$setting] = 0;
        }
        UserInfoModel::beUpdate([
            "uisettings" => json_encode($datalist,JSON_UNESCAPED_UNICODE)
        ])->beWhere("uid",$user["uid"])->beExecute();
        UserLogModel::beInsert([
            "uid" => $user["uid"],
            "ltype" => "setting_edit",
            "lipaddress" => beRouter::$beUserIP,
            "ldata" => json_encode(["admin" => (int)$admin["uid"]]),
            "ldateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("user_edit_successfully")]);
    }
    public function moneyupdate_post(){
        beLanguage::beReadLang("user");
        $admin = Auth::beGetUser();
        $uid = (int)$_POST["uid"];
        $user = Auth::beGetUser($uid,"uid,cid,money");
        if(!$user){
            return beAjaxError(["message" => beGetLang("user_not_found")]);
        }
        $amount = (double)$_POST["amount"];
        $giveamount = $amount;
        if(!$amount){
            return beAjaxError(["message" => "Bir tutar belirtmeniz gerekiyor!"]);
        }
        $cid = (int)$_POST["currencie"];
        $type = (int)$_POST["type"];
        if(!in_array($type,[-1,1])){
            return beAjaxError(["message" => "Belirtilen tür bulunamadı!"]);
        }
        $description = $_POST["description"];
        $currencie = CurrencyModel::beGetCurrencies("cid,cname,cicon",$cid);
        if(!$currencie){
            return beAjaxError(["message" => "Belirtilen para birimi bulunamadı!"]);
        }
        if($user["cid"] != $cid){
            $giveamount = CurrencyModel::beConvertCurrencie($giveamount,$currencie["cid"],$user["cid"]);
        }
        $user["money"] += $giveamount*$type;
        AuthModel::beUpdate(["money" => $user["money"]])->beWhere("uid",$user["uid"])->beExecute();
        UserLogModel::beInsert([
            "uid" => $user["uid"],
            "ltype" => "money_change",
            "lipaddress" => beRouter::$beUserIP,
            "ldata" => json_encode([
                "type" => $type,
                "amount" => $amount,
                "currencie" => $currencie,
                "description" => $description,
                "admin" => (int)$admin["uid"]
            ]),
            "ldateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("user_edit_successfully")]);
    }
    public function userfind_post(){
        $username = $_POST["term"];
        if($username){
            $userdata = explode(" ",$username);
            $namecount = count($userdata);
            switch($namecount){
                case 1 :
                    if(strpos($userdata[0],"@") === false){
                        $userlist = AuthModel::beSelect("uid,concat(name,' ',surname,'  #  ',email) as namesurname")->beWhere("name",$userdata[0],"LIKE")->beGetAll();
                        if(!$userlist){
                            $userlist = AuthModel::beSelect("uid,concat(name,' ',surname,'  #  ',email) as namesurname")->beWhere("surname",$userdata[0],"LIKE")->beGetAll();
                        }
                        if(!$userlist){
                            $userlist = AuthModel::beSelect("uid,concat(name,' ',surname,'  #  ',email) as namesurname")->beWhere("email",$userdata[0],"LIKE")->beGetAll();
                        }
                    }
                    else{
                        $userlist = AuthModel::beSelect("uid,concat(name,' ',surname,'  #  ',email) as namesurname")->beWhere("email",$userdata[0],"LIKE")->beGetAll();
                    }
                    break;
                case 2 :
                    $userlist = AuthModel::beSelect("uid,concat(name,' ',surname,'  #  ',email) as namesurname")->beWhere("name",$userdata[0],"LIKE")->beWhere("surname",$userdata[1],"LIKE")->beGetAll();
                    break;
                case 3 :
                    $userlist = AuthModel::beSelect("uid,concat(name,' ',surname,'  #  ',email) as namesurname")->beWhere("name",$userdata[0]." ".$userdata[1],"LIKE")->beWhere("surname",$userdata[2],"LIKE")->beGetAll();
                    break;
            }
            return json_encode($userlist,JSON_UNESCAPED_UNICODE);
        }
    }
    public function searchlogs_post(){
        $sort = (int)$_POST["sort"];
        if(!$sort){
            $sort = 1;
        }
        $page = (int)$_POST["page"];
        if(!$page){
            $page = 1;
        }
        $uid = (int)$_POST["uid"];
        $itemsearch = UserLogModel::beSelect("COUNT(lid) as total");
        if($uid){
            $itemsearch = $itemsearch->beWhere("uid",$uid);
        }
        $itemcount = (int)$itemsearch->beGet()["total"];
        $paganation = bePaganation($page,$itemcount);
        $items = UserLogModel::beSelect("*");
        if($uid){
            $items = $items->beWhere("uid",$uid);
        }
        if($paganation["itemstart"] == 0){
            $items = $items->beLimit($paganation["itemlimit"]);
        }
        else{
            $items = $items->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
        }
        switch($sort){
            case 1 :
                $items = $items->beOrder("lid","DESC");
                break;
            case 2 :
                $items = $items->beOrder("lid","ASC");
                break;
        }
        $items = $items->beGetAll();
        $logtypes = [
            "login" => [
                "message" => "Sisteme giriş yapıldı!"    
            ],
            "invoice_extend" => [
                "message" => "<a href=\"".beGetRoute("client.invoice.invoice")."/{iid}\" target=\"_blank\">#{iid}</a> sayılı fatura kullanıcı tarafından ödendi!",
                "veriables" => ["iid"]
            ]
        ];
        $itemshtml = beGetView("admin.user.logs-listrows",["items" => $items,"logtypes" => $logtypes]);
        return beAjaxSuccess(["html" => $itemshtml,"paganation" => $paganation["paganation"],"itemcount" => $itemcount]);
    }
    public function searchorders_post(){
        $sort = (int)$_POST["sort"];
        if(!$sort){
            $sort = 1;
        }
        $page = (int)$_POST["page"];
        if(!$page){
            $page = 1;
        }
        $pageitems = (int)$_POST["pageitems"];
        if(!$pageitems){
            $pageitems = 15;
        }
        $uid = (int)$_POST["uid"];
        $itemsearch = UserProductModel::beSelect("COUNT(upid) as total")->beWhere("uid",$uid);
        $itemcount = (int)$itemsearch->beGet()["total"];
        $paganation = bePaganation($page,$itemcount,"",$pageitems);
        $items = UserProductModel::beSelect("upid,upname,uptag");
        $items = $items->beWhere("uid",$uid);
        if($paganation["itemstart"] == 0){
            $items = $items->beLimit($paganation["itemlimit"]);
        }
        else{
            $items = $items->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
        }
        switch($sort){
            case 1 :
                $items = $items->beOrder("upid","DESC");
                break;
            case 2 :
                $items = $items->beOrder("upid","ASC");
                break;
        }
        $items = $items->beGetAll();
        return beAjaxSuccess(["message" => "Başarılı bir şekilde kullanıcının hizmetleri listelendi","items" => $items]);
    }
    public function loginfromadmin_post(){
        beLanguage::beReadLang("user");
        $user = Auth::beGetUser();
        $uid = (int)$_POST["uid"];
        $loginuser = Auth::beGetUser($uid,"uid,loginkey,usergroup");
        if(!$loginuser){
            return beAjaxError(["message" => beGetLang("user_not_found")]);
        }
        if(in_array($loginuser["usergroup"],[4]) && $user["uid"] != 1){
            return beAjaxError(["message" => "Girmeye çalıştığınız hesap bir yönetici hesabı bu hesaba giriş yapamazsınız!"]);
        }
        beCookie::beCreateCookie("be_user",$loginuser["uid"]."_".$loginuser["loginkey"],true,true,-1);
        beCookie::beCreateCookie("be_user_admin",$user["uid"]."_".$user["loginkey"],true,true,-1);
        return beAjaxSuccess(["message" => "Başarılı bir şekilde müşteri hesabına giriş yapıldı!","url" => beGetRoute("client.dashboard")]);
    }
    public function returntoadmin(){
        $admincontent = $_COOKIE["be_user_admin"];
        if(!$admincontent){
            beError("Bulunamadı","Dönmeye çalıştığınız admin hesabı bulunamadı");
        }
        beCookie::beCreateCookie("be_user",$admincontent,true,true,-1);
        beCookie::beDeleteCookie("be_user_admin");
        beRouter::beRedirect(beGetRoute("admin.dashboard"));
    }
    public function search_post(){
        $sort = (int)$_POST["sort"];
        if(!$sort){
            $sort = 1;
        }
        $page = (int)$_POST["page"];
        if(!$page){
            $page = 1;
        }
        $username = $_POST["user"];
        $userids = [];
        $data = $_POST["data"];
        $options = (int)$_POST["options"];
        if($username){
            $userdata = explode(" ",$username);
            $namecount = count($userdata);
            switch($namecount){
                case 1 :
                    $userlist = AuthModel::beSelect("uid")->beWhere("name",$userdata[0],"LIKE")->beGetAll();
                    if(!$userlist){
                        $userlist = AuthModel::beSelect("uid")->beWhere("surname",$userdata[0],"LIKE")->beGetAll();
                    }
                    if(!$userlist){
                        $userlist = AuthModel::beSelect("uid")->beWhere("email",$userdata[0],"LIKE")->beGetAll();
                    }
                    break;
                case 2 :
                    $userlist = AuthModel::beSelect("uid")->beWhere("name",$userdata[0],"LIKE")->beWhere("surname",$userdata[1],"LIKE")->beGetAll();
                    break;
                case 3 :
                    $userlist = AuthModel::beSelect("uid")->beWhere("name",$userdata[0]." ".$userdata[1],"LIKE")->beWhere("surname",$userdata[2],"LIKE")->beGetAll();
                    break;
            }
        }
        if($userlist){
            foreach($userlist as $user){
                $userids[] = (int)$user["uid"];
            }
        }
        if(!$userids && $data){
            $userlist = UserInfoModel::beSelect("uid")->beWhere("uiphone",$data,"LIKE")->beGetAll();
            if(!$userlist){
                $userlist = UserInfoModel::beSelect("uid")->beWhere("uiaddress",$data,"LIKE")->beGetAll();
            }
            if($userlist){
                foreach($userlist as $user){
                    $userids[] = (int)$user["uid"];
                }
            }
        }
        $usersearch = AuthModel::beSelect("COUNT(uid) as total");
        if($userids){
            $usersearch = $usersearch->beWhere("uid",$userids,"IN");
        }
        $usercount = (int)$usersearch->beGet()["total"];
        $paganation = bePaganation($page,$usercount);
        $users = AuthModel::beTable("be_users as u")->beSelect("u.uid,u.cid,u.name,u.surname,u.email,u.money,u.regdate,ui.uidial,ui.uiphone");
        if($userids){
            $users = $users->beWhere("u.uid",$userids,"IN");
        }
        if($paganation["itemstart"] == 0){
            $users = $users->beLimit($paganation["itemlimit"]);
        }
        else{
            $users = $users->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
        }
        $orderkey = "u.uid";
        switch($options){
            case 1 : 
                $orderkey = "u.uid";
                break;
            case 2 :
                $orderkey = "money";
                break;
        }
        switch($sort){
            case 1 :
                $users = $users->beOrder($orderkey,"DESC");
                break;
            case 2 :
                $users = $users->beOrder($orderkey,"ASC");
                break;
        }
        $users = $users->beJoin("INNER JOIN be_user_info as ui ON ui.uid = u.uid")->beGetAll();
        $currencies = CurrencyModel::beGetCurrencies("cid,cicon");
        $orderhtml = beGetView("admin.user.listrows",["users" => $users,"currencies" => $currencies]);
        return beAjaxSuccess(["html" => $orderhtml,"paganation" => $paganation["paganation"],"usercount" => $usercount]);
    }
    public function beSetUserMessages($lid,&$userlogs){
        $vieweruser = Auth::beGetUser();
        $admin = false;
        if($vieweruser["group"]["ugpermissions"]["admin_user_show"] == 1){
            $admin = true;
        }
        foreach($userlogs as $key => $item){
            $ldata = json_decode($item["ldata"],true);
            switch($item["ltype"]){
                case "login" :
                    $userlogs[$key]["lmessage"] = "Hesaba giriş yapıldı!";
                    break;
                case "money_change" :
                    $admin = Auth::beGetUser($ldata["admin"],"uid,name,surname");
                    $types = [-1 => "çıkarıldı",1 => "eklendi"];
                    if($admin){
                        $userlogs[$key]["lmessage"] = "Hesaba <a href=\"".beGetRoute('admin.user.show',["uid" => $admin["uid"]])."\">{$admin['name']} {$admin['surname']}</a> adlı yetkili tarafından {$ldata['amount']}{$ldata['currencie']['cicon']} kadar bakiye {$types[$ldata['type']]}!";
                    }
                    else{
                        $userlogs[$key]["lmessage"] = "Hesaba ekip tarafından {$ldata['amount']}{$ldata['currencie']['cicon']} kadar bakiye {$types[$ldata['type']]}!";
                    }
                    break;
                case "invoice_extend" :
                    if($admin){
                        $userlogs[$key]["lmessage"] = "Hesaba <a href=\"".beGetRoute("admin.invoice.show",["iid" => $ldata["iid"]])."\">#{$ldata['iid']}</a> numlaralı fatura hizmet uzatımı için oluşturuldu!";
                    }
                    else{
                        $userlogs[$key]["lmessage"] = "Hesaba <a href=\"".beGetRoute("client.invoice.invoice",["iid" => $ldata["iid"]])."\">#{$ldata['iid']}</a> numlaralı fatura hizmet uzatımı için oluşturuldu!";
                    }
                case "invoice_create_payment" :
                    $userlogs[$key]["lmessage"] = "Sipariş için oluştulan fatura ödendi!";
                    break;
            }
        }
    }
}
?>