<?php

namespace App\Components\Institution;

use App\Models\Dsar\DsarType;
use App\Models\Institution\Institution;
use App\Models\Institution\InstitutionType;
use Livewire\Component;

class Edit extends Component {
    public Institution $institution;

    public $display_name;

    public $institution_types;
    public $institution_type_id;

    public $dsar_types;
    public $dsar_type_id;

    public $send_type;

    public bool $is_prioritised = false;


    public function mount() {
        $this->institution_types = InstitutionType::pluck('display_name', 'id');
        $this->dsar_types = DsarType::pluck('display_name', 'id');
        $this->institution_type_id = $this->institution->institution_type_id;
        $this->display_name = $this->institution->display_name;
        $this->dsar_type_id = $this->institution->dsar_type_id;
        $this->send_type = $this->institution->send_type;
        $this->is_prioritised = (bool) $this->institution->is_prioritised;
    }

    public function saveInstitution() {
        $this->validate([
            'institution_type_id' => 'required|integer|exists:institution_types,id',
            'dsar_type_id' => 'required|integer|exists:dsar_types,id',
            'display_name' => 'required|string|max:255',
            'send_type' => 'nullable|in:post,email,both',
        ]);

        $this->institution->update([
            'institution_type_id' => $this->institution_type_id,
            'dsar_type_id' => $this->dsar_type_id,
            'display_name' => $this->display_name,
            'send_type' => $this->send_type ?: null,
            'is_prioritised' => $this->is_prioritised,
        ]);

        return redirect()->route('institutions.show', $this->institution);
    }


    public function render() {
        return view('components.institution.edit');
    }
}
