<?php

namespace App\Components\Institution;

use App\Models\Institution\Institution;
use Livewire\Component;
use Livewire\WithPagination;

class RelationManager extends Component {
    public Institution $institution;
    public $search = '';
    public $selectedIds = [];

    use WithPagination;

    public function attachSelected() {
        if (empty($this->selectedIds)) {
            $this->dispatch('toast', type: 'error', message: 'No institutions selected.');
            return;
        }

        $this->institution->relatedInstitutions()->syncWithoutDetaching($this->selectedIds);

        $this->selectedIds = [];

        $this->dispatch('toast', type: 'success', message: 'Institutions attached successfully.');
    }

    public function detach($id)
    {
        $this->institution->relatedInstitutions()->detach($id);
        $this->dispatch('toast', type: 'success', message: 'Institutions detached successfully.');
    }

    public function render() {
        $alreadyAttachedIds = $this->institution->relatedInstitutions->pluck('id')->toArray();

        $query = Institution::where('id', '!=', $this->institution->id)
            ->whereNotIn('id', $alreadyAttachedIds);

        if ($this->search) {
            $query->where('display_name', 'like', '%' . $this->search . '%');
        }

        return view('components.institution.relation-manager', [
            'availableInstitutions' => $query->paginate(10),
            'mainInstitution' => $this->institution
        ]);
    }
}
