<?php

namespace App\Reporting;

use App\Contracts\ReportTile;
use App\Metrics\ServiceBookingCount;
use App\Support\Period;
use Carbon\Carbon;

class ServiceBookingsTodayKPI extends ReportTile
{
    private mixed $value = null;
    private mixed $second_value = null;

    public function name(): string
    {
        return 'Service Bookings';
    }

    public function value(): mixed
    {
        if ($this->value === null) {
            $this->value = $this->countForDay(Carbon::today());
        }
        return $this->value;
    }

    public function difference(): mixed
    {
        if ($this->secondaryValue() > 0) {
            return (100 * round(($this->value() - $this->secondaryValue()) / $this->secondaryValue(), 2)) . '%';
        }
        return '';
    }

    public function secondaryValue(): mixed
    {
        if ($this->second_value === null) {
            $this->second_value = $this->countForDay(Carbon::yesterday());
        }
        return $this->second_value;
    }

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

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

    private function countForDay(Carbon $day): int
    {
        return (int) (new ServiceBookingCount())
            ->get(Period::create($day->copy()->startOfDay(), $day->copy()->endOfDay()))
            ->sum();
    }
}
