<?php

namespace App\Livewire;

use Illuminate\Support\Facades\DB;
use Livewire\Component;

class XfUserSelector extends Component
{

    private const int MIN_CHARS = 3;

    public string $search = '';
    public ?int $selected = null;
    public ?string $selectedUsername = null;

    public function mount( ?int $initialUserId = null ){
        if( $initialUserId ){
            $user = DB::connection('xenforo')->table('user')->where('user_id', $initialUserId)->first();
            if( $user ){
                $this->selected = $user->user_id;
                $this->selectedUsername = $user->username;
                $this->search = $user->username;
            }
        }
    }

    public function updatedSearch(): void
    {
        if( $this->selected && $this->search !== $this->selectedUsername) {
            $this->selected = null;
            $this->selectedUsername = null;
        }
    }

    public function selectUser( int $userId, string $username ): void
    {
        $this->selected = $userId;
        $this->selectedUsername = $username;
        $this->search = $username;
    }

    public function getResultsProperty(): array
    {
        if( strlen($this->search) < self::MIN_CHARS || $this->selected ) {
            return [];
        }

        return DB::connection('xenforo')
            ->table('user')
            ->where('username', 'like', '%' . $this->search . '%')
            ->orderBy('username')
            ->limit(10)
            ->get(['user_id','username'])
            ->toArray();
    }

    public function render()
    {
        return view('livewire.xf-user-selector');
    }
}
