<?php

namespace App\Components\Institution;

use App\Models\Institution\Institution;
use App\Models\Institution\InstitutionAlias;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class Aliases extends Component {
    use AuthorizesRequests;

    public Institution $institution;
    public bool $show = false;
    public string $alias = '';

    protected $paginationTheme = 'bootstrap';

    public function showAdd() {
        $this->show = true;
    }

    public function addAlias(HistoryService $service) {
        $this->authorize('institutions.edit');

        $data = $this->validate([
            'alias' => 'required|string|min:1'
        ]);

        $this->institution->aliases()->updateOrCreate(['alias' => $data['alias']], []);
        $this->hideAddAlias();
    }

    public function hideAddAlias() {
        $this->show = false;
        $this->reset('alias');
    }

    public function deleteAlias(int $id) {
        $this->authorize('institutions.edit');

        $alias = InstitutionAlias::findOrFail($id);

        $alias->delete();
    }

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