<?php

/*
 * Copyright © 2020 Miguel Nogueira
 *
 *   This file is part of Raspberry Staff Manager.
 *
 *     Raspberry Staff Manager is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Raspberry Staff Manager is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Raspberry Staff Manager.  If not, see <https://www.gnu.org/licenses/>.
 */

namespace App\Http\Controllers\Auth;

use App\Facades\IP;
use App\Facades\Options;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Session;

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 = '/dashboard';

    /**
     * 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(array $data)
    {
        $password = ['required', 'string', 'confirmed'];

        $signupEnabled = Options::getOption('enable_registrations');
        $signupOverride = Session::has('ALLOW_REGISTRATION_OVERRIDE') && Session::get('ALLOW_REGISTRATION_OVERRIDE') === true;
        $signupOverrideEmail = Session::has('REGISTRATION_OVERRIDE_EMAIL') ? Session::get('REGISTRATION_OVERRIDE_EMAIL') : null;

        switch (Options::getOption('pw_security_policy')) { // this could be better structured, switch doesn't feel right
            case 'off':
                $password = ['required', 'string', 'confirmed'];
                break;
            case 'low':
                $password = ['required', 'string', 'min:10', 'confirmed'];
                break;

            case 'medium':
                $password = ['required', 'string', 'confirmed', 'regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[#?!@$%^&*-]).{12,}$/'];
                break;

            case 'high':
                $password = ['required', 'string', 'confirmed', 'regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{20,}$/'];
        }

        return Validator::make($data, [
            'uuid' => (Options::getOption('requireGameLicense') && Options::getOption('currentGame') == 'MINECRAFT') ? ['required', 'string', 'unique:users', 'min:32', 'max:32'] : ['nullable', 'string'],
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'dob' => ['required', 'string', 'date_format:Y-m-d', 'before:-13 years'],
            'acceptTerms' => ['required', 'accepted'],
            'password' => $password,
        ], [
            'dob.before' => __('You must be 13 years of age or older in order to sign up for an account.'),
            'dob.required' => __('Please enter your date of birth.'),
            'uuid.required' => __('Please enter a valid (and Premium) Minecraft username! We do not support cracked users.'),
            'acceptTerms.required' => __('Please accept the Community Guidelines, Terms of Service and Privacy Policy to continue.'),

        ])->after(function (\Illuminate\Validation\Validator $validator) use ($signupEnabled, $signupOverride, $signupOverrideEmail) {

            $email = $validator->getData()['email'];

            $validator->errors()->addIf(!$signupEnabled && !$signupOverride, 'signup', __('We\'re sorry, but new sign ups are currently closed and invite-only.'));
            $validator->errors()->addIf($signupOverride && $email !== $signupOverrideEmail, 'email', 'You must sign up with the email address you were invited with.');

        });
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        $ip = IP::shouldCollect() ? request()->ip() : '0.0.0.0';

        $user = User::create([
            'uuid' => $data['uuid'] ?? 'disabled',
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'registrationIp' => $ip,
            'currentIp' => $ip,
            'dob' => $data['dob'],
        ]);

        $user->assignRole('user');

        if (Session::get('ALLOW_REGISTRATION_OVERRIDE')) {
            Session::forget([
                'ALLOW_REGISTRATION_OVERRIDE',
                'REGISTRATION_OVERRIDE_EMAIL'
            ]);
        }

        return $user;
    }
}
