<?php

namespace App\Components\Claim;

use App\Models\Claim\Claim;
use App\Models\Institution\Institution;
use App\Models\Institution\InstitutionType;
use Livewire\Component;
use Livewire\WithFileUploads;

class CareSettingManager extends Component {

    public Claim $claim;

    use WithFileUploads;

    public $settings = [];


    public $institutionTypes = [];

    public function mount(Claim $claim)
    {
        $this->claim = $claim;
        $this->institutionTypes = InstitutionType::all();

        foreach ($this->claim->careSettings as $setting) {
            $this->settings[] = [
                'id' => $setting->id,
                'institution_id' => $setting->institution_id,
                'institution_name' => $setting->institution->display_name,
                'institution_type_id' => $setting->institution->type_id,
                'date_text' => $setting->dates,
                'people_involved' => $setting->people_involved,
                'personal_statement' => $setting->statement,
                'search_results' => [],
            ];
        }
    }


    public function search($index) {
        $this->settings[$index]['search_results'] = [];

        $display_name = $this->settings[$index]['institution_name'];

        $this->settings[$index]['search_results'] = Institution::where('display_name', 'LIKE', "%$display_name%")->get();

    }

    public function setItem($index, $value) {
        $this->settings[$index]['institution_name'] = Institution::find($value)->display_name;
        $this->settings[$index]['institution_id'] = $value;
        $this->settings[$index]['search_results'] = [];
    }

    public function addSetting() {
        $this->settings[] = [
            'institution_id' => null,
            'institution_name' => '',
            'institution_type_id' => null,
            'date_text' => '',
            'people_involved' => '',
            'personal_statement' => '',
            'search_results' => []
        ];
    }

    public function removeSetting($index)
    {
        if (!isset($this->settings[$index])) {
            return;
        }

        $setting = $this->settings[$index];

        if (!empty($setting['id'])) {
            $this->claim
                ->careSettings()
                ->where('id', $setting['id'])
                ->delete();
        }

        unset($this->settings[$index]);
        $this->settings = array_values($this->settings);

        $this->dispatch(
            'toast',
            type: 'success',
            message: 'Care setting removed.'
        );
    }


    public function save()
    {
        $this->validate([
            'settings.*.institution_name' => 'required|string',
            'settings.*.date_text' => 'required|string',
        ]);

        \DB::transaction(function () {

            foreach ($this->settings as $index => $setting) {

                if (empty($setting['institution_id'])) {
                    $institution = Institution::create([
                        'display_name' => $setting['institution_name'],
                        'institution_type_id' => $setting['institution_type_id'],
                    ]);

                    $this->settings[$index]['institution_id'] = $institution->id;
                }

                $careSetting = $this->claim->careSettings()->updateOrCreate(
                    ['id' => $setting['id'] ?? null],
                    [
                        'institution_id'  => $this->settings[$index]['institution_id'],
                        'dates'           => $setting['date_text'],
                        'people_involved' => $setting['people_involved'],
                        'statement'       => $setting['personal_statement'],
                    ]
                );

                $this->settings[$index]['id'] = $careSetting->id;
            }
        });

        $this->dispatch(
            'toast',
            type: 'success',
            message: 'Care settings saved.'
        );
    }


    public function render() {
        return view('components.claim.care-setting-manager');
    }
}
