<?php

namespace App\Components\Account;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Laravel\Fortify\Actions\ConfirmTwoFactorAuthentication;
use Laravel\Fortify\Actions\DisableTwoFactorAuthentication;
use Laravel\Fortify\Actions\EnableTwoFactorAuthentication;
use Laravel\Fortify\Actions\GenerateNewRecoveryCodes;
use Livewire\Component;

class AccountSecurity extends Component {
    /* ---------------- PASSWORD ---------------- */

    public string $current_password = '';
    public string $new_password = '';
    public string $new_password_confirmation = '';

    /* ---------------- 2FA ---------------- */

    public string $twoFactorCode = '';

    public function updatePassword(): void {
        $this->validate([
            'current_password' => 'required',
            'new_password' => 'required|min:12|confirmed',
        ]);

        $user = Auth::user();

        if (!Hash::check($this->current_password, $user->password)) {
            $this->addError('current_password', 'Incorrect password.');
            return;
        }

        $user->update([
            'password' => Hash::make($this->new_password),
        ]);

        $this->reset(['current_password', 'new_password', 'new_password_confirmation']);

        session()->flash('success', 'Password updated 🔐');
    }

    /* ---------------- 2FA ACTIONS ---------------- */

    public function enable2fa(EnableTwoFactorAuthentication $action): void {
        $action(Auth::user());
    }

    public function confirm2fa(ConfirmTwoFactorAuthentication $action): void {
        $this->validate([
            'twoFactorCode' => 'required|string',
        ]);

        $action(Auth::user(), $this->twoFactorCode);

        $this->twoFactorCode = '';

        session()->flash('success', 'Two-factor authentication enabled ✨');
    }

    public function disable2fa(DisableTwoFactorAuthentication $action): void {
        $action(Auth::user());

        session()->flash('success', 'Two-factor authentication disabled.');
    }

    public function regenerateRecoveryCodes(GenerateNewRecoveryCodes $action): void {
        $action(Auth::user());

        session()->flash('success', 'Recovery codes regenerated.');
    }

    public function render() {
        $user = Auth::user();

        return view('components.account.account-security', [
            'twoFactorEnabled' =>
                !empty($user->two_factor_secret),

            'twoFactorConfirmed' =>
                !empty($user->two_factor_confirmed_at),

            'qrCode' =>
                (!empty($user->two_factor_secret) && empty($user->two_factor_confirmed_at))
                    ? $user->twoFactorQrCodeSvg()
                    : null,

            'recoveryCodes' =>
                (!empty($user->two_factor_secret) && !empty($user->two_factor_confirmed_at))
                    ? $user->recoveryCodes()
                    : [],
        ]);
    }
}