<?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\LanguageModel;
use App\System\Model\MessageTemplateModel;
use App\System\Model\MessageTemplatesModel;
use App\System\Model\ReferralModel;
use App\System\Model\SettingModel;
use App\System\Model\UserInfoModel;
use App\System\Model\UserLogModel;
use App\System\Vendor\Auth;
use App\System\Vendor\Basic\beCookie;
use App\System\Vendor\beLanguage;
use App\System\Vendor\beMail;
use App\System\Vendor\bePlugin;
use App\System\Vendor\beSms;

class AuthController extends beContoller {
    public function login_post(){
        beLanguage::beReadLang("auth");
        beLanguage::beReadLang("form");
        bePlugin::beRunHook("auth_user_login");
        $email = $_POST["email"];
        $password = $_POST["password"];
        if(empty($email) || empty($password)){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        $remember = isset($_POST["rememberme"]) ? true:false;
        $login = Auth::beLoginUser($email,$password,$remember);
        if(!$login["status"]){
            return beAjaxError(["message" => $login["message"]]);
        }
        UserLogModel::beInsert([
            "uid" => $login["uid"],
            "ltype" => "login",
            "lipaddress" => beRouter::$beUserIP,
            "ldata" => "",
            "ldateline" => BE_TIME
        ]);
        $url = beGetConfig("siteurl");
        $reredirect = beCookie::beGetCookie("be_reredirect");
        if($reredirect){
            $url = urldecode($reredirect);
        }
        $user = Auth::beGetUser($login["uid"],"lid");
        $language = LanguageModel::beGetLanguages("lid,lcode",$user["lid"]);
        beCookie::beCreateCookie("be_lang",$language["lcode"],true,true);
        $user = bePlugin::beRunHook("auth_user_logged",$user);
        return beAjaxSuccess(["message" => beGetLang("user_logged"),"url" => $url]);
    }
    public function register_post(){
        global $be;
        beLanguage::beReadLang("auth");
        beLanguage::beReadLang("address");
        beLanguage::beReadLang("form");
        bePlugin::beRunHook("auth_user_register");
        if(isset($_POST["agreement"]) && $_POST["agreement"] != "1"){
            return beAjaxError(["message" => beGetLang("user_agreement")]);
        }
        $name = htmlspecialchars($_POST["name"]);
        $surname = htmlspecialchars($_POST["surname"]);
        if(preg_match("/ /",$surname)){
            return beAjaxError(["message" => beGetLang("surname_space")]);
        }
        $email = htmlspecialchars($_POST["email"]);
        $password1 = $_POST["password1"];
        $password2 = $_POST["password2"];
        $district = htmlspecialchars($_POST["district"]);
        $province = htmlspecialchars($_POST["province"]);
        $address = htmlspecialchars($_POST["address"]);
        $phone = str_replace([" ","(",")","-"],"",$_POST["phone"]);
        if(substr($phone,0,1) == "0"){
            return beAjaxError(["message" => beGetLang("invalid_phone_number")]);
        }
        if(strlen($phone) != 10){
            return beAjaxError(["message" => beGetLang("incorrect_phone_number")]);
        }
        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")]);
        }
        $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])]);
        }
        $userinfo = UserInfoModel::beSelect("uid")->beWhere("uiphone",$phone)->beGet();
        if($userinfo){
            return beAjaxError(["message" => beGetLang("phone_number_using")]);
        }
        $acid = (int)$_POST["country"];
        $country = beModel::beTable("be_address_country")->beSelect("acid",$acid)->beGet();
        if(!$country){
            return beAjaxError(["message" => beGetLang("country_not_found")]);
        }
        $usersettings = [
            "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
        ];
        if($_POST["invoiceinfo"] == "1"){
            $usersettings["invoiceinfo"] = 1;
        }
        else{
            $usersettings["invoiceinfo"] = 0;
        }
        if($_POST["productinfo"] == "1"){
            $usersettings["productinfo"] = 1;
        }
        else{
            $_POST["productinfo"] = 0;
        }
        if(empty($name) || empty($surname) || empty($email) || empty($password1) || empty($password2) || empty($district) || empty($province)){
            return beAjaxError(["message" => beGetLang("form_not_full")]);
        }
        if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
            return beAjaxError(["message" => beGetLang("not_email")]);
        }
        if(strlen($password1) < 5){
            return beAjaxError(["message" => beGetLang("password_not_enough")]);
        }
        if($password1 != $password2){
            return beAjaxError(["message" => beGetLang("not_equals")]);
        }
        $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" => $password1,"extradata" => ["lid" => $be->settings["system_language"],"cid" => $be->settings["system_currency"],"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($usersettings,JSON_UNESCAPED_UNICODE)
        ]);
        $refcookie = beCookie::beGetCookie("be_refcode");
        if($refcookie){
            list($refcode,$refuid) = explode("_",beCookie::beGetCookie("be_refcode"));
            $refuser = Auth::beGetUser($refuid,"uid,salt");
            if($refcode == substr($refuser["salt"],8)){
                ReferralModel::beInsert([
                    "uid" => $user["uid"],
                    "rfuid" => $refuser["uid"],
                    "rftype" => "1",
                    "rfstatus" => "1",
                    "rfdateline" => BE_TIME
                ]);
            }
        }
        beCookie::beCreateCookie("be_user",$user["uid"]."_".$user["loginkey"],true,true);
        $user = bePlugin::beRunHook("auth_user_registered",$user);
        return beAjaxSuccess(["message" => beGetLang("user_registered"),"url" => beGetConfig("siteurl")]);
    }
    public function forgetpassword_post(){
        beLanguage::beReadLang("user");
        beLanguage::beReadLang("auth");
        beLanguage::beReadLang("form");
        $action = $_POST["action"];
        switch($action){
            case "reset_password":
                $userdata = $_POST["userdata"];
                if(empty($userdata)){
                    return beAjaxError(["message" => beGetLang("form_not_full")]);		
                }
                if(strpos($userdata,"@") !== false){
                    $email = $userdata;
                }
                else{
                    $phone = $userdata;
                }
                if($phone){
                    $userinfo = UserInfoModel::beSelect("uid")->beWhere("uiphone",$phone)->beGet();
                    if(!$userinfo){
                        return beAjaxError(["message" => beGetLang("user_not_found")]);
                    }
                    $user = AuthModel::beSelect("uid,lid,name,surname")->beWhere("uid",$userinfo["uid"])->beGet();
                    if(!$user){
                        return beAjaxError(["message" => beGetLang("user_not_found")]);
                    }
                    bePlugin::beRunHook("auth_reset_password_pre",["user" => $user,"type" => "phone"]);
                    $uid = $user["uid"];
                    $lastverification = beModel::beTable("be_verifications")->beSelect("vid,vdateline")->beWhere("uid",$uid)->beWhere("vtype","1")->beOrder("vid","DESC")->beLimit(1)->beGet();
                    if($lastverification){
                        if(BE_TIME < $lastverification["vdateline"]+120){
                            $minute = round((($lastverification["vdateline"]+120)-BE_TIME)/60);
                            return beAjaxError(["message" => beGetLang("auth_reset_password_waiting_time",["minute" => $minute])]);
                        }
                    }
                    $verifycode = substr(md5($uid.BE_TIME),0,16);
                    $vid = beModel::beInsert([
                        "uid" => $uid,
                        "vcode" => $verifycode,
                        "vtype" => "1",
                        "vstatus" => "1",
                        "vdateline" => BE_TIME
                    ],"be_verifications");
                    $randnumber = rand(1,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
                    beModel::beInsert([
                        "uid" => $uid,
                        "sccode" => $randnumber,
                        "scdata" => json_encode([
                            "vid" => $vid
                        ]),
                        "scstatus" => "0",
                        "sctype" => "1",
                        "scdateline" => BE_TIME
                    ],"be_smscodes");
                    $messages = MessageTemplateModel::beGetMessages("password_reset",$user["lid"])["password_reset"];
                    if(!$messages["sms"]){
                        return beAjaxError(["message" => beGetLang("auth_reset_password_closed_sms")]);
                    }
                    $message = str_replace(["{sitename}","{namesurname}","{code}"],[beGetConfig("sitename"),$user["name"]." ".$user["surname"],$randnumber],$messages["sms"]["mttmessage"]);
                    beSms::beCreateSms($message,2,$user["uid"]);
                    return beAjaxSuccess(["message" => beGetLang("auth_reset_password_send_sms"),"type" => 1]);
                }
                else{
                    $user = AuthModel::beSelect("uid,lid,name,surname")->beWhere("email",$email)->beGet();
                    if(!$user){
                        return beAjaxError(["message" => beGetLang("user_not_found")]);
                    }
                    bePlugin::beRunHook("auth_reset_password_pre",["user" => $user,"type" => "email"]);
                    $uid = $user["uid"];
                    $lastverification = beModel::beTable("be_verifications")->beSelect("vid,vdateline")->beWhere("uid",$uid)->beWhere("vtype","1")->beOrder("vid","DESC")->beLimit(1)->beGet();
                    if($lastverification){
                        if(BE_TIME < $lastverification["vdateline"]+120){
                            $minute = round((($lastverification["vdateline"]+120)-BE_TIME)/60);
                            return beAjaxError(["message" => beGetLang("auth_reset_password_waiting_time",["minute" => $minute])]);
                        }
                    }
                    $verifycode = substr(md5($uid.BE_TIME),0,16);
                    beModel::beInsert([
                        "uid" => $uid,
                        "vcode" => $verifycode,
                        "vtype" => "1",
                        "vstatus" => "1",
                        "vdateline" => BE_TIME
                    ],"be_verifications");
                    $reseturl = beGetRoute("auth.changepassword",["code" => $verifycode]);
                    $messages = MessageTemplateModel::beGetMessages("password_reset",$user["lid"])["password_reset"];
                    if(!$messages["mail"]){
                        return beAjaxError(["message" => beGetLang("auth_reset_password_closed_mail")]);
                    }
                    $message = str_replace(["{sitename}","{namesurname}","{reseturl}"],[beGetConfig("sitename"),$user["name"]." ".$user["surname"],$reseturl],$messages["mail"]["mttmessage"]);
                    beMail::beCreateMail($messages["mail"]["mttsubject"],$message,1,1,$user["uid"]);
                    return beAjaxSuccess(["message" => beGetLang("auth_reset_password_send_mail"),"type" => 2,"url" => beGetConfig("siteurl")]);
                }
                break;
            case "code_approve" :
                $code = $_POST["code"];
                if(empty($code)){
                    return beAjaxError(["message" => "SMS doğrulaması için tüm alanları doldurmanız gerekiyor"]);    
                }
                $smscode = beModel::beTable("be_smscodes")->beSelect("scid,scdata,scdateline")->beWhere("sccode",$code)->beWhere("sctype","1")->beGet();
                if(!$smscode){
                    return beAjaxError(["message" => "SMS doğrulama kodunu yanlış girdiniz lütfen tekrar kontrol edin"]);    
                }    
                if(BE_TIME > $smscode["scdateline"]+120){
                    return beAjaxError(["message" => "Kodun geçerlilik süresi doldu lütfen işlemleri tekrar ediniz"]);    
                }
                $scdata = json_decode($smscode["scdata"],true);
                $verification = beModel::beTable("be_verifications")->beSelect("vcode")->beWhere("vid",$scdata["vid"])->beGet();
                $vcode = $verification["vcode"];
                beModel::beUpdate(["scstatus" => "1"],"be_smscodes")->beWhere("scid",$smscode["scid"])->beExecute();
                return beAjaxSuccess(["message" => "Başarılı bir şekilde şifre sıfırlama sayfasına yönlendiriliyorsunuz!","url" => beGetRoute("auth.changepassword",["code" => $vcode])]);
                break;
        }
    }
    public function changepassword($code){
        beSetHeaderContent();
        $verification = beModel::beTable("be_verifications")->beSelect("vcode,vtype,vstatus,vdateline")->beWhere("vcode",$code)->beWhere("vtype","1")->beGet();
        if(!$verification){
            beError("Bilinmeyen Kod","Belirtilen koda ait bir işlem bulunmamaktadır!");
		}
		if($verification["vstatus"] == 0){
            beError("Geçersiz Kod","Belirtilen kod sizden önce kullanılmış!");
		}
		if(BE_TIME > $verification["vdateline"]+360){
            beError("Zaman Aşımı","Belirtilen kodun kullanımı için verilen süreyi aştınız!");
		}
        return beGetView("auth.changepassword",["verification" => $verification]);
    }
    public function changepassword_post(){
        $code = $_POST["code"];
        if(empty($code)){
            return beAjaxError(["message" => "Sıfırlama için tüm alanları doldurmanız gerekiyor"]);    
        }
        $verification = beModel::beTable("be_verifications")->beSelect("vid,uid,vstatus,vdateline")->beWhere("vcode",$code)->beWhere("vtype","1")->beGet();
        if(!$verification){
            return beAjaxError(["message" => "Belirtilen koda ait bir işlem bulunmamaktadır!"]);    
		}
        if($verification["vstatus"] == 0){
            return beAjaxError(["message" => "Belirtilen kod sizden önce kullanılmış!"]);  
        }
        if(BE_TIME > $verification["vdateline"]+360){
            return beAjaxError(["message" => "Belirtilen kodun kullanımı için verilen süreyi aştınız!"]);  
        }
        $password1 = $_POST["password1"];
        $password2 = $_POST["password2"];
        if($password1 != $password2){
            return beAjaxError(["message" => "Belirtilen şifreler birbirleri ile uyuşmuyor!"]);  
        }
        $password_length = strlen($password1);
        if($password_length < 5){
            return beAjaxError(["message" => "Şifreniz minimum karakter sayısı olan 5 dan daha kısa!"]);
        }
        if($password_length > 30){
            return beAjaxError(["message" => "Şifreniz maximum karakter sayısı olan 30 dan daha uzun!"]);			
        }
        $response = Auth::beUpdatePassword($verification["uid"],$password1);
        if(!$response["status"]){
            return beAjaxError(["message" => $response["message"]]);  
        }
        beModel::beUpdate(["vstatus" => "0"],"be_verifications")->beWhere("vid",$verification["vid"])->beExecute();
        return beAjaxSuccess(["message" => "Başarılı bir şekilde şifreniz değiştirildi!","url" => beGetConfig("siteurl")]);
    }
    public function logout(){
        Auth::beLogOut();
        beRouter::beRedirect(beGetConfig("siteurl"));
    }
}

?>