<?php

namespace App\System\Controller;
use App\System\Basic\beContoller;
use App\System\Basic\beModel;
use App\System\Basic\beRouter;
use App\System\Model\AlertModel;
use App\System\Model\AuthModel;
use App\System\Model\CurrencyModel;
use App\System\Model\TicketModel;
use App\System\Model\UserProductModel;
use App\System\Model\InvoiceModel;
use App\System\Model\LanguageModel;
use App\System\Model\UserInfoModel;
use App\System\Vendor\Auth;
use App\System\Vendor\Basic\beCookie;
use App\System\Vendor\beLanguage;
use App\System\Vendor\bePlugin;

class ClientController extends beContoller {
    public function dashboard(){
        beLanguage::beReadLang("clientarea");
        beLanguage::beReadLang("order");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        $user = Auth::beGetUser();
        $userinfo = UserInfoModel::beWhere("uid",$user["uid"])->beGet();
        $userinfo["uisettings"] = json_decode($userinfo["uisettings"],true);
        $product_count = UserProductModel::beSelect("COUNT(upid) as total")->beWhere("uid",$user["uid"])->beWhere("upstatus","-1","!=")->beGet()["total"];
        $ticket_count = TicketModel::beSelect("COUNT(tid) as total")->beWhere("uid",$user["uid"])->beWhere("tstatus","active")->beGet()["total"];
        $invoice_count = InvoiceModel::beSelect("COUNT(iid) as total")->beWhere("uid",$user["uid"])->beWhere("istatus","0")->beGet()["total"];
        $currency = [];
        $currencies = CurrencyModel::beGetCurrencies("cid,cname,cicon");
        foreach($currencies as $usercurrency){
            if($usercurrency["cid"] == $user["cid"]){
                $currency = $usercurrency;
            }
        }
        $cart = new CartController();
        $userproductstatus = UserProductModel::beGetUserProductStatus();
        $userproducts = UserProductModel::beSelect("pt.pname,be_user_products.*")->beWhere("uid",$user["uid"])->beWhere("lid",$user["lid"])->beWhere("upstatus","-1","!=")->beJoin("INNER JOIN be_product_translations as pt ON pt.pid = be_user_products.pid")->beGetAll();
        foreach($userproducts as $key => $userproduct){
            $endtime = $userproduct["upetime"];
            if($endtime){
                $userproducts[$key]["enddate"] = beDisplayTime($endtime);
                $day = round(($endtime-BE_TIME)/86400);
                if($endtime > BE_TIME){
                    $userproducts[$key]["endtext"] = beGetLang("order_days_left",["day" => $day]);
                    $userproducts[$key]["endclass"] = "text-success";
                }   
                else{
                    $day *= -1;
                    $userproducts[$key]["endtext"] = beGetLang("order_days_passed",["day" => $day]);
                    $userproducts[$key]["endclass"] = "text-danger";
                }
            }   
            else{
                $userproducts[$key]["endtext"] = "∞";
                $userproducts[$key]["enddate"] = "∞";
                $userproducts[$key]["upprice"] = "∞";
            }
            $extension = $cart->calculate_extension_nextprice($userproduct["upid"]);
            if($extension["status"]){
                $userproducts[$key]["upprice"] += $extension["price"];
            }
        }
        $tickets = TicketModel::beSelect("tid,tsubject")->beWhere("uid",$user["uid"])->beWhere("tstatus","closed","!=")->beOrder("tid","DESC")->beLimit(3)->beGetAll();
        $invoicestatus = InvoiceModel::beGetInvoiceStatus();
        $invoices = InvoiceModel::beSelect("iid,cid,iname,idescription,istatus,iprice,iexpiredate")->beWhere("uid",$user["uid"])->beWhere("istatus","0")->beGetAll();
        $contentup = beGetView("clientarea.headercontent",["user" => $user,"userinfo" => $userinfo,"currency" => $currency,"ticket_count" => $ticket_count,"product_count" => $product_count,"invoice_count" => $invoice_count]);
        beSetHeaderContent($contentup);
        return beGetView("clientarea.dashboard",["user" => $user,"userinfo" => $userinfo,"currency" => $currency,"currencies" => $currencies,"ticket_count" => $ticket_count,"product_count" => $product_count,"invoice_count" => $invoice_count,"userproducts" => $userproducts,"userproductstatus" => $userproductstatus,"tickets" => $tickets,"invoices" => $invoices,"invoicestatus" => $invoicestatus]);
    }
    public function banks(){
        beLanguage::beReadLang("clientarea");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_banks"));
        beSetHeaderContent("",1);
        $banks = beModel::beTable("be_banks")->beGetAll();
        return beGetView("clientarea.banks",["banks" => $banks]);
    }
    public function settings(){
        beLanguage::beReadLang("clientarea");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_user_settings"));
        $data["user"] = Auth::beGetUser();
        $data["userinfo"] = UserInfoModel::beSelect("uidial,uiphone,uiaddress")->beWhere("uid",$data["user"]["uid"])->beGet();
        $data["languages"] = LanguageModel::beGetLanguages("lid,lname");
        $data = bePlugin::beRunHook("clientarea_usersettings_start",$data);
        beSetHeaderContent("",1);
        return beGetView("clientarea.user.settings",$data);
    }
    public function userinfo(){
        beLanguage::beReadLang("clientarea");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_user_info"));
        $data["user"] = Auth::beGetUser();
        $data["userinfo"] = UserInfoModel::beSelect("uidial,uiphone,uiaddress")->beWhere("uid",$data["user"]["uid"])->beGet();
        $data = bePlugin::beRunHook("clientarea_userinfo_start",$data);
        beSetHeaderContent("",1);
        return beGetView("clientarea.user.userinfo",$data);
    }
    public function address_post(){
        beLanguage::beReadLang("auth");
        beLanguage::beReadLang("clientarea");
        $user = Auth::beGetUser();
        $address = htmlspecialchars($_POST["address"]);
        $addresslength = strlen($address);
        if($addresslength < 8){
            return beAjaxError(["message" => beGetLang("address_min_length",["minlength" => 8])]);
        }
        if($addresslength > 256){
            return beAjaxError(["message" => beGetLang("address_max_length",["maxlength" => 256])]);
        }
        UserInfoModel::beUpdate([
            "uiaddress" => $address
        ])->beWhere("uid",$user["uid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("clientarea_settings_updated")]);
    }
    public function systemsettings(){
        beLanguage::beReadLang("clientarea");
        NavController::beAddBreadcumb(beGetLang("clientarea"),beGetRoute("client.dashboard.alternative"));
        NavController::beAddBreadcumb(beGetLang("clientarea_nav_notification_settings"));
        $user = Auth::beGetUser();
        $userinfo = UserInfoModel::beSelect("uisettings")->beWhere("uid",$user["uid"])->beGet();
        $userinfo["uisettings"] = json_decode($userinfo["uisettings"],true);
        beSetHeaderContent("",1);
        return beGetView("clientarea.user.systemsettings",["userinfo" => $userinfo]);
    }
    public function systemsettings_post(){
        beLanguage::beReadLang("clientarea");
        $user = Auth::beGetUser();
        $userinfo = UserInfoModel::beSelect("uisettings")->beWhere("uid",$user["uid"])->beGet();
        $userinfo["uisettings"] = json_decode($userinfo["uisettings"],true);
        $userinfo["uisettings"]["sms_alert"] = (int)$_POST["uisms"] == 1 ? 1:0;
        $userinfo["uisettings"]["mail_alert"] = (int)$_POST["uiemial"] == 1 ? 1:0;
        $userinfo["uisettings"]["notification_alert"] = (int)$_POST["uialert"] == 1 ? 1:0;
        $userinfo["uisettings"]["order_auto_pay"] = (int)$_POST["uiautopay"] == 1 ? 1:0;
        UserInfoModel::beUpdate(["uisettings" => json_encode($userinfo["uisettings"])])->beWhere("uid",$user["uid"])->beExecute();
        return beAjaxSuccess(["message" => beGetLang("clientarea_settings_updated")]);
    }
    public function alert($aid){
        $user = Auth::beGetUser();
        $alert = AlertModel::beTable("be_alerts")->beSelect("aid,alink")->beWhere("aid",$aid)->beWhere("uid",$user["uid"])->beGet();
        AlertModel::beUpdate([
            "astatus" => "1",
            "areadtime" => BE_TIME
        ],"be_alerts")->beWhere("aid",$alert["aid"])->beExecute();
        beRouter::beRedirect($alert["alink"]);
    }
    public function setlanguage_post(){
        beLanguage::beReadLang("language");
        $user = Auth::beGetUser();
        $lid = (int)$_POST["language"];
        $language = LanguageModel::beGetLanguages("lid,lcode",$lid);
        if(!$language){
            return beAjaxError(["message" => beGetLang("langauge_not_found")]);
        }
        AuthModel::beUpdate(["lid" => $language["lid"]])->beWhere("uid",$user["uid"])->beExecute();
        beCookie::beCreateCookie("be_lang",$language["lcode"],true,true);
        return beAjaxSuccess(["message" => beGetLang("language_user_updated")]);
    }
    public function password_post(){
        beLanguage::beReadLang("auth");
        $user = Auth::beGetUser();
        $oldpassword = $_POST["oldpassword"];
        $response = Auth::beCheckPassword($user["salt"],$oldpassword,$user["password"]);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);
        }
        $password1 = $_POST["password1"];
        $password2 = $_POST["password2"];
        if($password1 != $password2){
            return beAjaxError(["message" => beGetLang("password_not_match")]);  
        }
        $password_length = strlen($password1);
        if($password_length < 5){
            return beAjaxError(["message" => beGetLang("password_min_length",["minlength" => 5])]);
        }
        if($password_length > 20){
            return beAjaxError(["message" =>beGetLang("password_max_length",["maxlength" => 20])]);			
        }
        $response = Auth::beUpdatePassword($user["uid"],$password1);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);  
        }
        return beAjaxSuccess(["message" => beGetLang("password_changed")]);
    }
}

?>