<?php

namespace App\Components\Institution;

use App\Models\Institution\Institution;
use Livewire\Component;

class Clients extends Component
{

    public Institution $institution;

    public function render() {
        $viaCareSetting = $this->institution->careSettings()
            ->with('claim.client', 'claim.status', 'claim.tags')
            ->get()
            ->filter(fn($cs) => $cs->claim)
            ->keyBy(fn($cs) => $cs->claim->id);

        $viaDirect = $this->institution->claims()
            ->with('client', 'status', 'tags')
            ->get()
            ->keyBy('id');

        $clients = collect();

        foreach ($viaCareSetting as $id => $cs) {
            $clients[$id] = [
                'claim' => $cs->claim,
                'via'   => $viaDirect->has($id) ? 'both' : 'care_setting',
            ];
        }

        foreach ($viaDirect as $id => $claim) {
            if (!$clients->has($id)) {
                $clients[$id] = ['claim' => $claim, 'via' => 'direct'];
            }
        }

        return view('components.institution.clients', ['clients' => $clients->values()]);
    }
}
