<?php

namespace Daylight\Core\Livewire\Auth;

use Illuminate\View\View;
use Livewire\Component;

class TwoFactorSetup extends Component
{
    public string $confirmationCode = '';

    public string $disableCode = '';

    public bool $showingQrCode = false;

    public bool $showingRecoveryCodes = false;

    public bool $showingConfirmation = false;

    public bool $showingDisableConfirmation = false;

    public function enableTwoFactor(): void
    {
        $user = auth()->user();

        $user->enableTwoFactor();

        $this->showingQrCode = true;
        $this->showingConfirmation = true;
    }

    public function confirmTwoFactor(): void
    {
        $user = auth()->user();

        if (! $user->verifyTwoFactorCode($this->confirmationCode)) {
            $this->addError('confirmationCode', __('daylight::auth.two_factor.invalid_code'));

            return;
        }

        $user->confirmTwoFactor();

        session(['two_factor_authenticated' => true]);

        $this->showingQrCode = false;
        $this->showingConfirmation = false;
        $this->showingRecoveryCodes = true;
        $this->confirmationCode = '';
    }

    public function disableTwoFactor(): void
    {
        $this->showingDisableConfirmation = true;
        $this->showingRecoveryCodes = false;
        $this->disableCode = '';
        $this->resetErrorBag('disableCode');
    }

    public function confirmDisableTwoFactor(): void
    {
        $user = auth()->user();

        if (! $user->verifyTwoFactorCode($this->disableCode)) {
            $this->addError('disableCode', __('daylight::auth.two_factor.invalid_code'));

            return;
        }

        $user->disableTwoFactor();

        session()->forget('two_factor_authenticated');

        $this->reset(['showingQrCode', 'showingRecoveryCodes', 'showingConfirmation', 'showingDisableConfirmation', 'confirmationCode', 'disableCode']);
    }

    public function cancelDisable(): void
    {
        $this->showingDisableConfirmation = false;
        $this->disableCode = '';
        $this->resetErrorBag('disableCode');
    }

    public function showRecoveryCodes(): void
    {
        $this->showingRecoveryCodes = true;
    }

    public function regenerateRecoveryCodes(): void
    {
        auth()->user()->regenerateRecoveryCodes();

        $this->showingRecoveryCodes = true;
    }

    public function render(): View
    {
        return view('daylight::livewire.auth.two-factor-setup');
    }
}
