<?php

namespace App\Reporting;

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

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) {
            $sql = 'COALESCE(SUM(hits + COALESCE(filter_views, 0) + COALESCE(quick_view_hits, 0) '
                . '+ COALESCE(compare_views, 0)), 0) as total_views';

            return ResourceView::query()
                ->where('viewable_type', 'vehicle')
                ->whereDate('date', $date)
                ->selectRaw($sql)
                ->first()
                ->total_views;
        })->average());
    }
}
