<?php

namespace App\Components\Dashboard;

use App\Models\Claim\Claim;
use App\Models\Claim\StatusHistory;
use App\Models\Client\Client;
use Livewire\Component;

class Stats extends Component
{
    public function render()
    {
        $clientsToday = Client::whereDate('created_at', today())->count();
        $clientsWeek  = Client::whereBetween('created_at', [now()->startOfWeek(), now()])->count();
        $clientsMonth = Client::whereBetween('created_at', [now()->startOfMonth(), now()])->count();

        $status24Today = $this->distinctClientsInStatus(24, today(), now());
        $status24Week  = $this->distinctClientsInStatus(24, now()->startOfWeek(), now());
        $status24Month = $this->distinctClientsInStatus(24, now()->startOfMonth(), now());

        $status34Today = $this->distinctClientsInStatus(34, today(), now());
        $status34Week  = $this->distinctClientsInStatus(34, now()->startOfWeek(), now());
        $status34Month = $this->distinctClientsInStatus(34, now()->startOfMonth(), now());

        return view('components.dashboard.stats', compact(
            'clientsToday', 'clientsWeek', 'clientsMonth',
            'status24Today', 'status24Week', 'status24Month',
            'status34Today', 'status34Week', 'status34Month',
        ));
    }

    private function distinctClientsInStatus(int $statusId, $from, $to): int
    {
        return StatusHistory::where('status_histories.status_id', $statusId)
            ->where('status_histories.subject_type', Claim::class)
            ->whereBetween('status_histories.started_at', [$from, $to])
            ->join('claims', 'claims.id', '=', 'status_histories.subject_id')
            ->distinct()
            ->count('claims.client_id');
    }
}
