<?php

namespace App\Livewire\Studio\Setting;

use App\Livewire\Forms\Studio\Setting\PasswordForm;
use App\Models\User;
use App\Traits\WithAuthorization;
use App\Traits\WithToast;
use App\Traits\WithUpdatedData;
use Illuminate\Support\Facades\Hash;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Kata Sandi')]
class Password extends Component
{
    use WithAuthorization, WithToast, WithUpdatedData;

    public PasswordForm $form;

    public function mount(User $user)
    {
        $this->form->setUser($user);
    }

    public function update()
    {
        $this->canOrAbort('update password');

        if (! Hash::check($this->form->current_password, $this->form->user->password)) {
            $this->toast('Kata sandi yang Anda masukkan tidak sesuai dengan kata sandi saat ini.', 'Gagal', 'danger');

            return;
        }

        auth()->logoutOtherDevices($this->form->current_password);

        $this->form->update();

        auth()->logout();
        session()->invalidate();
        session()->regenerateToken();

        $this->toast('Kata sandi berhasil diperbarui.');

        $this->redirectRoute('login', navigate: true);
    }

    public function render()
    {
        return view('livewire.studio.setting.password', [
            'pageTitle' => 'Kata Sandi',
        ]);
    }
}
