<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\ComplaintAgainst;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;


class RegisterController extends Controller
{

    use RegistersUsers;


    protected $redirectTo = RouteServiceProvider::HOME;



    public function __construct()
    {
        $this->middleware('guest');
    }



    protected function validator(array $data)
    {

        return Validator::make($data,[


            'name'=>[
                'required',
                'string',
                'max:255'
            ],


            'email'=>[
                'required',
                'email',
                'unique:users'
            ],


            'password'=>[
                'required',
                'min:8',
                'confirmed'
            ],


            'role'=>[
                'required'
            ],


            'complaint_against_id'=>[
                'nullable',
                'required_if:role,department',
                'exists:complaint_against,id'
            ],



        ]);

    }





    protected function create(array $data)
    {


    return User::create([


    'name'=>$data['name'],


    'email'=>$data['email'],


    'password'=>Hash::make(
        $data['password']
    ),


    'role'=>$data['role'],


    'is_admin'=> 
        isset($data['is_admin']) ? 1 : 0,


    'complaint_against_id'=>
        $data['role']=="department"
        ? $data['complaint_against_id']
        : null


    ]);


    }


}