<?php

namespace App\Reporting;

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

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

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

    public function value(): mixed
    {
        if (empty($this->value)) {
            $startDate = Carbon::now()->subDays(30)->format('Y-m-d');
            $endDate = Carbon::now()->format('Y-m-d');

            $this->value = $this->getTotalViews($startDate, $endDate);
        }

        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 (empty($this->second_value)) {
            $startDate = Carbon::now()->subDays(60)->format('Y-m-d');
            $endDate = Carbon::now()->subDays(30)->format('Y-m-d');

            $this->second_value = $this->getTotalViews($startDate, $endDate);
        }

        return $this->second_value;
    }

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


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

    /**
     * @param $startDate
     * @param $endDate
     * @return int
     */
    private function getTotalViews($startDate, $endDate): int
    {
        $dates = collect(Carbon::parse($startDate)->daysUntil($endDate));

        return round($dates->map(function ($date) {
            return VehicleView::query()
                ->whereDate('date', $date)
                ->selectRaw('COALESCE(SUM(hits + filter_views + quick_view_hits + compare_views), 0) as total_views')
                ->first()
                ->total_views;
        })->average());
    }
}
