<?php

namespace App\Livewire\User;

use App\Models\User;
use Livewire\Attributes\Validate;
use Livewire\Component;

class ProfileTab extends Component
{
    public ?User $user;

    #[Validate(['sometimes', 'nullable', 'string', 'max:255'])]
    public ?string $firstName = null;

    #[Validate(['sometimes', 'nullable', 'string', 'max:255'])]
    public $lastName = null;

    #[Validate(['required', 'string', 'max:255'])]
    public $username;

    #[Validate(['sometimes', 'nullable', 'email', 'max:255'])]
    public $email = null;

    #[Validate(['required', 'string', 'max:11'])]
    public $phone;

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

        if (!is_null($this->user->name)) {
            [$this->firstName, $this->lastName] = explode(' ', $this->user->name);
        }

        $this->username = $this->user->username;
        $this->email = $this->user->email;
        $this->phone = $this->user->phone;
    }

    public function updateUserProfile(): void
    {
        $this->validate();

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

        session()->flash('success', __('Your profile information got updated.'));
    }

    public function render()
    {
        return view('livewire.user.profile-tab');
    }

    private function prepareName(): ?string
    {
        return ! is_null($this->firstName) && ! is_null($this->lastName) ? "$this->firstName $this->lastName" : null;
    }
}
