<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop;

use JTL\Shop;
use JTL\Widgets\AbstractWidget;
use Plugin\tnt_stabila_shop\src\Repositories\DatabaseRepository;
use Plugin\tnt_stabila_shop\src\Repositories\SessionRepository;
use Plugin\tnt_stabila_shop\src\Services\PerformanceService;

/**
 * Class StabilaWidgetErrors
 * @package Plugin\tnt_stabila_shop
 */
class StabilaWidgetPerformance extends AbstractWidget
{
    /**
     * @inheritDoc
     */
    public function init(): void
    {
        parent::init();
        $this->oSmarty->assign(
            'tailadminURI',
            $this->getPlugin()->getPaths()->getAdminPath() . 'tailadmin/'
        )->assign(
            'pluginURL',
            $this->getPlugin()->getPaths()->getBackendURL()
        );
    }

    /**
     * @inheritDoc
     */
    public function getContent(): string
    {
        $performanceService = new PerformanceService(
            new DatabaseRepository(Shop::Container()->getDB()),
            new SessionRepository('tnt_stabila_shop'),
            Shop::Container()->getCache()
        );

        $data               = $performanceService->getPerformanceLastWeek();
        $weeklyPerformances = \array_map(
            static fn (object $dataChunk): string => (string)$dataChunk->returnValue,
            $data->weeklyPerformances
        );
        if (\count($weeklyPerformances) < 2) {
            $weeklyPerformances = [];
        }

        return $this->oSmarty->assign(
            'weeklyPerformances',
            \implode(',', $weeklyPerformances)
        )->assign(
            'changeType',
            $data->changeType
        )->assign(
            'changeAmount',
            $data->changeAmount
        )->fetch(__DIR__ . '/performanceWidget.tpl');
    }
}
