<?php

namespace App\Components\Institution;

use App\Models\Institution\Institution;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Livewire\WithPagination;

class RelationManager extends Component {
    use AuthorizesRequests;
    use WithPagination;

    public Institution $institution;
    public $search = '';
    public $selectedIds = [];

    public function attachSelected() {
        $this->authorize('institutions.links.create');

        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->authorize('institutions.links.delete');

        $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
        ]);
    }
}
