<?php

namespace App\Components\Institution;

use App\Models\Institution\Institution;
use App\Models\Dsar\DsarType;
use App\Models\Tag;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use AuthorizesRequests, WithPagination;

    public $search = '';
    public $sortColumn = 'display_name';
    public $sortDirection = 'asc';
    public $perPage = 10;

    #[Url(history: true)]
    public $tag_id;

    #[Url(history: true)]
    public $dsar_type_id;

    public function mount(): void {
        $this->authorize('viewAny', Institution::class);
    }

    public function boot(HistoryService $history): void {
        $this->history = $history;
    }

    public function clearFilters() {
        $this->reset('tag_id', 'dsar_type_id');
    }

    public function placeholder() {
        return <<<'HTML'
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-75"></div>
                        <div class="placeholder placeholder-wave w-50"></div>
                    </div>
                </div>
            </div>
        </div>
        HTML;
    }

    public function deleteInstitution($id) {
        $inst = Institution::findOrFail($id);

        $this->authorize('delete', $inst);

        if ($inst->hasAttachedClients()) {
            $this->dispatch('toast', message: 'Cannot delete: this institution is attached to one or more clients.', type: 'danger');
            return;
        }

        $inst->delete();

        $this->history->add($inst, "Institution deleted.");

        $this->history->add(auth()->user(), "Deleted institution {$inst->display_name}.");
    }

    public function render() {
        $institutions = Institution::with('dsarType')
            ->withCount(['careSettings', 'claims'])
            ->addSelect(\DB::raw('(
                SELECT COUNT(DISTINCT claims.client_id)
                FROM claims
                WHERE claims.deleted_at IS NULL
                AND (
                    claims.id IN (
                        SELECT claim_id FROM claim_institution WHERE claim_institution.institution_id = institutions.id
                    )
                    OR claims.id IN (
                        SELECT claim_id FROM care_settings WHERE care_settings.institution_id = institutions.id AND care_settings.deleted_at IS NULL
                    )
                )
            ) as clients_count'));

        if($this->search) {

            $search = trim($this->search);

            $institutions->where('display_name', 'like', '%'.$search.'%');

            if(is_numeric($search)) {
                $institutions->orWhere('id', $search - 100);
            }
        }

        if ($this->tag_id) {
            $institutions->whereHas('tags', function ($tags) {
                $tags->where('tags.id', $this->tag_id);
            });
        }

        if($this->dsar_type_id) {
            $institutions->where('dsar_type_id', $this->dsar_type_id);
        }

        $institutions = $institutions->orderBy($this->sortColumn, $this->sortDirection)->paginate($this->perPage);
        return view('components.institution.index', [
            'institutions' => $institutions,
            'tags' => Tag::pluck('name', 'id')->toArray(),
            'dsarTypes' => DsarType::pluck('display_name', 'id')->toArray(),
        ]);
    }
}
