<?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\ErrorService;

/**
 * Class StabilaWidgetErrors
 * @package Plugin\tnt_stabila_shop
 */
class StabilaWidgetErrors 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
    {
        $errorService = new ErrorService(
            new DatabaseRepository(Shop::Container()->getDB()),
            new SessionRepository('tnt_stabila_shop'),
            Shop::Container()->getCache()
        );

        $errors       = $errorService->getErrorsLastWeek();
        $weeklyErrors = \array_map(
            static fn (object $dataChunk): string => (string)$dataChunk->returnValue,
            $errors->weeklyErrors
        );
        if (\count($weeklyErrors) < 2) {
            $weeklyErrors = [];
        }

        return $this->oSmarty->assign(
            'lastErrors',
            $errors->lastErrors
        )->assign(
            'weeklyErrors',
            \implode(',', $weeklyErrors)
        )->assign(
            'changeType',
            $errors->changeType
        )->assign(
            'changeAmount',
            $errors->changeAmount
        )->fetch(__DIR__ . '/errorsWidget.tpl');
    }
}
