<?php


namespace App\Http\Controllers\Api;


use App\dao\SendCode\WebRegister;
use App\Facade\TableName;
use App\Game\GlobalUserInfo;
use App\Http\logic\api\SendCodeLogic;
use App\Models\AccountsInfo;
use App\Services\IpCheck;
use App\Services\SendCode;
use App\Util;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class SendCodeController
{
    protected $CodeType = [1 => 3, 3 => 1];

    public function send2(Request $request){
        return $this->send($request);
    }
    // 天一宏+Kmi 短信发送
    public function send(Request $request)
    {

        $phone = $request->Phone ?: '';
        $UserID = $request->UserID ?: 0;
        $Type = $request->Type ?: 0;    // 标识 1找回密码
        $ip = $request->ip();

        $language = GlobalUserInfo::getLocaleByUserID( $UserID,'en');
        \App::setLocale($language);

        try {
            $pack=$request->PackageName??"com.ouro777.newplay";
            $v=$request->v??1;
            $service = new IpCheck();
            if(!$service->ipCheck($ip,$pack,$v)){
                return apiReturnFail(__('messages.send_code.too_many_sms'));
            }

        }catch (\Exception $e){

        }

        $WebRegister = $request->WebRegister ?: 0;
        // 并发限制
        $res = Redis::setnx('SendCodeController' . $UserID, 1);
        if (!$res) {
            return apiReturnFail(__('messages.send_code.too_many_sms'));
        }
        Redis::expire('SendCodeController' . $UserID, 30);



        // 并发限制
        $res = Redis::setnx('SendCodeController' . $phone, 1);
        if (!$res) {
            return apiReturnFail(__('messages.send_code.too_many_sms'));
        }
        Redis::expire('SendCodeController' . $phone, 30);


        Log::info('接收客户端发送验证码手机号：'.$phone.' Type类型：'.$Type.' 用户ID：'.$UserID.' WebRegister：'.$WebRegister);
        $SendCodeConfig = DB::connection('read')->table('QPAccountsDB.dbo.SysSmsConfig')
            ->where('Status', 1)
            ->get();

        //默认
        $SendCodeConfigType = rand(0,100)>50?3:1;

        $user=AccountsInfo::where("UserID",$UserID)->select('Channel','BindCountry')->first();
        if(!$user){
            return apiReturnFail(['web.error.user_not_exist','Wrong UserID!']);
        }
        $Channel=$user->Channel;
//        $isMultiCountry=env('MULTI_COUNTRY',0)==1;

        //给电话号码加区号
        $CountryCode=env('COUNTRY_CODE','52');
        if(strstr($CountryCode,','))$CountryCode=IpCheck::$countries[$user->BindCountry]['phone_code']??env('COUNTRY_CODE','52');
        Log::info($CountryCode.'|'.$user->BindCountry);
        //用了配置的多区域区号带逗号来分割
        if(strlen($CountryCode)>3)$CountryCode=explode(',',$CountryCode)[0];


        //巴基斯坦判断
        if($user->BindCountry=='PK'||$CountryCode==92){
            // 移除所有非数字字符
            $phone = preg_replace('/[^0-9]/', '', $phone);

            // 检查是否以92开头（国际格式）
            if (strpos($phone, '92') === 0) {
                $phone = substr($phone, 2);
            }

            // 检查是否以0开头（本地格式）
            if (strpos($phone, '0') === 0) {
                $phone = substr($phone, 1);
            }

            // 检查号码是否为10位且以3开头
            if (strlen($phone) === 10 && strpos($phone, '3') === 0) {

            }else{
                return apiReturnFail(__('messages.send_code.invalid_phone_number'));
            }
        }
        //巴基斯坦判断
        if($user->BindCountry=='BD'||$CountryCode==880){
            // 移除所有非数字字符
            $phone = preg_replace('/[^0-9]/', '', $phone);

            // 检查是否以92开头（国际格式）
            if (strpos($phone, '880') === 0) {
                $phone = substr($phone, 3);
            }

            // 检查是否以0开头（本地格式）
            if (strpos($phone, '01') === 0) {
                $phone = substr($phone, 1);
            }

            // 检查号码是否为10位且以3开头
            if (strlen($phone) == 10 && strpos($phone, '1') === 0) {
                Log::info('now：'.$phone);
            }else{
                return apiReturnFail(__('messages.send_code.invalid_phone_number'));
            }
        }

        //检查电话长度
        $lenSize=IpCheck::$countries[$user->BindCountry]['phone_length']??env("PHONE_LENGTH","7,10");
        $lenSize=explode(",",$lenSize);
        $len=strlen($phone);
        if ($len <intval($lenSize[0]) || $len > intval($lenSize[1]??$lenSize[0])) {
            Log::info('手机长度问题 ' . $len);
            return apiReturnFail(__('messages.send_code.len_fail', ['len' => $len]));
        }

            //电话补齐
        $phone=$CountryCode.$phone;
        Log::info('now：'.$phone);

        if ($SendCodeConfig->count() > 1) {
            if (Redis::exists($phone."_".$Channel)) {
                $currentCodeType = (int)Redis::get($phone."_".$Channel);
                if($currentCodeType==100){
                    //两个通道都发了，不能再发了
                    return apiReturnFail(__('messages.send_code.invalid_phone_number'));
                }
                $SendCodeConfigType = $this->CodeType[$currentCodeType];
//                Redis::set($phone."_".$Channel, $this->CodeType[$currentCodeType]);
                Redis::set($phone."_".$Channel, 100);
                Redis::expire($phone."_".$Channel, 3600);
                Log::info('补发验证码通道：'.$SendCodeConfigType);
                Util::WriteLog('phone_error',$phone);
            } else {
                // 默认 codeType 1 天一泓短信
                // 默认 codeType 3 plants
                Redis::set($phone."_".$Channel, $SendCodeConfigType);
                Redis::expire($phone."_".$Channel, 3600);
            }
        } else {
            $SendCodeConfigType = (int)$SendCodeConfig->where('Status', 1)->first()->Type ?? 1;
        }


        Log::info('发送验证码渠道：'.$SendCodeConfigType);
        $logic = new SendCodeLogic();
        if ($logic->sendVerify(trim($phone), $ip, $Type) === false) {
            return apiReturnFail($logic->getError());
        }

        Log::info('验证手机号通过'.$phone);


        $lang = [
            // European Languages
            'en' => 'Hello, {{code}} (OTP) for your mobile verification', // English
            'pt' => 'Olá, {{code}} (OTP) para sua verificação de celular', // Portuguese
            'es' => 'Hola, {{code}} (OTP) para tu verificación móvil', // Spanish
            'de' => 'Hallo, {{code}} (OTP) für Ihre mobile Verifizierung', // German
            'fr' => 'Bonjour, {{code}} (OTP) pour votre vérification mobile', // French
            'it' => 'Ciao, {{code}} (OTP) per la tua verifica mobile', // Italian
            'nl' => 'Hallo, {{code}} (OTP) voor uw mobiele verificatie', // Dutch
            'sv' => 'Hej, {{code}} (OTP) för din mobilverifiering', // Swedish
            'no' => 'Hei, {{code}} (OTP) for din mobilbekreftelse', // Norwegian
            'fi' => 'Hei, {{code}} (OTP) mobiilitodennukseesi', // Finnish
            'da' => 'Hej, {{code}} (OTP) til din mobile verifikation', // Danish
            'pl' => 'Cześć, {{code}} (OTP) do weryfikacji twojego telefonu komórkowego', // Polish
            'cs' => 'Ahoj, {{code}} (OTP) pro ověření vašeho mobilního zařízení', // Czech
            'hu' => 'Szia, {{code}} (OTP) a mobil ellenőrzéséhez', // Hungarian
            'ro' => 'Salut, {{code}} (OTP) pentru verificarea mobilului tău', // Romanian
            'tr' => 'Merhaba, mobil doğrulamanız için {{code}} (OTP)', // Turkish
            'el' => 'Γειά, {{code}} (OTP) για την επιβεβαίωση του κινητού σας', // Greek
            'uk' => 'Привіт, {{code}} (OTP) для підтвердження вашого мобільного телефону', // Ukrainian

            // Asian Languages
            'zh' => '您好，您的手机验证验证码是 {{code}} (OTP)', // Chinese (Simplified)
            'ja' => 'こんにちは、{{code}} (OTP) はあなたの携帯認証用です', // Japanese
            'ko' => '안녕하세요, 모바일 인증을 위한 {{code}} (OTP)입니다', // Korean
            'ar' => 'مرحباً، {{code}} (OTP) للتحقق من هاتفك المحمول', // Arabic
            'hi' => 'नमस्ते, आपके मोबाइल सत्यापन के लिए {{code}} (OTP)', // Hindi
            'bn' => 'হ্যালো, আপনার মোবাইল যাচাইয়ের জন্য {{code}} (OTP)', // Bengali
            'th' => 'สวัสดี, รหัส {{code}} (OTP) สำหรับการยืนยันมือถือของคุณ', // Thai
            'vi' => 'Xin chào, {{code}} (OTP) cho việc xác minh điện thoại di động của bạn', // Vietnamese
            'id' => 'Halo, {{code}} (OTP) untuk verifikasi ponsel Anda', // Indonesian
            'ms' => 'Halo, {{code}} (OTP) untuk pengesahan telefon bimbit anda', // Malay
            'tl' => 'Kumusta, ang {{code}} (OTP) para sa iyong mobile na beripikasyon', // Tagalog
            'fa' => 'سلام، {{code}} (OTP) برای تأیید موبایل شما', // Persian
            'ur' => 'ہیلو، آپ کے موبائل تصدیق کے لیے {{code}} (OTP)', // Urdu
            'ta' => 'வணக்கம், உங்கள் மொபைல் சரிபார்ப்புக்கு {{code}} (OTP)', // Tamil
            'te' => '{{code}} (OTP) మీ మొబైల్ ధృవీకరణ కోసం', // Telugu
            'mr' => 'नमस्कार, आपल्या मोबाइल प्रमाणिकरणासाठी {{code}} (OTP)', // Marathi
            'gu' => 'હેલો, તમારા મોબાઈલ વેરિફિકેશન માટે {{code}} (OTP)', // Gujarati
            'zh-tw' => '您好，您的手機驗證碼是 {{code}} (OTP)', // Chinese (Traditional)
        ];

        $Content = $lang['en'];
        $locale=GlobalUserInfo::getLocale();
        if($locale&&isset($lang[$locale])){
            $Content=$lang[$locale];
        }


//        $Content = 'Hola, Código {{code}} para su verificación móvil Slotomania';
//        $Services = new SendCode();
//        $res = $Services->sendCode($SendCodeConfigType)->send($phone, $ip, $UserID, $Content);


        $logic = new SendCodeLogic();
        $res=false;
        if($SendCodeConfigType==3){

            if ($logic->send($phone, $ip, $UserID,$Content) === false) {
                $res= $logic->getError();
                return apiReturnFail($res);
            }
        }else{

            if ($logic->plants_send($phone, $ip, $UserID,$Content) === false) {
                $res= $logic->getError();
                return apiReturnFail($res);
            }
        }

        return apiReturnSuc();


    }


    public function notify(Request $request)
    {
        $sendResult = $request->sendResult ?: '';
        $to = $request->to ?: '';

        if ($sendResult == 'SUCCESS') {
            Log::info('发送验证码回调：发送成功' . $to);
        }
        Log::info('发送验证码回调：发送失败' . $to);
        return 'SUCCESS';
    }

    // 验证码
    public function send_verify(Request $request)
    {
        $phone = $request->phoneNum ?: '';
        $Type = $request->Type ?: 0;    // 标识 1找回密码
        $ip = $request->ip();
        $logic = new SendCodeLogic();


        if ($logic->sendVerify(trim($phone), $ip, $Type) === false) {
            $res=$logic->getError();
            if($res){
                if(is_array($res)){
                    if(__($res[0])!=$res[0]){
                        return apiReturnFail(__($res[0]),$res);
                    }
                    return apiReturnFail($res[1],$res);
                }
                return apiReturnFail($res);
            }
            return apiReturnFail($logic->getError());
        }

        return apiReturnSuc();
    }

    public function getCode(Request $request){
        $phone = $request->PhoneNum;
        $query = DB::table(TableName::QPTreasureDB() . 'GamePhoneVerityCode')
            ->where('PhoneNum', $phone)
            ->select('PhoneNum', 'Code')
            ->first();
        if($request->formart){
            return apiReturnSuc(['code' => $query?$query->Code:0]);
        }
        return $query?$query->Code:0;
    }
}
