<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Role;
use App\Marking;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
    use RegistersUsers;

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

    /**
     * The user has been registered.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function registered(Request $request, $user)
    {
        return $user;
    }

    /**
     * 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, [
            'marking' => 'required|max:255|unique:markings',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(Request $data)
    {
        $this->validate($data, [
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);

        $marking = Marking::Where('email',$data['email'])->first();

        if(!$marking){
            return response()->json(["message"=>"Marking does not exist, please contact sales team to get one"], 400);
        }
        if($marking->marking != strtoupper($data['marking'])){
            return response()->json(["message"=>"Incorrect marking"], 400);   
        }
        
        if(User::Where('email',$data['email'])->first()){
            return response()->json(["message"=>"Email already exist in the system"], 400);      
        }

        $role = Role::where('name','=','member')->first();
        $user = new User();
        $user->name = $data['name'];
        $user->email = $data['email'];
        $user->marking =  $marking->marking;
        $user->password = bcrypt($data['password']);

        $user->save();
        $user->attachRole($role);
        return response()->json($user, 201);   
    }
}
