<?php

namespace App\Livewire\Auth;

use App\Models\User;
use App\Notifications\User\OTP;
use App\Rules\ValidOTP;
use App\Utils\ManagesOTP;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Session;
use Livewire\Attributes\Validate;
use Livewire\Component;

#[Layout('components.layouts.auth', [
    'title' => 'Verify Email Address'
])]
class Verify extends Component {
    use ManagesOTP;

    #[Validate(new ValidOTP(4))]
    public $code;

    #[Session]
    public $delay;

    public function mount() {
        $user = User::find(auth()->id());
        if($user->hasVerifiedEmail()) {
            return to_route('account');
        }
    }

    public function verify() {
        $this->validate();

        $user = User::find(auth()->id());
        $user->markEmailAsVerified();
        
        $this->dispatchAlert(
            text: 'Account verified successfully.',
            type: 'success',
        );

        return $this->redirect(route('secret-phrase.backup'), true);
    }

    public function resend() {
        if ($this->delay == null) {
            $user = User::find(auth()->id());
            $otp = $this->createOTP($user, 'email_verification');

            $user->notify(new OTP($otp));
            $this->delay = 30;

            $this->dispatchAlert(
                text: 'Your activation code has been sent again to your email inbox or spam folder.',
                type: 'success',
            );
        }
    }

    public function setDelay($delay) {
        $this->delay = $delay;
    }
}
