<?php

namespace App\Components\Tag;

use App\Models\Tag;
use Illuminate\Database\Eloquent\Model;
use Livewire\Component;

class TagAssigner extends Component {
    public Model $model;
    public $search = '';

    public function mount(Model $model) {
        $this->model = $model;
        $this->model->load('tags');
    }

    public function getAvailableTagsProperty()
    {
        return Tag::whereNotIn('id', $this->model->tags->pluck('id'))
            ->when($this->search, fn($q) => $q->where('name', 'like', '%' . $this->search . '%'))
            ->orderBy('name')
            ->get();
    }

    public function assignTag($tagId) {
        $this->model->tags()->syncWithoutDetaching([$tagId]);
        $this->model->load('tags'); // Refresh tags
        $this->search = ''; // Clear search
    }

    public function removeTag($tagId) {
        $this->model->tags()->detach($tagId);
        $this->model->load('tags'); // Refresh tags
    }

    public function render() {
        return view('components.tag.tag-assigner', [
            'availableTags' => $this->availableTags,
        ]);
    }
}