<?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 Edit extends Component {
    use AuthorizesRequests;

    public Institution $institution;

    public $display_name;

    public $dsar_types;
    public $dsar_type_id;

    public $send_type;

    public bool $is_prioritised = false;

    public ?int $stated_sar_backlog = null;


    public function mount() {
        $this->authorize('edit', $this->institution);

        $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;
        $this->stated_sar_backlog = $this->institution->stated_sar_backlog;
    }

    public function saveInstitution() {
        $this->authorize('edit', $this->institution);

        $this->validate([
            'dsar_type_id'       => 'required|integer|exists:dsar_types,id',
            'display_name'       => 'required|string|max:255',
            'send_type'          => 'nullable|in:post,email,both',
            'stated_sar_backlog' => 'nullable|integer|min:0',
        ]);

        $backlogChanged = (int) $this->stated_sar_backlog !== (int) $this->institution->stated_sar_backlog
            || ($this->stated_sar_backlog === null) !== ($this->institution->stated_sar_backlog === null);

        $this->institution->update([
            'dsar_type_id'           => $this->dsar_type_id,
            'display_name'           => $this->display_name,
            'send_type'              => $this->send_type ?: null,
            'is_prioritised'         => $this->is_prioritised,
            'stated_sar_backlog'     => $this->stated_sar_backlog !== null && $this->stated_sar_backlog !== '' ? (int) $this->stated_sar_backlog : null,
            'sar_backlog_updated_at' => $backlogChanged ? now() : $this->institution->sar_backlog_updated_at,
        ]);

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


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