<?php

namespace App\Livewire\Auth;

use App\Enums\UserStatus;
use App\Traits\WithToast;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
use Livewire\Component;

#[Layout('components.layouts.auth', [
    'title' => 'Masuk Akun',
])]
class Login extends Component
{
    use WithToast;

    #[Validate(['required', 'string'], attribute: 'nama pengguna atau email')]
    public string $login = '';

    #[Validate('required', attribute: 'kata sandi')]
    public string $password = '';

    public function auth()
    {
        $this->validate();

        $identifier = filter_var($this->login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

        if (! auth()->attempt(
            [$identifier => $this->login, 'password' => $this->password],
        )) {
            $this->toast('Nama pengguna, email atau kata sandi salah.', 'Gagal', 'danger');

            return;
        }

        if (auth()->user()->status !== UserStatus::ACTIVE) {
            auth()->logout();

            return;
        }

        $this->toast('Selamat datang, '.auth()->user()?->employee?->full_name.'. Semoga harimu menyenangkan.');

        session()->regenerate();

        $this->redirectIntended('/studio/dashboard/overview', navigate: true);
    }

    public function render()
    {
        return view('livewire.auth.login');
    }
}
