<?php

namespace App\Livewire\Forms\Studio\Setting;

use App\Models\User;
use App\Traits\WithMediaHandler;
use Illuminate\Validation\Rule;
use Livewire\Form;

class AccountForm extends Form
{
    use WithMediaHandler;

    public ?User $user = null;

    public string $username = '';

    public string $email = '';

    public string $status = '';

    public ?string $email_verified_at = null;

    public function rules(): array
    {
        return [
            'username' => ['required', 'alpha_num', 'min:5', 'max:20', Rule::unique('users', 'username')->ignore($this->user)],
            'email' => ['required', 'email', 'max:100', Rule::unique('users', 'email')->ignore($this->user)],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'username' => 'nama pengguna',
        ];
    }

    public function setAccount(User $user)
    {
        $this->user = $user;

        $this->username = $user->username;
        $this->email = $user->email;
        $this->status = $user->status->label();
        $this->email_verified_at = $user->email_verified_at ? formatDateTime($user->email_verified_at) : '-';
    }

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

        $this->user->update([
            'username' => $this->username,
            'email' => $this->email,
        ]);
    }
}
