<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop\src\Helper;

class MathHelper
{
    /**
     * Calculates the performance based on the last X days and monthly totals.
     *
     * @param int|float $totalLastXDays The number of some things in the last X days.
     * @param list<object{returnValue: int|float}> $totals The monthly/weekly etc. totals.
     * @return object{average: float, performance: float, performanceAverage: float} The calculated performance
     * percentage.
     */
    public static function calcPerformance(int|float $totalLastXDays, array $totals): object
    {
        $totalsCount = 0;
        $average     = 0.0;
        $performance = 0.0;
        $lastValue   = null;
        foreach ($totals as $total) {
            $average     += $total->returnValue;
            $performance += $total->returnValue / ($lastValue ?? $total->returnValue) - 1;
            $lastValue   = $total->returnValue;
            $totalsCount++;
        }
        $totalsCount        = $totalsCount ?: 1; // Avoid division by zero
        $performanceAverage = $performance * 100;
        $average            /= $totalsCount;
        $performanceAverage /= $totalsCount;
        $performance        = $average != 0.0 ? ($totalLastXDays / $average - 1) * 100 : 0.0;

        return (object)[
            'average'            => $average,
            'performanceAverage' => $performanceAverage,
            'performance'        => $performance
        ];
    }
}
