<?php

namespace App\Reporting;

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

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

    public function name(): string
    {
        return 'Vehicle Ad views';
    }

    public function value(): mixed
    {
        if (!isset($this->value)) {
            $this->value = $this->getTotalViews(Carbon::now());
        }

        return $this->value;
    }

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

    public function secondaryValue(): mixed
    {
        if (!isset($this->second_value)) {
            $this->second_value = $this->getTotalViews(Carbon::now()->subDay());
        }

        return $this->second_value;
    }

    public function subtitle(): string
    {
        return 'today';
    }


    public function secondaryValueName(): string
    {
        return 'yesterday';
    }

    /**
     * @param $startDate
     * @param $endDate
     * @return int
     */
    private function getTotalViews($date): int
    {
        return VehicleView::query()
            ->whereDate('date', $date)
            ->sum('hits');
    }
}
