<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Services\SmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class SmsController extends Controller
{
    //发送短信验证码
    public function send(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'mobile' => ['required', 'regex:/^1[3456789]\d{9}$/'],
            'event' => 'required',
        ],[
            'mobile.required'=>"手机号码必须",
            'mobile.regex'=>"手机号码格式错误",
            'event.required'=>"类型必须",
        ]);
        if ($validator->fails()) {
            return $this->response()->errorForbidden($validator->messages()->first());
        }
        if($request->event=="forget"){
            if(!User::where(['mobile'=>$request->mobile])->first()){
                return $this->response->errorForbidden("该手机号码未注册");
            }
        }

        $user = Auth('api')->user();
        $result = SmsService::send($request->mobile, $request->event, [], $user);
        if (isset($result['error'])) {
            return $this->response->errorForbidden($result['error']);
        }

        return $this->response->array([
            'verifyKey' => $result['verifyKey']
            ,'code'=>$result['code']
        ]);
    }
}
