<?php

namespace App\Components\Report;

use App\Models\Claim\Status;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use App\Models\Solicitor\Solicitor;

class DaysInStatusReport extends Component {

    public function getStatusRangeCountsProperty() {

        $solicitor = app(Solicitor::class);

        return Status::query()
            ->leftJoin('claims', 'claims.status_id', '=', 'statuses.id')
            ->leftJoin('status_histories', function ($join) use ($solicitor) {
                $join->on('status_histories.subject_id', '=', 'claims.id')
                    ->on('status_histories.status_id', '=', 'claims.status_id')
                    ->where('status_histories.subject_type', '=', \App\Models\Claim\Claim::class)
                    ->where('status_histories.solicitor_id', $solicitor->id)
                    ->whereNull('status_histories.ended_at');
            })
            ->select(
                'statuses.id',
                'statuses.display_name as name',
    
                DB::raw("COUNT(DISTINCT claims.id) as current_claim_count"),
    
                DB::raw("COUNT(DISTINCT CASE WHEN DATE(status_histories.started_at) = CURDATE() THEN claims.id END) as range_today"),
                DB::raw("COUNT(DISTINCT CASE WHEN DATEDIFF(NOW(), status_histories.started_at) BETWEEN 2 AND 7 THEN claims.id END) as range_week"),
                DB::raw("COUNT(DISTINCT CASE WHEN DATEDIFF(NOW(), status_histories.started_at) BETWEEN 8 AND 30 THEN claims.id END) as range_month"),
                DB::raw("COUNT(DISTINCT CASE WHEN DATEDIFF(NOW(), status_histories.started_at) BETWEEN 31 AND 60 THEN claims.id END) as range_60"),
                DB::raw("COUNT(DISTINCT CASE WHEN DATEDIFF(NOW(), status_histories.started_at) BETWEEN 61 AND 90 THEN claims.id END) as range_90"),
                DB::raw("COUNT(DISTINCT CASE WHEN DATEDIFF(NOW(), status_histories.started_at) > 90 THEN claims.id END) as range_old")
            )
            ->groupBy('statuses.id', 'statuses.display_name')
            ->get();
    }
    
    public function render()
    {
        return view('components.report.days-in-status-report', [
            'reportData' => $this->statusRangeCounts
        ]);
    }
}
