<?php

namespace App\Http\Controllers\Auth;

use App\Facade\Theme;
use App\Facade\UserConfig;
use App\Helpers\MiscHelper;
use App\Helpers\RecaptchaHelper;
use App\Mail\UserActivationRequired;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
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 login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    public static function passwordRequirements()
    {
        return [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ];
    }

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

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(Request $request)
    {
        return Validator::make($request->all(), self::passwordRequirements())
            ->after(function($validator) use ($request)
            {
                // reCAPTCHA validation
                if (
                    UserConfig::get('recaptcha_enabled_registration') &&
                    !RecaptchaHelper::validateResponse($request->request->get('g-recaptcha-response'), $request->getClientIp())
                )
                {
                    $validator->errors()->add('recaptcha', trans('auth.recaptcha_failed_message'));
                }
            });
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        $activationData = [
            'is_activated' => true
        ];

        if (UserConfig::get('require_email_verification'))
        {
            $activationData['is_activated'] = false;
            $activationData['activation_token'] = MiscHelper::randomString();
        }

        return User::create(array_merge(
            [
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
                'is_admin' => false
            ],
            $activationData
        ));
    }

    public function register(Request $request)
    {
        if (!UserConfig::get('allow_self_registration'))
        {
            return redirect(route('home'));
        }

        $this->validator($request)->validate();

        /** @var User $user */
        $user = $this->create($request->all());

        if ($user->is_activated)
        {
            $this->guard()->login($user);
        }
        else
        {
            // Send activation e-mail
            Mail::to($user)->send(new UserActivationRequired($user));
            $request->session()->flash('info', trans('auth.activation_required_message'));
        }

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

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showRegistrationForm()
    {
        if (!UserConfig::get('allow_self_registration'))
        {
            return redirect(route('home'));
        }

        return Theme::render('auth.v2_unified', [
            'active_tab' => 'register'
        ]);
    }
}
