<?php

namespace App\Components\Institution;

use App\Models\Dsar\DsarType;
use App\Models\Institution\Institution;
use App\Services\HistoryService;
use Livewire\Component;

class Edit extends Component {
    public Institution $institution;

    public $display_name;

    public $dsar_types;
    public $dsar_type_id;

    public $send_type;

    public bool $is_prioritised = false;


    public function mount() {
        $this->dsar_types = DsarType::pluck('display_name', '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(HistoryService $history) {
        $this->validate([
            'dsar_type_id' => 'required|integer|exists:dsar_types,id',
            'display_name' => 'required|string|max:255',
            'send_type' => 'nullable|string|in:post,email,both,N/A',
        ]);

        $attributes = [
            'dsar_type_id' => $this->dsar_type_id,
            'display_name' => $this->display_name,
            'send_type' => $this->send_type ?: null,
            'is_prioritised' => $this->is_prioritised,
        ];
        $before = $this->institution->only(array_keys($attributes));

        $this->institution->update($attributes);

        $changed = [];
        foreach ($this->institution->getChanges() as $field => $newValue) {
            if (in_array($field, ['updated_at', 'created_at'])) {
                continue;
            }
            $changed[$field] = ['from' => $before[$field] ?? null, 'to' => $newValue];
        }

        if (!empty($changed)) {
            $history->add($this->institution, 'Institution updated', ['changed' => $changed]);
        }

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


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