<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\UserManagement\Customer;
use App\Models\UserManagement\UserType;
use App\Providers\RouteServiceProvider;
use App\Models\UserManagement\User;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Auth\Events\Registered;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

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 = RouteServiceProvider::HOME;

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


    public function register(Request $request){

        $userTable = (new User)->getTable();

        $rules = [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'phone' => ['required', 'string', 'max:255', "unique:$userTable"],
            'username' => ['required', 'string', 'max:128', "unique:$userTable"],
            'email' => ['required', 'string', 'email', 'max:255', "unique:$userTable"],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
        ];
        $validator =  Validator::make($request->all(),$rules);

        if ($validator->fails()){
            return  redirect()->back()
                ->with([
                    "message" => __("Oupps! Your account registration failed. Correct error(s) below and click Register button to re-submit."),
                    "alert-type" => "danger",
                ])
                ->withErrors($validator)
                ->withInput();
        }
      //  $this->validatorZ($request->all());
        $user = $this->create($request->all()) ;
        event(new Registered($user));

        $this->guard()->login($user);

        if ($response = $this->registered($request, $user)) {
            return $response;
        }

        $cart = Cart::instance('default')->content();
        $redirect = (blank($cart)) ? route("shop.index") : route("checkout.index");

        return $request->wantsJson()
            ? new JsonResponse([], 201)
            : redirect($redirect)->with([
                "message" => __("Your account has been created and you now logged-in"),
                "alert-type" => "success",
            ]);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param array $data
     * @return array|RedirectResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function validatorZ(array $data){
        $userTable = (new User)->getTable();

        $validator =  Validator::make($data, [
                        'first_name' => ['required', 'string', 'max:255'],
                        'last_name' => ['required', 'string', 'max:255'],
                        'phone' => ['required', 'string', 'max:255', "unique:$userTable"],
                        'username' => ['required', 'string', 'max:128', "unique:$userTable"],
                        'email' => ['required', 'string', 'email', 'max:255', "unique:$userTable"],
                        'password' => ['required', 'string', 'min:6', 'confirmed'],
                    ]);


        if ($validator->fails()){
            return  redirect()->back()
                            ->with([
                                "message" => __("Oupps! Your account registration failed. Correct error(s) below and click Register button to re-submit."),
                                "alert-type" => "danger",
                            ])->withErrors($validator)
                            ->withInput();

        }

        dd($validator->passes(),$validator->fails());
        return $validator->validate();


    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data){
       return Customer::create([
                    'first_name' => $data['first_name'],
                    'last_name' => $data['last_name'],
                    'username' => $data['username'],
                    'email' => $data['email'],
                    'phone' => $data['phone'],
                    'password' => Hash::make($data['password']),
                 //   UserType::FK_ID => UserType::CUSTOMER,
                ]);

        //$user->assignRole(Role);

     //   return $user;
    }
}
