<?php

declare(strict_types=1);

namespace Plugin\tnt_coupons\src\Helper;

use stdClass;

final class ChartDataBuilder
{
    /**
     * @param object{dZeit: string, nCount: numeric-string|int|float}[] $beforeSales
     * @param object{dZeit: string, nCount: numeric-string|int|float}[] $saleSales
     */
    public static function build(array $beforeSales, array $saleSales): stdClass
    {
        $chartData         = new stdClass();
        $chartData->labels = [];
        $chartData->series = [[], []];

        foreach ($beforeSales as $row) {
            $chartData->labels[]    = $row->dZeit;
            $chartData->series[1][] = (float)$row->nCount;
            $chartData->series[0][] = 'null';
        }

        foreach ($saleSales as $row) {
            $lastLabel = $chartData->labels[count($chartData->labels) - 1] ?? null;
            if ($lastLabel === $row->dZeit) {
                array_pop($chartData->series[0]);
                array_pop($chartData->labels);
            }

            $chartData->labels[]    = $row->dZeit;
            $chartData->series[0][] = (float)$row->nCount;
        }

        if (count($beforeSales) === 0) {
            unset($chartData->series[1]);
        }

        return $chartData;
    }
}
