<?php

namespace App\Reporting;

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

class AvgVehicleAgeTile extends ReportTile
{
    protected $value;
    protected $second_value;

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

    public function value(): mixed
    {
        if (empty($this->value)) {
            $this->value = round(ReportingStat::query()
                ->where('key', 'vehicle-age')
                ->where('date', '>', Carbon::now()->subDays(30)->format('Y-m-d'))
                ->average('value') ?? 0);
        }

        return $this->value;
    }

    public function difference(): mixed
    {
        if ($this->secondaryValue() > 0) {
            $diff = $this->value() - $this->secondaryValue();
            return abs($diff) == 1
                ? $diff . ' year'
                : $diff . ' years';
        }
        return '';
    }

    public function secondaryValue(): mixed
    {
        if (empty($this->second_value)) {
            $this->second_value = round(ReportingStat::query()
                ->where('key', 'vehicle-age')
                ->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.';
    }
}
