<?php

namespace App\Components\Dsar;

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

class Outstanding extends Component {
    use WithPagination;

    public string $search           = '';
    public string $statusFilter     = '';
    public string $institutionFilter = '';

    public function mount(): void {
        $this->authorize('dsars.view');
    }

    public function updatingSearch()           { $this->resetPage(); }
    public function updatingStatusFilter()     { $this->resetPage(); }
    public function updatingInstitutionFilter(){ $this->resetPage(); }

    public function render() {
        $query = Dsar::with(['institution', 'claim.client', 'latestResponse'])
            ->whereNotIn('status', ['draft', 'completed']);

        if ($this->statusFilter) {
            $query->where('status', $this->statusFilter);
        }

        if ($this->institutionFilter) {
            $query->where('institution_id', $this->institutionFilter);
        }

        if ($this->search) {
            $search = $this->search;
            $query->where(function ($q) use ($search) {
                $q->whereHas('institution', fn($i) => $i->where('display_name', 'like', "%{$search}%"))
                  ->orWhereHas('claim.client', fn($c) =>
                      $c->where('name_first', 'like', "%{$search}%")
                        ->orWhere('name_last', 'like', "%{$search}%")
                  );
            });
        }

        $dsars = $query->orderByDesc('is_flagged')->orderBy('created_at')->paginate(20);

        $institutions = Institution::orderBy('display_name')
            ->whereHas('claims.dsars', fn($q) => $q->whereNotIn('status', ['draft', 'completed']))
            ->get(['id', 'display_name']);

        return view('components.dsar.outstanding', compact('dsars', 'institutions'));
    }
}
