<?php

namespace App\Livewire\Studio\Setting;

use App\Livewire\Forms\Studio\Setting\AccountForm;
use App\Livewire\Forms\Studio\Setting\PasswordForm;
use App\Livewire\Forms\Studio\Setting\ProfileForm;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithToast;
use App\Traits\Notification\WithSubscribeNotification;
use App\Traits\Utilities\WithUpdatedData;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Hash;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Pengaturan')]
class Account extends Component
{
    use WithAuthorization, WithSubscribeNotification, WithToast, WithUpdatedData;

    public AccountForm $accountForm;

    public ProfileForm $profileForm;

    public PasswordForm $passwordForm;

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

        $user->load('employee');

        $this->accountForm->setAccount($user);

        $this->profileForm->setProfile($user->employee);

        $this->passwordForm->setUser($user);
    }

    public function updateAccount(): void
    {
        $this->canOrAbort('update account');

        $this->accountForm->update();

        $this->toast('Akun berhasil diperbarui.');
    }

    public function updateProfile(): void
    {
        $this->canOrAbort('update profile');

        $this->profileForm->update();

        $this->toast('Profil berhasil diperbarui.');
    }

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

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

            return;
        }

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

        $this->passwordForm->update();

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

        $this->toast('Kata sandi berhasil diperbarui, Silakan masuk kembali.');

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

    public function render(): View
    {
        return view('livewire.studio.setting.account', [
            'pageTitle' => 'Akun',
        ]);
    }
}
