<?php

namespace App\Reporting;

use App\Contracts\ReportTile;
use App\Reporting\Concerns\HasReportingPeriod;
use Carbon\Carbon;
use Mtc\VehicleReservations\Reservation;

class ReservationsRevenueKPI extends ReportTile
{
    use HasReportingPeriod;

    private mixed $value = null;
    private mixed $second_value = null;

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

    public function value(): mixed
    {
        if ($this->value === null) {
            $this->value = $this->revenueBetween($this->windowStart(), $this->windowEnd());
        }
        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->revenueBetween($this->previousStart(), $this->previousEnd());
        }
        return $this->second_value;
    }

    public function subtitle(): string
    {
        return $this->periodSubtitle();
    }

    public function secondaryValueName(): string
    {
        return $this->previousPeriodName();
    }

    public function toArray(): array
    {
        return [
            ...parent::toArray(),
            'format' => 'currency',
        ];
    }

    private function revenueBetween(Carbon $from, Carbon $to): float
    {
        return (float) Reservation::query()
            ->whereNotNull('confirmed_at')
            ->whereBetween('confirmed_at', [$from, $to])
            ->sum('amount');
    }
}
