<?php declare(strict_types=1);

namespace Diamond\Presentation\Modules\UserHistory;

use Core\Menu\AdminMenu;
use Core\ModuleController;
use Diamond\Application\System\SystemService;
use Diamond\Application\User\UserService;
use Diamond\Domain\Stat\Contracts\StatEntityInterface;
use Diamond\Helpers\Date;
use Diamond\Infrastructure\Models\Stat\Stat;
use Diamond\Repositories\Stat\StatCriteria;
use Diamond\Repositories\Stat\StatRepository;

/**
 * Description of UserHistory
 *
 * @author Diamond Code Generator
 */
class UserHistory extends ModuleController
{

    private array $menuItems = [];

    private array $menuLabelsCache = [];

    public function __construct(protected UserService    $userService,
                                protected StatRepository $statRepository,
                                protected AdminMenu      $adminMenu
    )
    {
    }

    public function process(): string
    {
        if (!$id = input_get('id')) {
            throw new \RuntimeException('user id not set');
        }

        if (!$user = $this->userService->getUserRepository()->findById((int)$id)) {
            throw new \RuntimeException('user not found by id ' . $id);
        }

        $results = $this->statRepository->findByCriteria(
            StatCriteria::create()
                ->setFilterByUserId($user->getId())
                ->setSortByDateTime('DESC')
                ->setSearchByRequestUri(admin_path())
                ->setLimit(1000)
        );
        $history = [];

        $this->menuItems = $this->adminMenu->getItems();

        /** @var Stat $stat */
        foreach ($results as $stat) {
            if (strpos($stat->getRequestedPage(), '/_service') !== false) {
                continue;
            }
            $history[$stat->getDatetime()->format('d.m.Y H:i:s')][] = $this->buildItem($stat);
        }

        return $this->render([
            'history' => $history
        ]);
    }

    /**
     * @param StatEntityInterface|Stat $statEntity
     * @return array
     */
    private function buildItem(StatEntityInterface $statEntity): array
    {
        $label = $statEntity->getRequestedPage();
        $icon = '';

        if (isset($this->menuLabelsCache[$statEntity->getRequestedPage()])) {
            $label = $this->menuLabelsCache[$statEntity->getRequestedPage()][0];
            $icon = $this->menuLabelsCache[$statEntity->getRequestedPage()][1];
        } else {
            foreach ($this->menuItems as $root => $groups) {
                foreach ($groups as $item) {
                    if (isset($item['url'])) {
                        //      dump($item['url'],$statEntity->getRequestedPage(),$item['url']===$statEntity->getRequestedPage(),'-------');
                    };
                    if (isset($item['url']) && $item['url'] === $statEntity->getRequestedPage()) {
                        $label = $this->menuLabelsCache[$item['url']][0] = $item['label'];
                        $icon = $this->menuLabelsCache[$item['url']][1] = $item['icon'];
                        break;
                    }
                }
            }
        }

        if (strpos($statEntity->getRequestUri(), 'fn=add')) {
            $label .= ' . Создание';
        } elseif ($statEntity->getRequestMethod() === 'POST' && str_contains($statEntity->getPostData(),'"actiontype":"rows_delete"')) {
            $label .= ' . Удаление';
        }
        elseif ($statEntity->getRequestMethod() === 'POST' && strpos($statEntity->getRequestUri(), 'fn=edit')) {
            $label .= ' . Изменение';
        }
        else {
            $label .= ' . Чтение';
        }

        return [
            'page' => $statEntity->getRequestedPage(),
            'date' => $statEntity->getDatetime()->format('d.m.Y H:i:s'),
            'url' => $statEntity->getRequestUri(),
            'user_agent' => $statEntity->getUserAgent(),
            'method' => $statEntity->getRequestMethod(),
            'caption' => $label,
            'icon' => $icon,
        ];
    }
}               