<?php

namespace App\Http\Controllers\Auth;

use App\Models\Member;
use App\Models\MemberGroup;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    use RegistersUsers;

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

    /**
     * Show the application register form.
     *
     * @return \Illuminate\Http\Response
     */

    public function showRegistrationForm()
    {
        return view('theme::register');
    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $this->rule($request);

        Auth::member()->login($this->create($request->all()));

        return redirect($this->redirectPath());

    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  $request
     * @return void
     */
    protected function rule($request)
    {
        $shop = trans("translate::shop");
        $str = trans("language::system.no_null");

        $this->validate($request, [
            'username' => 'required|string|max:255|unique:members',
            'email' => 'required|string|email|max:255|unique:members',
            'password' => 'required|string|min:6|confirmed'
        ], [
            'username.required' => (isset($shop['username']) ? $shop['username'] : 'Username').' '.$str,
            'username.unique' => isset($shop['exist_username']) ? $shop['exist_username'] : 'username already exists',
            'password.required' => (isset($shop['password']) ? $shop['password'] : 'Password').' '.$str,
            'password.confirmed' => isset($shop['match_password']) ? $shop['match_password'] : 'Passwords entered twice are inconsistent',
            'email.required' => (isset($shop['email']) ? $shop['email'] : 'E-mail').' '.$str,
            'email.email' => isset($shop['wrong_email_format']) ? $shop['wrong_email_format'] : 'E-mail format is wrong',
            'email.unique' => isset($shop['exist_email']) ? $shop['exist_email'] : 'email already exists'
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array $data
     * @return Member
     */
    protected function create(array $data)
    {
        return Member::create([
            'username' => $data['username'],
            'password' => bcrypt($data['password']),
            'group_id' => MemberGroup::min('id'),
            'email' => $data['email'],
            'lang' => config('lang')
        ]);
    }
}
