<?php

namespace App\Classes;

use App\Models\Company;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class QueryCount
{
    public Collection $qcount;

    public function __construct($model, $field) {
        $this->qcount = $model::select($field, DB::raw('count(*) as q_count'))
                            ->groupBy($field)
                            ->pluck('q_count', $field);
        return $this;
    }

    public function number_shorten($number, $precision = 2)
    {
        // $precision = $number>1000?$precision:0;
        $suffixes = ['', 'K+', 'M+', 'B+', 'T+', 'Qa+', 'Qi+'];
        $index = (int) log(abs($number), 1000);
        $index = max(0, min(count($suffixes) - 1, $index)); // Clamps to a valid suffixes' index
        $shnum = explode('.', number_format($number / 1000 ** $index, $precision));
        return ($shnum[1]>=1?implode('.', $shnum):$shnum[0]) . $suffixes[$index];
    }

    public function getBadgeCount($key='all'):string {
        $count = ($key=='all')?$this->qcount->sum():(isset($this->qcount[$key])?$this->qcount[$key]:0);
        return $this->number_shorten($count);
    }
}
