<?php

namespace App\Http\Requests;

use App\Mailables\RegisterUser;
use App\Models\User;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Mail;

class EmailVerification extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $id = $this->route('id');
        $hash = $this->route('hash');

        if(empty($id) || empty($hash)) {
            return false;
        }

        $user = User::find($id);

        if(empty($user)) {
            return false;
        }

        if (! hash_equals(sha1($user->getEmailForVerification()), (string) $hash)) {
            return false;
        }

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }

    /**
     * Fulfill the email verification request.
     *
     * @return void
     */
    public function fulfill()
    {
        $id = $this->route('id');
        $user = User::find($id);
        if (! $user->hasVerifiedEmail()) {
            $user->markEmailAsVerified();

            if ($user->state == 'pendingEmailValidation') {
                $user->state = 'pendingApproval';
                $user->save();

                Mail::to(config('mail.to.admin'))->send(new RegisterUser());
            }

            event(new Verified($user));
        }
    }

    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        return $validator;
    }
}
