<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Modules\Base\Http\Requests\SmsRequest;
use Modules\Base\Services\SmsService;
use Modules\Base\Services\UserService;
use SMG\Support\Rules\Mobile;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/download';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            //'name' => 'required|string|max:255',
            'code'=>'required|check_sms:'.$data['phone'].',1',
            'phone' => ['required', new Mobile(), 'unique:users'],
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        $data = array_only($data, ['name', 'email', 'phone', 'password']);
        $data['password'] = Hash::make($data['password']);
        $data['sn'] = date('YmdHis').rand(10000,99999);
        $user = \Modules\Base\Entities\User::create($data);

        try{
            if (method_exists(UserService::class, 'getTokenIm')) {
                UserService::getTokenIm($user);
            }
        }catch (\Exception $exception){

        }
        return $user;
    }

    public function sms(Request $request, SmsService $sms){
        $this->validate($request, [
            'phone'=>['required', new Mobile(), 'unique:users'],
            'captcha'=>'required|captcha',
        ],['captcha'=>'验证码错误']);

        $sms->send($request->phone, 1);
        return response(['code'=>200,'msg'=>'success']);
    }
}
