<?php

namespace App\Livewire\Member\Setting;

use App\Livewire\Forms\Member\Setting\ProfileForm;
use App\Livewire\Forms\Studio\Setting\AccountForm;
use App\Livewire\Forms\Studio\Setting\PasswordForm;
use App\Traits\Components\WithToast;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Hash;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Pengaturan')]
#[Layout('components.layouts.member')]
class Account extends Component
{
    use WithToast;

    public AccountForm $accountForm;

    public ProfileForm $profileForm;

    public PasswordForm $passwordForm;

    public bool $hasMemberData = false;

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

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

        $customer = $user->customer;
        $this->hasMemberData = (bool) $customer;

        if ($this->hasMemberData) {
            $this->profileForm->setProfile($customer);
        }

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

    public function updateAccount(): void
    {
        $this->accountForm->update();

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

    public function updateProfile(): void
    {
        if (! $this->hasMemberData) {
            return;
        }

        $this->profileForm->update();

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

    public function updatePassword(): void
    {
        if (! Hash::check($this->passwordForm->current_password, auth()->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.member.setting.account', [
            'pageTitle' => 'Pengaturan Akun',
        ]);
    }
}
