<?php

namespace App\Reporting;

use App\Contracts\ReportTile;
use App\Reporting\Concerns\HasReportingPeriod;
use Mtc\MercuryDataModels\ReportingStat;

class AverageInventoryTile extends ReportTile
{
    use HasReportingPeriod;

    protected $value;
    protected $second_value;

    public function name(): string
    {
        return 'Avg. inventory';
    }

    public function value(): mixed
    {
        if (empty($this->value)) {
            $this->value = round(ReportingStat::query()
                ->where('key', 'vehicle-count')
                ->whereBetween('date', [$this->windowStart(), $this->windowEnd()])
                ->average('value') ?? 0);
        }

        return $this->value;
    }

    public function difference(): mixed
    {
        if ($this->secondaryValue() > 0) {
            return round(100 * ($this->value() - $this->secondaryValue()) / ($this->secondaryValue() ?: 1), 2) . '%';
        }
        return '';
    }

    public function secondaryValue(): mixed
    {
        if (empty($this->second_value)) {
            $this->second_value = round(ReportingStat::query()
                ->where('key', 'vehicle-count')
                ->whereBetween('date', [$this->previousStart(), $this->previousEnd()])
                ->average('value') ?? 0);
        }

        return $this->second_value;
    }

    public function subtitle(): string
    {
        return $this->periodSubtitle();
    }

    public function secondaryValueName(): string
    {
        return $this->previousPeriodName();
    }
}
