<?php

namespace App\Components\Report;

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

class DaysInStatusReport extends Component {

    public function getStatusRangeCountsProperty() {
        $workspace = session('workspace', 'ha');

        // Count claims by their current status (claims.status_id is the source of
        // truth). status_histories is only a partial audit trail — a row is written
        // the first time a status is *changed*, so claims still in their original
        // status have no history row. We therefore drive the report off the claims
        // table and use the open history row only for timing, falling back to the
        // claim's created_at (it has been in its current status since creation).
        //
        // DISTINCT claims.id guards against any claim that ended up with more than
        // one open (ended_at IS NULL) history row.
        $duration = "DATEDIFF(NOW(), COALESCE(status_histories.started_at, claims.created_at))";

        $results = Status::query()
            ->leftJoin('claims', function ($join) {
                $join->on('claims.status_id', '=', 'statuses.id')
                    ->whereNull('claims.deleted_at');
            })
            ->leftJoin('status_histories', function ($join) {
                $join->on('status_histories.subject_id', '=', 'claims.id')
                    ->where('status_histories.subject_type', '=', Claim::class)
                    ->whereNull('status_histories.ended_at');
            })
            ->where('statuses.type', $workspace)
            ->select(
                'statuses.display_name as name',
                DB::raw("COUNT(DISTINCT CASE WHEN $duration <= 1 THEN claims.id END) as range_today"),
                DB::raw("COUNT(DISTINCT CASE WHEN $duration BETWEEN 2 AND 7 THEN claims.id END) as range_week"),
                DB::raw("COUNT(DISTINCT CASE WHEN $duration BETWEEN 8 AND 30 THEN claims.id END) as range_month"),
                DB::raw("COUNT(DISTINCT CASE WHEN $duration > 30 THEN claims.id END) as range_old")
            )
            ->groupBy('statuses.id', 'statuses.display_name')
            ->get();

        return $results;
    }

    public function render()
    {
        return view('components.report.days-in-status-report', [
        'reportData' => $this->statusRangeCounts
        ]);
    }
}
