<?php

namespace App\Livewire;

use App\Models\Entry;
use Livewire\Component;

class EntrySelector extends Component
{
    public string $search = '';
    public ?int $selectedEntryId = null;

    public ?string $entryName = null;

    public bool $dropdown = false;

    public function mount( ?int $oldEntryId = null ): void
    {
        if( $oldEntryId ) {
            $entry = Entry::find($oldEntryId);
            if( $entry ) {
                $this->selectedEntryId = $oldEntryId;
                $this->entryName = $entry->complete_title ?? $entry->title;
            }
        }
    }

    public function updatedSearch(): void
    {
        if( $this->selectedEntryId ) {
            $this->selectedEntryId = null;
            $this->entryName = null;
        }
        $this->dropdown = strlen($this->search) > 2;
    }

    public function selectEntry( int $id ){
        $entry = Entry::find($id);
        if( $entry ) {
            $this->selectedEntryId = $id;
            $this->entryName = $entry->complete_title ?? $entry->title;
            $this->search = $entry->complete_title ?? $entry->title;
            $this->dropdown = false;

        }
    }

    public function clearEntry(): void
    {
        $this->selectedEntryId = null;
        $this->entryName = null;
        $this->search = '';
    }

    public function render()
    {
        $entries = collect();

        if( $this->dropdown && strlen($this->search) > 2 ) {
            $entries = Entry::where('complete_title', 'like', '%' . $this->search . '%')
                ->orWhere('title', 'like', '%' . $this->search . '%')
                ->orderBy('complete_title', 'asc')
                ->orderBy('title', 'asc')
                ->limit(20)
                ->get();
        }

        $data = [ 'entries' => $entries, 'required_chars' => 3 ];

        return view('livewire.entry-selector', $data);
    }
}
