<?php

namespace App\Http\Controllers\V1;

use App\Models\User;
use App\Services\SmsServer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Models\EmailCode;
use Illuminate\Support\Facades\Validator;


class SmsController extends Controller
{
    //发送短信验证码
    public function send(Request $request)
    {
        $checkResult = $this->checkMobile($request);

        if (!isset($checkResult['prefix'])) { //手机号验证不通过
            return $this->error($checkResult);
        }

        $request->event = $request->event ? : 'login';
        if ($request->event == "forget") {
            if (!User::where(['mobile' => $request->mobile])->first()) {
                return $this->error(trans("api.MOBILE_NO_REGISTER"));
            }
        }
        $prefix = $checkResult['prefix'];
        $user = Auth('api')->user();

        $result = SmsServer::send($request->mobile, $request->event, $prefix, [], $user);

        if (isset($result['error'])) {
            return $this->error(trans('api.SMS_RETURN_ERROR'));
        }
        $data = [
            'verifyKey' => $result['verifyKey'],
            'smsCode' => $result['smsCode'],
        ];
        return $this->success($data);
    }

    //验证手机号是否合法（支持中国/菲律宾）
    public function checkMobile($request)
    {
        $prefix = $request->prefix ? : $this->getMobilePrefix($request->mobile);

        switch ($prefix) {
            case '86': //中国
                $rule = ['required', 'regex:/^(\\+?0?86\\-?)?1[345789]\\d{9}$/'];
                break;
            case '63': //菲律宾 10位数字，或 11位 都验证通过
                $rule = ['required', 'regex:/^(\\+?0?63\\-?)?\\d{10}|^(\\+?0?63\\-?)?\\d{11}$/'];
                break;
            default: //默认为菲律宾
                $rule = ['required', 'regex:/^(\\+?0?63\\-?)?\\d{10}|^(\\+?0?63\\-?)?\\d{11}$/'];
        }

        $params = $request->all();
        //实际接收短信的手机号为组合
        $params['mobile'] = $prefix . $params['mobile'];

        $validator = Validator::make($params, [
            'mobile' => $rule,
        ], [
            'mobile.required' => trans('api.PLEASE_ENTER_MOBILE_PHONE_NUMBER'),
            'mobile.regex' => trans('api.MOBILE_PHONE_NUMBER_FORMAT_ERROR'),
        ]);
        if ($validator->fails()) {
            return $validator->messages()->first();
        }
        $checkResult = [
            'prefix' => $prefix
        ];

        return $checkResult;
    }


    //如果没有手机号前缀，正则判断
    public function getMobilePrefix($moble)
    {
        $prefix = '63';
        if(preg_match("/^(\\+?0?86\\-?)?1[345789]\\d{9}$/", $moble)){
            $prefix =  '86';
        }
        return $prefix;
    }

    //发送邮箱验证码
    public function sendEmailCode(Request $request)
    {
        $email = $request->input('email');
        $lang  = $request->input('lang', 'en');

        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ], [
            'email.required' => trans('api.PLEASE_ENTER_EMAIL'),
            'email.email' => trans('api.MAILBOX_FORMAT_ERROR'),
        ]);
        if ($validator->fails()) {
            return $this->error(trans('api.PARAMS_ERROR'));
        }

        $code = rand(1000, 9999);

        if($lang == 'zh'){
            $notice  = '本次验证码是' . '【 ' . $code . ' 】 ' . '有效期 5 分钟';
            $subject = '邮箱验证通知';
        }else{
            $subject = 'Mailbox validation notification';
            $notice  = 'Your verification code this time is' . '【 ' . $code . ' 】 ' . 'Valid for 5 minutes';
        }
        try {
            Mail::raw($notice, function ($message) use ($email, $subject) {
                $message->subject($subject);
                $message->to($email);
            });
            $verCode = new EmailCode();
            $verCode->channel = 'email';
            $verCode->account = $email;
            $verCode->code = $code;
            $verCode->state = 0;
            $verCode->save();
            return $this->success();
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }


}
