<?php

namespace App\Reporting;

use App\Facades\Settings;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\Builder;
use Mtc\MercuryDataModels\ReportingStat;
use Mtc\MercuryDataModels\Vehicle;

class VehiclesInStockKPI implements Arrayable
{
    public function toArray()
    {
        if (tenant()->type === 'listing') {
            $count = ReportingStat::query()
                ->where('key', 'vehicle-count')
                ->latest()
                ->first()
                ?->value ?? 0;
        }
        if (empty($count)) {
            $count = Vehicle::query()
                ->active()
                ->when(
                    $this->excludeSoldVehicles(),
                    fn (Builder $query) => $query->where('is_sold', false)
                )
                ->count();
        }
        return [
            'name' => 'Vehicles published',
            'value' => $count,
            'scope' => '',
        ];
    }

    private function excludeSoldVehicles(): bool
    {
        return (bool) Settings::get('filter-results-exclude-sold-vehicles', false);
    }
}
