<?php namespace Tps\Birzha\Components;

use Cms\Classes\ComponentBase;
use Illuminate\Support\Facades\Redirect;
use RainLab\User\Models\User;

class EmailVerify extends ComponentBase
{
    public function componentDetails() {
        return [
            'name' => 'Email Verification',
            'description' => 'Email Verification'
        ];
    }

    public function defineProperties()
    {
        return [
            'id' => [
                'title'       => 'User ID',
                'description' => 'User ID',
                'default'     => '{{ :id }}',
                'type'        => 'string',
            ],
            'code' => [
                'title'       => 'Verificaiton code',
                'description' => 'Verificaiton code',
                'default'     => '{{ :code }}',
                'type'        => 'string',
            ]
        ];
    }

    public function onRun() {

        $user = User::find($this->property('id'));

        if(!is_null($user)) {

            if(!$user->email_verified) {
                if($user->email_activation_code == $this->property('code')) {
                    $user->email_verified = true;
                    $user->email_activation_code = null;
                    $user->save();

                    $this->page['message'] = \Lang::get('rainlab.user::lang.account.email_verified_message');
                    
                } else {

                    $this->page['message'] = \Lang::get('rainlab.user::lang.account.email_verification_link_invalid');
                }
            } else {

                $this->page['message'] = \Lang::get('rainlab.user::lang.account.email_already_verified');
            }

        } else {

            return Redirect::to('/404');
        }
        
    }
}