<?php

namespace App\Components\PensionCase;

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

class StatusReport extends Component {
    public string $claimType = 'bank';

    const TYPES = [
        'bank' => 'Bank',
        'fscs' => 'FSCS',
        'fos'  => 'FOS',
    ];

    public function setType(string $type): void {
        if (array_key_exists($type, self::TYPES)) {
            $this->claimType = $type;
        }
    }

    public function getStatusCountsProperty(): \Illuminate\Support\Collection {
        $counts = PensionCase::select('status_id', DB::raw('count(*) as cases_count'))
            ->where('claim_type', $this->claimType)
            ->whereNotNull('status_id')
            ->groupBy('status_id')
            ->pluck('cases_count', 'status_id');

        return Status::where('type', 'pension-' . $this->claimType)
            ->get()
            ->map(function (Status $status) use ($counts) {
                $status->cases_count = $counts[$status->id] ?? 0;
                return $status;
            })
            ->sortByDesc('cases_count');
    }

    public function getNoStatusCountProperty(): int {
        return PensionCase::where('claim_type', $this->claimType)
            ->whereNull('status_id')
            ->count();
    }

    public function getTotalsProperty(): array {
        return PensionCase::select('claim_type', DB::raw('count(*) as total'))
            ->groupBy('claim_type')
            ->pluck('total', 'claim_type')
            ->toArray();
    }

    public function render(): \Illuminate\View\View {
        return view('components.pension-case.status-report', [
            'statusCounts'  => $this->statusCounts,
            'noStatusCount' => $this->noStatusCount,
            'totals'        => $this->totals,
        ]);
    }
}
