<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Config;
use App\Providers\RouteServiceProvider;
use App\Http\Middleware\OnlyFullVersion;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;
use App\Http\Controllers\Auth\AuthHelpers;
use Illuminate\Foundation\Auth\RegistersUsers;

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');

        $this->middleware(OnlyFullVersion::class)->only(
            [
                'register',
            ]
        );
    }

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\View\View
     */
    public function showRegistrationForm()
    {
        if (AuthHelpers::checkRegister()) {
            $security_questions = $this->getSecurityQuestions();
            return view('auth.register', compact('security_questions'));
        } else {
            return view('partials.error', ['error' => trans('auth.register_disabled')]);
        }
    }


    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        $data = $this->validator($request->all())->validated();
        event(new Registered($user = $this->create($data)));

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

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

        return $request->wantsJson()
            ? new JsonResponse(
                ['message' => $this->sendSuccessfullyRegistered()],
                201
            )
            : redirect($this->redirectPath());
    }


    /**
     * 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, [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'user_name' => ['required', 'string', 'max:255', 'unique:srm_Users,user_name'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:srm_Users,Email'],
            'password' => ['required', 'confirmed', 'max:16', Password::min(8)
                ->letters()
                ->mixedCase()
                ->numbers()],
            'Security_question_index' => ['required', 'numeric'],
            'Security_answer' => ['required', 'string', 'max:255'],
        ], $this->validationMessages());
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        return User::create([
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'user_name' => $data['user_name'],
            'Email' => $data['email'],
            'Password' => Hash::make($data['password']),
            'Security_question_index' => $data['Security_question_index'],
            'Security_answer' => $data['Security_answer'],

            'status' => 'Pended',
            'is_admin' => 0,
            'is_owner' => 0,
            'group_id' => null,
            'regestration_IP' => request()->server("REMOTE_ADDR"),

        ]);
    }


    protected function getSecurityQuestions()
    {
        return  Config::get('srm_config.dashboard.security_questions');
    }

    protected function validationMessages()
    {
        return [
            'first_name.required' => 'Please enter your first name.',
            'last_name.required' => 'Please enter your last name.',
            'user_name.required' => 'Username can\'t be empty.',
            'user_name.unique' => 'This user name is already registered. Please use a different user name.',
            'email.required' => 'Email can\'t be empty.',
            'user_name.exists' => 'This email address is already registered. Please use a different email or log in with your existing account.',
            'password.required' => ':attribute can\'t be empty.',
            'password.confirmed' => 'Password and confirmation password do not match. Please make sure they match before proceeding.',
            'password.*' => 'Your :attribute must meet the following requirements: Between 8 and 16 characters long, contain at least one uppercase letter, one lowercase letter, one number.',
            'Security_answer.required' => 'Please provide an answer to the security question. This field cannot be left empty.'
        ];
    }

    protected function sendSuccessfullyRegistered()
    {
        return trans('auth.registered');
    }
}
