<?php

namespace App\Components\Report\Tranche;

use App\Models\Client\Client;
use App\Models\Tranche;
use Illuminate\Database\Eloquent\Builder;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component {
    use WithPagination;

    public $search = '';

    /**
     * High priority = client is 68+ OR their claim has a terminal illness.
     */
    protected function applyHighPriorityScope(Builder $query): void {
        $cutoff = now()->subYears(68)->toDateString();

        $query->where(function ($inner) use ($cutoff) {
            $inner->whereDate('date_of_birth', '<=', $cutoff)
                ->orWhereHas('claim.terminalIllness');
        });
    }

    public function render() {
        $fundedCount = Client::whereHas('tranche')->count();

        $highPriorityFunded = Client::whereHas('tranche')
            ->tap(fn ($q) => $this->applyHighPriorityScope($q))
            ->count();

        $stats = [
            'funded'        => $fundedCount,
            'available'     => Client::whereDoesntHave('tranche')
                ->whereHas('claim', fn ($q) => $q->whereNotNull('case_number'))
                ->count(),
            'pending'       => Client::whereHas('tranche')
                ->whereHas('claim', fn ($q) => $q->whereNull('case_number'))
                ->count(),
            'high_priority' => $highPriorityFunded,
            'low_priority'  => max(0, $fundedCount - $highPriorityFunded),
        ];

        $tranches = Tranche::withCount('clients')
            ->withCount([
                'clients as high_priority_count' => fn ($q) => $this->applyHighPriorityScope($q),
            ])
            ->where(function ($q) {
                $q->where('tranche_name', 'like', '%' . $this->search . '%')
                    ->orWhere('funder_name', 'like', '%' . $this->search . '%');
            })
            ->paginate(10);

        return view('components.report.tranche.index', [
            'stats'    => $stats,
            'tranches' => $tranches,
        ]);
    }
}
