<?php

namespace App\Reporting;

use App\Contracts\ReportTile;
use Carbon\Carbon;
use Mtc\MercuryDataModels\ReportingStat;

class AverageInventoryTile extends ReportTile
{
    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')
                ->where('date', '>', Carbon::now()->subDays(30)->format('Y-m-d'))
                ->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')
                ->where('date', '>', Carbon::now()->subDays(60)->format('Y-m-d'))
                ->where('date', '<', Carbon::now()->subDays(30)->format('Y-m-d'))
                ->average('value') ?? 0);
        }

        return $this->second_value;
    }

    public function subtitle(): string
    {
        return 'last 30 days';
    }

    public function secondaryValueName(): string
    {
        return 'prev 30 d.';
    }
}
