<?php

namespace App\Livewire\Auth;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;

class Pin extends Component {
    public function render() {
        $user = User::find(auth()->id());


        return $user->hasSetPin()
            ? view('livewire.auth.pin')->layout('components.layouts.auth', ['title' => 'Enter Pin'])
            : view('livewire.auth.set-pin')->layout('components.layouts.auth', ['title' => 'Set Pin']);
    }

    public function mount() {
        if (session('pin-entered')) {
            return to_route('account');
        }
    }

    #[Validate('required|digits:4')]
    public $pin;

    public function update() {
        $user = User::find(auth()->id());

        $user->update([
            'pin' => $this->pin,
        ]);

        $this->dispatchAlert(
            text: 'Pin set successfully.',
            type: 'success'
        );

        return $this->redirect(route('account.enter-pin'), true);
    }

    public function verify() {
        $user = User::find(auth()->id());
        if (Hash::check(
            value: $this->pin,
            hashedValue: $user->pin,
        )) {
            session([
                'pin-entered' => true
            ]);
            // return $this->redirect(route('account'), true); Make this happen
            return to_route('account');
        };
        $this->dispatch('wrong-pin');
    }
}
