<?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\Traits\ActivatesUsers;
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, ActivatesUsers;

    /**
     * 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)
    {
        if (!isset($data['is_activated']))
        {
            $data['is_activated'] = true;

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

        $data['password'] = bcrypt($data['password']);
        $data['is_admin'] = false;
        unset($data['password_confirmation']);

        return User::create($data);
    }

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

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

        $userData = $request->all();

        // Social media login info
        $registerData = $request->getSession()->get('ssoRegisterData');
        if (!is_null($registerData))
        {
            $userData = array_merge($registerData, $userData);
            $request->getSession()->remove('ssoRegisterData');
        }

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

        if ($user->is_activated)
        {
            $this->logActivatedActivity($user);
            $this->sendUserActivatedEmails($user);
            $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(Request $request)
    {
        if (!UserConfig::get('allow_self_registration'))
        {
            return redirect(route('home'));
        }

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

    /**
     * Show the application registration form (for a social media-linked account).
     *
     * @return \Illuminate\Http\Response
     */
    public function showRegistrationFormSso(Request $request)
    {
        if (!UserConfig::get('allow_self_registration'))
        {
            return redirect(route('home'));
        }

        // Social media login info
        $registerData = $request->getSession()->get('ssoRegisterData');
        if (is_null($registerData))
        {
            // No SSO data in session, use the normal registration screen
            return redirect(route('register'));
        }

        return Theme::render('auth.v2_unified', [
            'active_tab' => 'register',
            'is_sso' => true,
            'register_data' => $registerData
        ]);
    }
}
