<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use App\User;
use Mail;
use App\Rules\Pesel;

class RegistrationController extends Controller
{
    public function create()
    {
        return view('register');
    }

    public function store()
    {
        $this->validate(request(), [

            'name' => 'required|min:2|max:45|regex:/^[A-Za-zżźćńółęąśŻŹĆĄŚĘŁÓŃ\040\x27-]+$/',
            'surname' => 'required|min:2|max:45|regex:/^[A-Za-zżźćńółęąśŻŹĆĄŚĘŁÓŃ\040\x27-]+$/',
            'PESEL' => new Pesel,
            'phoneNumber' => 'required|digits:9',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed|min:6|max:45',
        ],
        [
            'required' => ':attribute jest wymagany(e).',
            'min' => ':attribute musi mieć przynajmniej :min znaki.',
            'max' => ':attribute musi mieć nie więcej niż :max znaków.',
            'regex' => ':attribute może zawierać tylko litery, spacje, myślniki i apostrofy',
            'digits' => ':attribute musi składać się z :digits cyfr.',
            'unique' =>':attribute jest już zajęty.',
            'confirmed' =>':attribute się nie zgadza.',
            'email' => 'Niepoprawny adres e-mail.'
        ]);


        $request = request();

        $confirmation_code = str_random(30);

        $user = User::create([
            'password' => $request-> password,
            'email' => $request-> email,
            'name' => $request-> name,
            'surname' => $request-> surname,
            'PESEL' => $request-> PESEL,
            'phoneNumber' => $request-> phoneNumber,
            'functionID' => 1,
            'degreeID' => 1,
            'number' => 'ABC123',
            'confirmation_code' => $confirmation_code
        ]);

        Mail::send('emails.verify', compact('confirmation_code'), function($message) {
            $message->to(Input::get('email'), Input::get('name'))->subject('Weryfikacja adresu e-mail');
        });

        //Flash::message('Thanks for signing up! Please check your email.');


        auth()->login($user);

        return redirect()->to('/jednostka');
    }

    public function confirm($confirmation_code)
    {
        if( ! $confirmation_code)
        {
            throw new InvalidConfirmationCodeException;
        }

        $user = User::whereConfirmationCode($confirmation_code)->first();

        if ( ! $user)
        {
            throw new InvalidConfirmationCodeException;
        }

        $user->confirmed = 1;
        $user->confirmation_code = null;
        $user->email_verified_at = now();
        $user->save();

        //Flash::message('You have successfully verified your account.');

        return redirect()->to('/jednostka');
    }

}

