<?php

namespace App\Components\Institution;

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

class Create extends Component {
    use AuthorizesRequests;

    public $display_name;

    public $dsar_types;
    public $dsar_type_id = 6;
    public $send_type;

    public $rules = [
        'dsar_type_id' => 'required|integer|exists:dsar_types,id',
        'display_name' => 'required|string|max:255|unique:institutions,display_name',
        'send_type' => 'nullable|string|in:post,email,both',
    ];

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

        $this->dsar_types = DsarType::pluck('display_name', 'id');

        if ($prefill = request()->query('display_name')) {
            $this->display_name = $prefill;
        }
    }

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

        $this->validate();

        $institution = Institution::create([
            'dsar_type_id' => $this->dsar_type_id,
            'display_name' => $this->display_name,
            'send_type' => $this->send_type ?: null,
        ]);

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


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