<?php

namespace App\System\Controller;
use App\System\Basic\beContoller;
use App\System\Basic\beModel;
use App\System\Basic\beRouter;
use App\System\Model\AttachmentModel;
use App\System\Model\AuthModel;
use App\System\Model\CurrencyModel;
use App\System\Model\LanguageModel;
use App\System\Model\MessageTemplateModel;
use App\System\Model\SettingModel;
use App\System\Model\TicketAdminSignatureModel;
use App\System\Model\TicketDepertmentModel;
use App\System\Model\TicketModel;
use App\System\Model\TicketPostModel;
use App\System\Model\TicketPredefinedCategoriesModel;
use App\System\Model\TicketPredefinedRepliesModel;
use App\System\Model\UserGroupModel;
use App\System\Model\UserInfoModel;
use App\System\Model\UserProductModel;
use App\System\Vendor\Auth;
use App\System\Vendor\beAlert;
use App\System\Vendor\beLanguage;
use App\System\Vendor\beMail;
use App\System\Vendor\bePlugin;
use App\System\Vendor\beSms;
use App\System\Vendor\beTicket;
use League\CLImate\TerminalObject\Basic\Json;

class TicketController extends beContoller {
    public function list($status){
        $user = Auth::beGetUser();
        $depertmentlist = TicketDepertmentModel::beTable("be_ticket_depertments as td")->beSelect("td.tdid,tdadmins,tdname")->beWhere("tdt.lid",$user["lid"])->beJoin("INNER JOIN be_ticket_depertment_translations as tdt ON tdt.tdid = td.tdid")->beGetAll();
        $depertments = [];
        foreach($depertmentlist as $depertment){
            $depertments[(int)$depertment["tdid"]] = $depertment;
        }
        return beGetView("admin.ticket.list",["status" => $status,"depertments" => $depertments]);
    }
    public function add(){
        $admin = Auth::beGetUser();
        $depertments = TicketDepertmentModel::beTable("be_ticket_depertments as td")->beSelect("td.tdid,tdname")->beWhere("tdt.lid",$admin["lid"])->beJoin("INNER JOIN be_ticket_depertment_translations as tdt ON tdt.tdid = td.tdid")->beGetAll();
        return beGetView("admin.ticket.add",["depertments" => $depertments]);
    }
    public function add_post(){
        $admin = Auth::beGetUser();
        beLanguage::beReadLang("ticket");
        beLanguage::beReadLang("order");
        beLanguage::beReadLang("form");
        beLanguage::beReadLang("user");
        $uid = (int)$_POST["user"];
        $user = Auth::beGetUser($uid);
        if(!$user){
            return beAjaxError(["message" => beGetLang("user_not_found")]);
        }
        $subject = htmlspecialchars($_POST["subject"]);
        $tdid = (int)$_POST["depertment"];
        $upid = (int)$_POST["userproduct"];
        $message = strip_tags($_POST["message"],"<p><a><br><b><em><span><sup><code><h2><h3><h4><h5>");
        if(empty($subject) || empty($message)){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        $depertment = TicketDepertmentModel::beSelect("tdid,tdadmins")->beWhere("tdid",$tdid)->beGet();
        if(!$depertment){
            return beAjaxError(["message" => beGetLang("ticket_depertment_not_found")]);
        }
        if($upid){
            $order = UserProductModel::beSelect("upid")->beWhere("upid",$upid)->beWhere("uid",$user["uid"])->beWhere("upstatus","-1","!=")->beGet();
            if(!$order){
                return beAjaxError(["message" => beGetLang("order_not_found")]);
            }
        }
        $tid = beTicket::beInsertTicket([
            "uid" => $user["uid"],
            "upid" => $upid,
            "subject" => $subject,
            "status" => "active",
            "lastreply" => "user",
            "depertment" => $depertment["tdid"],
            "ipaddress" => beRouter::$beUserIP,
            "dateline" => BE_TIME
        ])["tid"];
        beTicket::beTicketPost([
            "tid" => $tid,
            "uid" => $user["uid"],
            "message" => $message,
            "files" => "[]",
            "ipaddress" => beRouter::$beUserIP,
            "dateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("ticket_created"),"url" => beGetRoute("admin.ticket.show",["tid" => $tid])]);
    }
    public function show($tid){
        $user = Auth::beGetUser();
        beLanguage::beReadLang("ticket");
        $ticket = TicketModel::beTable("be_tickets as t")->beSelect("t.*,up.upname,up.uptag,u.lid,u.name,u.surname,u.usergroup,u2.uid as adminuid,u2.name as adminname,u2.surname as adminsurname")->beWhere("tid",$tid)->beJoin("INNER JOIN be_users as u ON u.uid = t.uid LEFT JOIN be_users as u2 ON u2.uid = tadmin LEFT JOIN be_user_products as up ON up.upid = t.upid")->beGet();
        if(!$ticket){
            beError(beGetLang("ticket"),beGetLang("ticket_not_found"));
        }
        $status = TicketModel::beGetUserTicketStatus();
        $replynames = TicketModel::beGetReplyStatus();
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        $depertmentlist = TicketDepertmentModel::beTable("be_ticket_depertments as td")->beSelect("td.tdid,tdadmins,tdname")->beWhere("tdt.lid",$user["lid"])->beJoin("INNER JOIN be_ticket_depertment_translations as tdt ON tdt.tdid = td.tdid")->beGetAll();
        $depertments = [];
        foreach($depertmentlist as $depertment){
            $depertments[(int)$depertment["tdid"]] = $depertment;
        }
        $usergrouplist = UserGroupModel::beSelect("ugid,ugnamestyle")->beGetAll();
        $usergroups = [];
        foreach($usergrouplist as $usergroup){
            $usergroups[(int)$usergroup["ugid"]] = $usergroup;
        }
        $posts = TicketPostModel::beSelect("u.name,u.surname,u.usergroup,be_ticket_posts.*")->beWhere("be_ticket_posts.tid",$ticket["tid"])->beJoin("INNER JOIN be_users as u ON u.uid = be_ticket_posts.uid")->beOrder("tpid","DESC")->beGetAll();
        foreach($posts as $key => $post){
            $tpfiles = json_decode($post["tpfiles"],true);
            if($tpfiles){
                $attachments = AttachmentModel::beSelect("aid,aname,aslug,asize,adateline")->beWhere("aid",$tpfiles,"IN")->beGetAll();
                $posts[$key]["attachments"] = $attachments;
            }
        }
        $predefinedreplies = TicketPredefinedCategoriesModel::beGetAll();
        foreach($predefinedreplies as $key => $predefinedreply){
            $predefinedreplies[$key]["messages"] = TicketPredefinedRepliesModel::beSelect("tprid,tprname")->beWhere("tpcid",$predefinedreply["tpcid"])->beOrder("tprusage","DESC")->beGetAll();
        }
        $signature = TicketAdminSignatureModel::beSelect("tasid,tasmessage")->beWhere("uid",$user["uid"])->beWhere("lid",$ticket["lid"])->beWhere("tastime","all")->beGet();
        if(!$signature){
            $hour = date("H",BE_TIME);
            $type = "day";
            if($hour > 18){
                $type = "night";
            }
            $signature = TicketAdminSignatureModel::beSelect("tasid,tasmessage")->beWhere("uid",$user["uid"])->beWhere("lid",$ticket["lid"])->beWhere("tastime",$type)->beGet();
            if(!$signature){
                $signature = [];
            }
        }
        $buttons = [];
        $buttons = bePlugin::beRunHook("admin_ticket_show_buttons",["ticket" => $ticket,"depertments" => $depertments,"posts" =>$posts,"buttons" => $buttons])["buttons"];
        return beGetView("admin.ticket.show",[
            "ticket" => $ticket,
            "posts" => $posts,
            "status" => $status,"predefinedreplies" => $predefinedreplies,
            "signature" => $signature,
            "depertments" => $depertments,"replycategories" => $replynames,
            "currencies" => $currencies,"usergroups" => $usergroups,
            "buttons" => $buttons 
        ]);
    }
    public function status_post(){
        beLanguage::beReadLang("ticket");
        $tid = (int)$_POST["tid"];
        $status = (int)$_POST["status"];
        $ticket = beTicket::beGetTicket($tid,"tid");
        if(!$ticket["status"]){
            return beAjaxError(["message" => $ticket["message"]]);
        }
        $updatestatus = beTicket::beUpdateTicketStatus($ticket["tid"],$status);
        if(!$updatestatus["status"]){
            return beAjaxError(["message" => $updatestatus["message"]]);
        }
        return beAjaxSuccess(["message" => beGetLang("ticket_updated")]);
    }
    public function depertment_post(){
        beLanguage::beReadLang("ticket");
        $tid = (int)$_POST["tid"];
        $tdid = (int)$_POST["depertment"];
        $ticket = beTicket::beGetTicket($tid,"tid");
        if(!$ticket["status"]){
            return beAjaxError(["message" => $ticket["message"]]);
        }
        $updatedepatment = beTicket::beUpdateTicketDepartment($ticket["tid"],$tdid);
        if(!$updatedepatment["status"]){
            return beAjaxError(["message" => $updatedepatment["message"]]);
        }
        return beAjaxSuccess(["message" => beGetLang("ticket_updated")]);
    }
    public function admin_post(){
        beLanguage::beReadLang("user");
        beLanguage::beReadLang("ticket");
        $tid = (int)$_POST["tid"];
        $ticket = beTicket::beGetTicket($tid,"tid");
        if(!$ticket["status"]){
            return beAjaxError(["message" => $ticket["message"]]);
        }
        $uid = (int)$_POST["admin"];
        $user = Auth::beGetUser($uid,"uid");
        if(!$user){
            return beAjaxError(["message" => beGetLang("user_not_found")]);
        }
        beTicket::beUpdateTicketAdmin($ticket["tid"],$user["uid"]);
        return beAjaxSuccess(["message" => beGetLang("ticket_updated")]);
    }
    public function newmesssage_post(){
        beLanguage::beReadLang("ticket");
        $admin = Auth::beGetUser();
        $tid = (int)$_POST["tid"];
        $ticket = beTicket::beGetTicket($tid,"uid,tid,tsubject,tadmin");
        $user = Auth::beGetUser($ticket["uid"],"uid,name,surname,email");
        if(!$ticket["status"]){
            return beAjaxError(["message" => $ticket["message"]]);
        }
        $updateticket = [
            "tlastreply" => "admin"
        ];
        if(!$ticket["tadmin"]){
            $updateticket["tadmin"] = $admin["uid"];
        }
        $chekpost = (int)$_POST["chekpost"];
        if($chekpost){
            $tpid = (int)$_POST["lastpost"];
            $lastpost = TicketPostModel::beWhere("tpid",$tpid,">")->beWhere("tid",$ticket["tid"])->beGet();
            if($lastpost){
                return beAjaxError(["message" => "Sizden önce bir mesaj yazıldı!","askoverride" => true]);
            }
        }
        $message = $_POST["message"];
        $aidlist = $_POST["aidlist"];
        $files = [];
        foreach($aidlist as $aid){
            $attachment = AttachmentModel::beSelect("aid")->beWhere("aid",(int)$aid)->beWhere("uid",$admin["uid"])->beGet();
            if($attachment){
                $files[] = (int)$attachment["aid"];
            }
        }
        preg_match_all("/\[aid=(.*)\]/",$message,$matches);
        if($matches){
            $message = str_replace($matches[0],"",$message);
            $message = str_replace("<p></p>","",$message);
            foreach($matches[1] as $aid){
                $files[] = (int)$aid;
            }
        }
        $message = str_replace(["{namesurname}","{adminnamesurname}","{email}","{sitename}","{siteurl}","{siteshortname}","{sitephone}","{timenow}"],[$user["name"]." ".$user["surname"],$admin["name"]." ".$admin["surname"],$user["email"],beGetConfig("sitename"),beGetConfig("siteurl"),beGetConfig("siteshortname"),beGetConfig("phone_text"),beSpecialTime(BE_TIME)],$message);
        beTicket::beTicketPost([
            "tid" => $ticket["tid"],
            "uid" => $admin["uid"],
            "message" => $message,
            "files" => json_encode($files,JSON_UNESCAPED_UNICODE),
            "ipaddress" => beRouter::$beUserIP,
            "dateline" => BE_TIME
        ]);
        $userinfo = UserInfoModel::beSelect("uid,uisettings")->beWhere("uid",$ticket["uid"])->beGet();
        $ticketlink = beGetRoute("client.ticket.ticket",["tid" => $tid]);
        $uisettings = json_decode($userinfo["uisettings"],true);
        $messages = MessageTemplateModel::beGetMessages("ticket_replied_user",1)["ticket_replied_user"];
        if($messages["alert"] && $uisettings["notification_alert"]){
            $message = str_replace(["{sitename}","{ticketname}","{namesurname}","{adminname}","{ticketlink}"],[beGetConfig("sitename"),$ticket["tsubject"],$user["name"]." ".$user["surname"],$admin["name"]." ".$admin["surname"],$ticketlink],$messages["alert"]["mttmessage"]);
            beAlert::beCreateAlert(json_encode(["message" => $message],JSON_UNESCAPED_UNICODE),$ticketlink,$userinfo["uid"]);
        }
        if($messages["sms"] && $uisettings["sms_alert"]){
            $message = str_replace(["{sitename}","{ticketname}","{namesurname}","{adminname}","{ticketlink}"],[beGetConfig("sitename"),$ticket["tsubject"],$user["name"]." ".$user["surname"],$admin["name"]." ".$admin["surname"],$ticketlink],$messages["sms"]["mttmessage"]);
            beSms::beCreateSms($message,1,$userinfo["uid"]);
        }
        if($messages["mail"] && $uisettings["mail_alert"]){
            $message = str_replace(["{sitename}","{ticketname}","{namesurname}","{adminname}","{ticketlink}"],[beGetConfig("sitename"),$ticket["tsubject"],$user["name"]." ".$user["surname"],$admin["name"]." ".$admin["surname"],$ticketlink],$messages["mail"]["mttmessage"]);
            beMail::beCreateMail($messages["mail"]["mttsubject"],$message,2,1,$userinfo["uid"]);
        }
        $updateticket["tlastreplydateline"] = BE_TIME;
        beTicket::beUpdateTicket($ticket["tid"],$updateticket);
        return beAjaxSuccess(["message" => beGetLang("ticket_replied")]);
    }
    public function getpredefinedreply_post(){
        beLanguage::beReadLang("ticket");
        $tprid = (int)$_POST["tprid"];
        $definedreply = TicketPredefinedRepliesModel::beSelect("tprid,tprmessage,tprusage")->beWhere("tprid",$tprid)->beGet();
        if(!$definedreply){
            return beAjaxError(["message" => beGetLang("ticket_predefined_message_not_found")]);
        }
        TicketPredefinedRepliesModel::beUpdate(["tprusage" => $definedreply["tprusage"]+1])->beWhere("tprid",$definedreply["tprid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("ticket_predefined_message_found"),"definedreply" => $definedreply["tprmessage"]]);
    }
    public function delete_post(){
        beLanguage::beReadLang("ticket");
        $tid = (int)$_POST["tid"];
        $ticket = beTicket::beGetTicket($tid,"tid");
        if(!$ticket["status"]){
            return beAjaxError(["message" => beGetLang("ticket_not_found")]);
        }
        TicketPostModel::beDelete()->beWhere("tid",$ticket["tid"])->beExecute();
        TicketModel::beDelete()->beWhere("tid",$ticket["tid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("ticket_deleted")]);
    }
    public function depertment_list(){
        $user = Auth::beGetUser();
        $depertments = TicketDepertmentModel::beTable("be_ticket_depertments as td")->beSelect("td.tdid,td.tdadmins,td.tddateline,tdt.lid,tdt.tdname")->beWhere("tdt.lid",$user["lid"])->beJoin("INNER JOIN be_ticket_depertment_translations AS tdt ON tdt.tdid = td.tdid")->beGetAll();
        foreach($depertments as $key => $depertment){
            $tdadmins = json_decode($depertment["tdadmins"],true);
            foreach($tdadmins as $uid){
                $depertments[$key]["admins"][] = Auth::beGetUser($uid,"uid,name,surname");
            }
        }
        return beGetView("admin.ticket.depertment.list",["depertments" => $depertments]);
    }
    public function depertment_add(){
        $languages = LanguageModel::beGetLanguages("lid,lname");
        $usergroups = UserGroupModel::beSelect("ugid,ugpermissions")->beGetAll();
        $ugidlist = [];
        foreach($usergroups as $usergroup){
            $ugpermissions = json_decode($usergroup["ugpermissions"],true);
            if($ugpermissions["admin_ticket_show"] == 1 && $ugpermissions["admin_ticket_message_add"] == 1){
                $ugidlist[] = (int)$usergroup["ugid"];
            }
        }
        $ticketusers = AuthModel::beSelect("uid,name,surname")->beWhere("usergroup",$ugidlist,"IN")->beGetAll();
        return beGetView("admin.ticket.depertment.add",["ticketusers" => $ticketusers,"languages" => $languages]);
    }
    public function depertment_add_post(){
        beLanguage::beReadLang("user");
        beLanguage::beReadLang("ticket");
        beLanguage::beReadLang("language");
        $name = $_POST["name"];
        $lid = (int)$_POST["language"];
        $language = LanguageModel::beGetLanguages("lid",$lid);
        if(!$language){
            return beAjaxError(["message" => beGetLang("language_not_found")]);
        }
        $users = $_POST["users"];
        $uidlist = [];
        foreach($users as $uid){
            $user = Auth::beGetUser((int)$uid,"uid");
            if(!$user){
                return beAjaxError(["message" => beGetLang("user_not_found")]);
            }
            $uidlist[] = (int)$uid;
        }
        $tdid = TicketDepertmentModel::beInsert([
            "tdadmins" => json_encode($uidlist),
            "tddateline" => BE_TIME
        ]);
        beModel::beInsert([
            "tdid" => $tdid,
            "lid" => $language["lid"],
            "tdname" => $name
        ],"be_ticket_depertment_translations");
        return beAjaxSuccess(["message" => beGetLang("ticket_depertment_created"),"url" => beGetRoute("admin.ticket.depertment.list")]);
    }
    public function depertment_edit($tdid){
        beLanguage::beReadLang("ticket");
        global $be;
        $depertment = TicketDepertmentModel::beWhere("tdid",$tdid)->beGet();
        if(!$depertment){
            return beAjaxError(["message" => beGetLang("ticket_depertment_not_found")]);
        }
        $tdadmins = json_decode($depertment["tdadmins"],true);
        foreach($tdadmins as $uid){
            $depertment["admins"][] = (int)$uid;
        }
        $depertmenttranslations = beModel::beTable("be_ticket_depertment_translations")->beSelect("tdtid,lid,tdname")->beWhere("tdid",$depertment["tdid"])->beGetAll();
        $usergroups = UserGroupModel::beSelect("ugid,ugpermissions")->beGetAll();
        $ugidlist = [];
        foreach($usergroups as $usergroup){
            $ugpermissions = json_decode($usergroup["ugpermissions"],true);
            if($ugpermissions["admin_ticket_list"] == 1 && $ugpermissions["admin_ticket_message_add"] == 1){
                $ugidlist[] = (int)$usergroup["ugid"];
            }
        }
        $ticketusers = AuthModel::beSelect("uid,name,surname")->beWhere("usergroup",$ugidlist,"IN")->beGetAll();
        $languages = LanguageModel::beGetLanguages("lid,lname");
        $systemlid = $be->settings["system_language"];
        return beGetView("admin.ticket.depertment.edit",["depertment" => $depertment,"depertmenttranslations" => $depertmenttranslations,"ticketusers" => $ticketusers,"languages" => $languages,"systemlid" => $systemlid]);
    }
    public function depertment_edit_post(){
        beLanguage::beReadLang("ticket");
        beLanguage::beReadLang("user");
        $tdid = (int)$_POST["tdid"];
        $depertment = TicketDepertmentModel::beSelect("tdid")->beWhere("tdid",$tdid)->beGet();
        if(!$depertment){
            return beAjaxError(["message" => beGetLang("ticket_depertment_not_found")]);
        }
        $users = $_POST["users"];
        $uidlist = [];
        foreach($users as $uid){
            $user = Auth::beGetUser((int)$uid,"uid");
            if(!$user){
                return beAjaxError(["message" => beGetLang("user_not_found")]);
            }
            $uidlist[] = (int)$uid;
        }
        TicketDepertmentModel::beUpdate(["tdadmins" => json_encode($uidlist)])->beWhere("tdid",$depertment["tdid"])->beExecute();
        $languages = LanguageModel::beGetLanguages("lid");
        foreach($languages as $language){
            $tdname = $_POST["tdname"][(int)$language["lid"]];
            if($tdname){
                $depertmenttranslation = beModel::beTable("be_ticket_depertment_translations")->beSelect("tdtid")->beWhere("tdid",$depertment["tdid"])->beWhere("lid",$language["lid"])->beGet();
                if($depertmenttranslation){
                    beModel::beUpdate([
                        "tdname" => $tdname
                    ],"be_ticket_depertment_translations")->beWhere("tdtid",$depertmenttranslation["tdtid"])->beExecute();
                }
                else{
                    beModel::beInsert([
                        "tdid" => $tdid,
                        "lid" => $language["lid"],
                        "tdname" => $tdname
                    ],"be_ticket_depertment_translations");
                }
            }
        }
        return beAjaxSuccess(["message" => beGetLang("ticket_depertment_updated")]);
    }
    public function depertment_delete_post(){
        beLanguage::beReadLang("ticket");
        $tdid = (int)$_POST["tdid"];
        $depertment = TicketDepertmentModel::beSelect("tdid")->beWhere("tdid",$tdid)->beGet();
        if(!$depertment){
            return beAjaxError(["message" => "Belirtilen destek departmanı sistem üzerinde bulunamadı!"]);
        }
        TicketDepertmentModel::beDelete()->beWhere("tdid",$depertment["tdid"])->beExecute();
        beModel::beDelete("be_ticket_depertment_translations")->beWhere("tdid",$depertment["tdid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("ticket_depertment_deleted")]);
    }
    public function predefinedcategory_list(){
        $predefinedcategories = TicketPredefinedCategoriesModel::beGetAll();
        return beGetView("admin.ticket.predefinedcategories.list",["predefinedcategories" => $predefinedcategories]);
    }
    public function predefinedcategory_add(){
        return beGetView("admin.ticket.predefinedcategories.add");
    }
    public function predefinedcategory_add_post(){
        beLanguage::beReadLang("ticket");
        $name = $_POST["name"];
        TicketPredefinedCategoriesModel::beInsert([
            "tpcname" => $name,
            "tpcdateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("ticket_predefined_category_created"),"url" => beGetRoute("admin.ticket.predefined.category.list")]);
    }
    public function predefinedcategory_edit($tpcid){
        beLanguage::beReadLang("ticket");
        $predefinedcategory = TicketPredefinedCategoriesModel::beSelect("tpcid,tpcname")->beWhere("tpcid",$tpcid)->beGet();
        if(!$predefinedcategory){
            beError(beGetLang("ticket"),beGetLang("ticket_predefined_category_not_found"));
        }
        $predefinedreplies = TicketPredefinedRepliesModel::beWhere("tpcid",$predefinedcategory["tpcid"])->beGetAll();
        $languages = LanguageModel::beGetLanguages("lid,lname");
        return beGetView("admin.ticket.predefinedcategories.edit",["predefinedcategory" => $predefinedcategory,"predefinedreplies" => $predefinedreplies,"languages" => $languages]);
    }
    public function predefinedcategory_edit_post(){
        beLanguage::beReadLang("ticket");
        beLanguage::beReadLang("language");
        beLanguage::beReadLang("form");
        $tpcid = (int)$_POST["tpcid"];
        $predefinedcategory = TicketPredefinedCategoriesModel::beSelect("tpcid")->beWhere("tpcid",$tpcid)->beGet();
        if(!$predefinedcategory){
            beError(beGetLang("ticket"),beGetLang("ticket_predefined_category_not_found"));
        }
        $languages = LanguageModel::beGetLanguages("lid");
        $predefinedreplies = TicketPredefinedRepliesModel::beSelect("tprid")->beWhere("tpcid",$predefinedcategory["tpcid"])->beGetAll();
        foreach($predefinedreplies as $predefinedreply){
            $tprid = $predefinedreply["tprid"];
            $lid = (int)$_POST["language"][$tprid];
            if(!$languages[$lid]){
                return beAjaxError(["message" => beGetLang("language_not_found")]);
            }
            if(empty($_POST["name"][$tprid]) || empty($_POST["message"][$tprid])){
                return beAjaxError(["message" => beGetLang("form_not_full")]);
            }
            TicketPredefinedRepliesModel::beUpdate([
                "lid" => $lid, 
                "tpcid" => $predefinedcategory["tpcid"],
                "tprname" => $_POST["name"][$tprid],
                "tprmessage" => $_POST["message"][$tprid],
             ])->beWhere("tprid",$tprid)->beExecute();
        }
        return beAjaxSuccess(["message" => beGetLang("ticket_predefined_category_updated")]);
    }
    public function predefinedcategory_delete_post(){
        beLanguage::beReadLang("ticket");
        $tpcid = (int)$_POST["tpcid"];
        $predefinedcategory = TicketPredefinedCategoriesModel::beSelect("tpcid")->beWhere("tpcid",$tpcid)->beGet();
        if(!$predefinedcategory){
            beError(beGetLang("ticket"),beGetLang("ticket_predefined_category_not_found"));
        }
        TicketPredefinedCategoriesModel::beDelete()->beWhere("tpcid",$predefinedcategory["tpcid"])->beExecute();
        TicketPredefinedRepliesModel::beDelete()->beWhere("tpcid",$predefinedcategory["tpcid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("ticket_predefined_category_deleted")]);
    }
    public function predefinedreply_add_post(){
        beLanguage::beReadLang("ticket");
        beLanguage::beReadLang("language");
        $tpcid = (int)$_POST["tpcid"];
        $predefinedcategory = TicketPredefinedCategoriesModel::beSelect("tpcid")->beWhere("tpcid",$tpcid)->beGet();
        if(!$predefinedcategory){
            beError(beGetLang("ticket"),beGetLang("ticket_predefined_category_not_found"));
        }
        $name = $_POST["add_name"];
        $lid = (int)$_POST["add_language"];
        $message = $_POST["add_message"];
        $language = LanguageModel::beGetLanguages("lid",$lid);
        if(!$language){
            return beAjaxError(["message" => beGetLang("language_not_found")]);
        }
        TicketPredefinedRepliesModel::beInsert([
           "lid" => $lid, 
           "tpcid" => $predefinedcategory["tpcid"],
           "tprname" => $name,
           "tprmessage" => $message,
           "tprusage" => 0,
           "tprdateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("ticket_predefined_reply_created")]);
    }
    public function predefinedreply_delete_post(){
        beLanguage::beReadLang("ticket");
        $tpcid = (int)$_POST["tpcid"];
        $predefinedcategory = TicketPredefinedCategoriesModel::beSelect("tpcid")->beWhere("tpcid",$tpcid)->beGet();
        if(!$predefinedcategory){
            beError(beGetLang("ticket"),beGetLang("ticket_predefined_category_not_found"));
        }
        $tprid = (int)$_POST["tprid"];
        $predefinedreply = TicketPredefinedRepliesModel::beSelect("tprid")->beWhere("tprid",$tprid)->beGet();
        if(!$predefinedreply){
            beError(beGetLang("ticket"),beGetLang("ticket_predefined_reply_not_found"));
        }
        TicketPredefinedRepliesModel::beDelete()->beWhere("tprid",$predefinedreply["tprid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("ticket_predefined_reply_deleted")]);
    }
    public function adminsignature_add_post(){
        beLanguage::beReadLang("user");
        beLanguage::beReadLang("ticket");
        beLanguage::beReadLang("language");
        $uid = (int)$_POST["user"];
        $lid = (int)$_POST["language"];
        $type = $_POST["type"];
        $message = $_POST["message"];
        $user = Auth::beGetUser($uid,"uid");
        if(!$user){
            return beAjaxError(["message" => beGetLang("user_not_found")]);
        }
        $signaturestimes = TicketAdminSignatureModel::beGetTicketAdminSignatureTimes();
        if(!array_key_exists($type,$signaturestimes)){
            return beAjaxError(["message" => beGetLang("ticket_signature_time_not_found")]);
        }
        $language = LanguageModel::beGetLanguages("lid",$lid);
        if(!$language){
            return beAjaxError(["message" => beGetLang("language_not_found")]);
        }
        TicketAdminSignatureModel::beInsert([
            "uid" => $user["uid"],
            "lid" => $language["lid"],
            "tastime" => $type,
            "tasmessage" => $message,
            "tasdateline" => BE_TIME
        ]);
        return beAjaxSuccess(["message" => beGetLang("ticket_signature_created")]);
    }
    public function adminsignature_edit($tasid){
        beLanguage::beReadLang("ticket");
        $signature = TicketAdminSignatureModel::beWhere("tasid",$tasid)->beGet();
        if(!$signature){
            beError(beGetLang("ticket"),beGetLang("ticket_signature_not_found"));
        }
        $signaturestypes = TicketAdminSignatureModel::beGetTicketAdminSignatureTimes();
        $languages = LanguageModel::beGetLanguages("lid,lname,lcode");
        return beGetView("admin.ticket.signature.edit",["signature" => $signature,"signaturestypes" => $signaturestypes,"languages" => $languages]);
    }
    public function adminsignature_edit_post(){
        beLanguage::beReadLang("ticket");
        beLanguage::beReadLang("language");
        $tasid = (int)$_POST["tasid"];
        $signature = TicketAdminSignatureModel::beSelect("tasid")->beWhere("tasid",$tasid)->beGet();
        if(!$signature){
            return beAjaxError(["message" => beGetLang("ticket_signature_not_found")]);
        }
        $lid = (int)$_POST["language"];
        $type = $_POST["type"];
        $message = $_POST["message"];
        $signaturestypes = TicketAdminSignatureModel::beGetTicketAdminSignatureTimes();
        if(!array_key_exists($type,$signaturestypes)){
            return beAjaxError(["message" => beGetLang("ticket_signature_time_not_found")]);
        }
        $language = LanguageModel::beGetLanguages("lid",$lid);
        if(!$language){
            return beAjaxError(["message" => beGetLang("language_not_found")]);
        }
        TicketAdminSignatureModel::beUpdate([
            "lid" => $language["lid"],
            "tastime" => $type,
            "tasmessage" => $message,
        ])->beWhere("tasid",$signature["tasid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("ticket_signature_updated")]);
    }
    public function adminsignature_delete_post(){
        beLanguage::beReadLang("ticket");
        $tasid = (int)$_POST["tasid"];
        $signature = TicketAdminSignatureModel::beSelect("tasid")->beWhere("tasid",$tasid)->beGet();
        if(!$signature){
            return beAjaxError(["message" => beGetLang("ticket_signature_not_found")]);
        }
        TicketAdminSignatureModel::beDelete()->beWhere("tasid",$signature["tasid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("ticket_signature_deleted")]);
    }
    public function search_post(){
        $user = Auth::beGetUser();
        $pageitems = (int)$_POST["pageitems"];
        $name = $_POST["name"];
        $sort = (int)$_POST["sort"];
        if(!$sort){
            $sort = 1;
        }
        $page = (int)$_POST["page"];
        if(!$page){
            $page = 1;
        }
        $status = $_POST["status"];
        $depertment = (int)$_POST["depertment"];
        $username = $_POST["user"];
        $userid = 0;
        if($username){
            $userdata = explode(" ",$username);
            $namecount = count($userdata);
            switch($namecount){
                case 1 :
                    $userid = AuthModel::beSelect("uid")->beWhere("name",$userdata[0])->beGet()["uid"];
                    if(!$userid){
                        $userid = AuthModel::beSelect("uid")->beWhere("email",$userdata[0])->beGet()["uid"];
                    }
                    break;
                case 2 :
                    $userid = AuthModel::beSelect("uid")->beWhere("name",$userdata[0])->beWhere("surname",$userdata[1])->beGet()["uid"];
                    break;
                case 3 :
                    $userid = AuthModel::beSelect("uid")->beWhere("name",$userdata[0]." ".$userdata[1])->beWhere("surname",$userdata[2])->beGet()["uid"];
                    break;
            }
        }
        if($_POST["uid"]){
            $userid = (int)$_POST["uid"];
        }
        $adminname = $_POST["admin"];
        $adminid = 0;
        if($username){
            $userdata = explode(" ",$adminname);
            $namecount = count($userdata);
            switch($namecount){
                case 1 :
                    $adminid = AuthModel::beSelect("uid")->beWhere("name",$userdata[0])->beGet()["uid"];
                    if(!$adminid){
                        $adminid = AuthModel::beSelect("uid")->beWhere("email",$userdata[0])->beGet()["uid"];
                    }
                    break;
                case 2 :
                    $adminid = AuthModel::beSelect("uid")->beWhere("name",$userdata[0])->beWhere("surname",$userdata[1])->beGet()["uid"];
                    break;
                case 3 :
                    $adminid = AuthModel::beSelect("uid")->beWhere("name",$userdata[0]." ".$userdata[1])->beWhere("surname",$userdata[2])->beGet()["uid"];
                    break;
            }
        }
        if($_POST["adminuid"]){
            $adminid = (int)$_POST["adminuid"];
        }
        $ticketsearch = TicketModel::beSelect("COUNT(tid) as total");
        if($name){
            $ticketsearch = $ticketsearch->beWhere("tname",$name,"LIKE");
        }
        if($status && $status != "all"){
            $ticketsearch = $ticketsearch->beWhere("tstatus",$status);
        }
        if($depertment){
            $ticketsearch = $ticketsearch->beWhere("tdepertment",$depertment);
        }
        if($userid){
            $ticketsearch = $ticketsearch->beWhere("uid",$userid);
        }
        if($adminid){
            $ticketsearch = $ticketsearch->beWhere("tadmin",$adminid);
        }
        $ticketcount = (int)$ticketsearch->beGet()["total"];
        $paganation = bePaganation($page,$ticketcount,"",$pageitems);
        $tickets = TicketModel::beTable("be_tickets as t")->beSelect("tid,t.uid,t.upid,tsubject,tstatus,tlastreply,tdepertment,tadmin,tdateline,up.upname,up.uptag,u1.uid as useruid,u1.name as username,u1.surname as usersurname,u1.usergroup as usergroup,u2.uid as adminuid,u2.name as adminname,u2.surname as adminsurname,u2.usergroup as admingroup");
        if($name){
            $tickets = $tickets->beWhere("tname",$name,"LIKE");
        }
        if($status && $status != "all"){
            $tickets = $tickets->beWhere("tstatus",$status);
        }
        if($depertment){
            $tickets = $tickets->beWhere("tdepertment",$depertment);
        }
        if($userid){
            $tickets = $tickets->beWhere("t.uid",$userid);
        }
        if($adminid){
            $tickets = $tickets->beWhere("tadmin",$adminid);
        }
        if($paganation["itemstart"] == 0){
            $tickets = $tickets->beLimit($paganation["itemlimit"]);
        }
        else{
            $tickets = $tickets->beLimit($paganation["itemstart"],$paganation["itemlimit"]);
        }
        $orderkey = "tlastreply,tid";
        switch($sort){
            case 1 :
                $tickets = $tickets->beOrder($orderkey,"ASC");
                break;
            case 2 :
                $tickets = $tickets->beOrder($orderkey,"DESC");
                break;
        }
        $tickets = $tickets->beJoin("INNER JOIN be_users as u1 ON u1.uid = t.uid LEFT JOIN be_users as u2 ON u2.uid = tadmin LEFT JOIN be_user_products as up ON up.upid = t.upid")->beGetAll();
        $status = TicketModel::beGetUserTicketStatus();
        $replynames = TicketModel::beGetReplyStatus();
        $depertmentlist = TicketDepertmentModel::beTable("be_ticket_depertments as td")->beSelect("td.tdid,tdadmins,tdname")->beWhere("tdt.lid",$user["lid"])->beJoin("INNER JOIN be_ticket_depertment_translations as tdt ON tdt.tdid = td.tdid")->beGetAll();
        $depertments = [];
        foreach($depertmentlist as $depertment){
            $depertments[(int)$depertment["tdid"]] = $depertment;
        }
        $usergrouplist = UserGroupModel::beSelect("ugid,ugname,ugnamestyle")->beGetAll();
        $usergroups = [];
        foreach($usergrouplist as $usergroup){
            $usergroups[(int)$usergroup["ugid"]] = $usergroup;
        }
        $tickethtml = beGetView("admin.ticket.listrows",["tickets" => $tickets,"status" => $status,"replynames" => $replynames,"depertments" => $depertments,"usergroups" => $usergroups]);
        return beAjaxSuccess(["html" => $tickethtml,"paganation" => $paganation["paganation"],"ticketcount" => $ticketcount]);
    }

    public function tickets(){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("ticket");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_tickets"));
        $user = Auth::beGetUser();
        $ticketsactive = TicketModel::beWhere("uid",$user["uid"])->beWhere("tstatus","closed","!=")->beGetAll();
        $ticketsclose = TicketModel::beWhere("uid",$user["uid"])->beWhere("tstatus","closed")->beOrder("tid","DESC")->beLimit(10)->beGetAll();
        $ticketstatus = TicketModel::beGetUserTicketStatus();
        $ticketreplystatus = TicketModel::beGetReplyStatus();
        $depertmens = [];
        $depertmentlist = TicketDepertmentModel::beTable("be_ticket_depertments as td")->beSelect("td.tdid,tdname")->beWhere("tdt.lid",$user["lid"])->beJoin("INNER JOIN be_ticket_depertment_translations as tdt ON tdt.tdid = td.tdid")->beGetAll();
        foreach($depertmentlist as $depertmen){
            $depertmens[(int)$depertmen["tdid"]] = $depertmen;
        }
        beSetHeaderContent("",1);
        return beGetView("clientarea.ticket.list",["ticketsactive" => $ticketsactive,"ticketsclose" => $ticketsclose,"depertmens" => $depertmens,"ticketstatus" => $ticketstatus,"ticketreplystatus" => $ticketreplystatus]);
    }
    public function ticket($tid){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("ticket");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_tickets"));
        $user = Auth::beGetUser();
        $ticket = TicketModel::beWhere("uid",$user["uid"])->beWhere("tid",$tid)->beGet();
        if(!$ticket){
            beError(beGetLang("ticket"),beGetLang("ticket_not_found"));
        }
        NavController::beAddBreadcumb($ticket["tsubject"]);
        $ticketreplystatus = TicketModel::beGetReplyStatus();
        $ticketstatus = TicketModel::beGetUserTicketStatus();
        if($ticket["tdepertment"]){
            $ticket["depertment"] = TicketDepertmentModel::beTable("be_ticket_depertments as td")->beSelect("td.tdid,tdname")->beWhere("tdt.lid",$user["lid"])->beWhere("td.tdid",$ticket["tdepertment"])->beJoin("INNER JOIN be_ticket_depertment_translations as tdt ON tdt.tdid = td.tdid")->beGet();
        }
        $usergrouplist = UserGroupModel::beSelect("ugid,ugname,ugnamestyle")->beGetAll();
        $usergroups = [];
        foreach($usergrouplist as $usergroup){
            $usergroups[(int)$usergroup["ugid"]] = $usergroup;
        }
        global $lastpost;
        $posts = TicketPostModel::beSelect("u.name,u.surname,u.usergroup,be_ticket_posts.*")->beWhere("be_ticket_posts.tid",$ticket["tid"])->beJoin("INNER JOIN be_users as u ON u.uid = be_ticket_posts.uid")->beOrder("tpid","DESC")->beGetAll();
        foreach($posts as $key => $post){
            $tpfiles = json_decode($post["tpfiles"],true);
            if($tpfiles){
                $attachments = AttachmentModel::beSelect("aid,aname,aslug,asize,adateline")->beWhere("aid",$tpfiles,"IN")->beGetAll();
                $posts[$key]["attachments"] = $attachments;
            }
        }
        $ticket_user_files = SettingModel::beGetSettings("ticket_user_files")["ticket_user_files"];
        beSetHeaderContent("",1);
        $postsdata = beGetView("clientarea.ticket.posts",["posts" => $posts,"user" => $user,"usergroups" => $usergroups]);
        return beGetView("clientarea.ticket.ticket",["ticket" => $ticket,"posts" => $postsdata,"lastpost" => $lastpost,"usergroups" => $usergroups,"ticketstatus" => $ticketstatus,"ticketreplystatus" => $ticketreplystatus,"ticket_user_files" => $ticket_user_files]);
    }
    public function newpost_post(){
        beLanguage::beReadLang("ticket");
        $tid = $_POST["tid"];
        $message = strip_tags($_POST["message"],"<p><a><br><b><em><span><sup><code><h2><h3><h4><h5>");
        $user = Auth::beGetUser();
        $ticket = TicketModel::beWhere("uid",$user["uid"])->beWhere("tid",$tid)->beGet();
        if(!$ticket){
            return beAjaxError(["message" => beGetLang("ticket_not_found")]);
        }
        if($ticket["tstatus"] == "closed"){
            return beAjaxError(["message" => beGetLang("ticket_closed")]);
        }
        $userinfo = UserInfoModel::beSelect("uisettings")->beWhere("uid",$user["uid"])->beGet();
        $uisettings = json_decode($userinfo["uisettings"],true);
        $files = [];
        $ticket_user_files = SettingModel::beGetSettings("ticket_user_files")["ticket_user_files"];
        if($ticket_user_files && $uisettings["ticket_files"]){
            $aidlist = $_POST["aidlist"];
            foreach($aidlist as $aid){
                $attachment = AttachmentModel::beSelect("aid")->beWhere("aid",(int)$aid)->beWhere("uid",$user["uid"])->beGet();
                if($attachment){
                    $files[] = (int)$attachment["aid"];
                }
            }
        }
        beTicket::beTicketPost([
            "tid" => $ticket["tid"],
            "uid" => $user["uid"],
            "message" => $message,
            "files" => json_encode($files,JSON_UNESCAPED_UNICODE),
            "ipaddress" => beRouter::$beUserIP,
            "dateline" => BE_TIME
        ]);
        beTicket::beUpdateTicket($ticket["tid"],["tlastreply" => "user","tlastreplydateline" => BE_TIME]);
        $sendinfouids = [];
        if($ticket["tadmin"]){
            $sendinfouids[] = $ticket["tadmin"];
        }
        else{
            if($ticket["tdepertment"]){
                $department = TicketDepertmentModel::beSelect("tdid,tdadmins")->beWhere("tdid",$ticket["tdepertment"])->beGet();
                if(!$department){
                    return beAjaxError(["message" => beGetLang("ticket_depertment_not_found")]);
                }
                $sendinfouids = json_decode($department["tdadmins"],true);
            }
        }
        if($sendinfouids){
            $userinfos = UserInfoModel::beSelect("uid,uisettings")->beWhere("uid",$sendinfouids,"IN")->beGetAll();
            $ticketlink = beGetRoute("admin.ticket.show",["tid" => $tid]);
            foreach($userinfos as $userinfo){
                $uisettings = json_decode($userinfo["uisettings"],true);
                $messages = MessageTemplateModel::beGetMessages("ticket_replied_admin",1)["ticket_replied_admin"];
                if($messages["alert"] && $uisettings["notification_alert"]){
                    $message = str_replace(["{ticketname}","{username}","{ticketlink}"],[$ticket["tsubject"],$user["name"]." ".$user["surname"],$ticketlink],$messages["alert"]["mttmessage"]);
                    beAlert::beCreateAlert(json_encode(["message" => $message],JSON_UNESCAPED_UNICODE),$ticketlink,$userinfo["uid"]);
                }
                if($messages["sms"] && $uisettings["sms_alert"]){
                    $message = str_replace(["{ticketname}","{username}","{ticketlink}"],[$ticket["tsubject"],$user["name"]." ".$user["surname"],$ticketlink],$messages["sms"]["mttmessage"]);
                    beSms::beCreateSms($message,1,$userinfo["uid"]);
                }
                if($messages["mail"] && $uisettings["mail_alert"]){
                    $message = str_replace(["{ticketname}","{username}","{ticketlink}"],[$ticket["tsubject"],$user["name"]." ".$user["surname"],$ticketlink],$messages["mail"]["mttmessage"]);
                    beMail::beCreateMail($messages["mail"]["mttsubject"],$message,2,1,$userinfo["uid"]);
                }
            }
        }
        return beAjaxSuccess(["message" => beGetLang("ticket_replied"),"refresh" => 1]);
    }
    public function newticket(){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("ticket");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_tickets"),beGetRoute("client.ticket.tickets"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_ticket_new"));
        $user = Auth::beGetUser();
        $depertments = TicketDepertmentModel::beTable("be_ticket_depertments as td")->beSelect("td.tdid,tdname")->beWhere("tdt.lid",$user["lid"])->beJoin("INNER JOIN be_ticket_depertment_translations as tdt ON tdt.tdid = td.tdid")->beGetAll();
        $userproducts = UserProductModel::beSelect("upid,upname,uptag")->beWhere("uid",$user["uid"])->beWhere("upstatus","-1","!=")->beGetAll();
        beSetHeaderContent("",1);
        $ticket_user_files = SettingModel::beGetSettings("ticket_user_files")["ticket_user_files"];
        return beGetView("clientarea.ticket.add",["depertments" => $depertments,"userproducts" => $userproducts,"ticket_user_files" => $ticket_user_files]);
    }
    public function newticket_post(){
        $user = Auth::beGetUser();
        beLanguage::beReadLang("ticket");
        beLanguage::beReadLang("form");
        $subject = htmlspecialchars($_POST["subject"]);
        $tdid = (int)$_POST["depertment"];
        $upid = (int)$_POST["userproduct"];
        $message = strip_tags($_POST["message"],"<p><a><br><b><em><span><sup><code><h2><h3><h4><h5>");
        $userinfo = UserInfoModel::beSelect("uisettings")->beWhere("uid",$user["uid"])->beGet();
        $uisettings = json_decode($userinfo["uisettings"],true);
        if($uisettings["ticket_create"] == 0){
            return beAjaxError(["message" => beGetLang("ticket_create_permission_denied")]);
        }
        if($uisettings["ticket_onlyone"] == 1){
            $ticket_count = TicketModel::beSelect("COUNT(tid) as total")->beWhere("uid",$user["uid"])->beWhere("tstatus","active")->beGet()["total"];
            if($ticket_count == 1){
                return beAjaxError(["message" => beGetLang("ticket_create_only_one")]);
            }
        }
        if(empty($subject) || empty($message)){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        if(strlen($subject) > 128){
            return beAjaxError(["message" => beGetLang("ticket_subject_long_length",["length" => 128])]);
        }
        if(strlen($subject) < 8){
            return beAjaxError(["message" => beGetLang("ticket_subject_short_length",["length" => 8])]);
        }
        if(strlen($message) > 4096){
            return beAjaxError(["message" => beGetLang("ticket_message_long_length",["length" => 4096])]);
        }
        if(strlen($message) < 8){
            return beAjaxError(["message" => beGetLang("ticket_message_short_length",["length" => 8])]);
        }
        $depertment = TicketDepertmentModel::beSelect("tdid,tdadmins")->beWhere("tdid",$tdid)->beGet();
        if(!$depertment){
            return beAjaxError(["message" => beGetLang("ticket_depertment_not_found")]);
        }
        if($upid){
            $order = UserProductModel::beSelect("upid")->beWhere("upid",$upid)->beWhere("uid",$user["uid"])->beWhere("upstatus","-1","!=")->beGet();
            if(!$order){
                return beAjaxError(["message" => "Belirtilen sipariş bulunamadı!"]);
            }
        }
        $files = [];
        $ticket_user_files = SettingModel::beGetSettings("ticket_user_files")["ticket_user_files"];
        if($ticket_user_files && $uisettings["ticket_files"]){
            $aidlist = $_POST["aidlist"];
            foreach($aidlist as $aid){
                $attachment = AttachmentModel::beSelect("aid")->beWhere("aid",(int)$aid)->beWhere("uid",$user["uid"])->beGet();
                if($attachment){
                    $files[] = (int)$attachment["aid"];
                }
            }
        }
        $tid = beTicket::beInsertTicket([
            "uid" => $user["uid"],
            "upid" => $upid,
            "subject" => $subject,
            "status" => "active",
            "lastreply" => "user",
            "depertment" => $depertment["tdid"],
            "ipaddress" => beRouter::$beUserIP,
            "dateline" => BE_TIME
        ])["tid"];
        beTicket::beTicketPost([
            "tid" => $tid,
            "uid" => $user["uid"],
            "message" => $message,
            "files" => json_encode($files,JSON_UNESCAPED_UNICODE),
            "ipaddress" => beRouter::$beUserIP,
            "dateline" => BE_TIME
        ]);
        $tdadmins = json_decode($depertment["tdadmins"],true);
        if($tdadmins){
            $userinfos = UserInfoModel::beSelect("uid,uisettings")->beWhere("uid",$tdadmins,"IN")->beGetAll();
            foreach($userinfos as $userinfo){
                $uisettings = json_decode($userinfo["uisettings"],true);
                $ticketlink = beGetRoute("admin.ticket.show",["tid" => $tid]);
                $messages = MessageTemplateModel::beGetMessages("ticket_created_admin",1)["ticket_created_admin"];
                if($messages["alert"] && $uisettings["notification_alert"]){
                    $message = str_replace(["{ticketname}","{username}","{ticketlink}"],[$subject,$user["name"]." ".$user["surname"],$ticketlink],$messages["alert"]["mttmessage"]);
                    beAlert::beCreateAlert(json_encode(["message" => $message],JSON_UNESCAPED_UNICODE),$ticketlink,$userinfo["uid"]);
                }
                if($messages["sms"] && $uisettings["sms_alert"]){
                    $message = str_replace(["{ticketname}","{username}","{ticketlink}"],[$subject,$user["name"]." ".$user["surname"],$ticketlink],$messages["sms"]["mttmessage"]);
                    beSms::beCreateSms($message,1,$userinfo["uid"]);
                }
                if($messages["mail"] && $uisettings["mail_alert"]){
                    $message = str_replace(["{ticketname}","{username}","{ticketlink}"],[$subject,$user["name"]." ".$user["surname"],$ticketlink],$messages["mail"]["mttmessage"]);
                    beMail::beCreateMail($messages["mail"]["mttsubject"],$message,2,1,$userinfo["uid"]);
                }
            }
        }
        return beAjaxSuccess(["message" => beGetLang("ticket_created"),"url" => beGetRoute("client.ticket.ticket",["tid" => $tid])]);
    }
}
?>