<?php

namespace App\Components\Tag;

use App\Models\Tag;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class TagAssigner extends Component {
    use AuthorizesRequests;

    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->authorize('edit', $this->model);

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

    public function removeTag($tagId) {
        $this->authorize('edit', $this->model);

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

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