<?php

use Espo\Core\Container;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Metadata;
use Espo\Core\InjectableFactory;
use Espo\Core\Utils\Config\ConfigWriter;

class AfterUninstall
{
    public function run(Container $container)
    {
        /** @noinspection PhpUnhandledExceptionInspection */
        $metadata = $container->getByClass(Metadata::class);
        /** @noinspection PhpUnhandledExceptionInspection */
        $config = $container->getByClass(Config::class);
        /** @var ConfigWriter $configWriter */
        $configWriter = $container->getByClass(InjectableFactory::class)->create(ConfigWriter::class);

        $this->removeProjectParent($config, $metadata);
        $this->removeAdminIframeUrl($config, $configWriter);
    }

    private function removeProjectParent(Config $config, Metadata $metadata): void
    {
        $activitiesEntityTypeList = $config->get('activitiesEntityList', []);
        $historyEntityTypeList = $config->get('historyEntityList', []);

        $entityTypeList = array_merge($activitiesEntityTypeList, $historyEntityTypeList);
        $entityTypeList = array_unique($entityTypeList);

        foreach ($entityTypeList as $entityType) {
            if (!$metadata->get(['entityDefs', $entityType, 'fields', 'parent', 'entityList'])) {
                continue;
            }

            $list = $metadata->get(['entityDefs', $entityType, 'fields', 'parent', 'entityList'], []);

            if (!in_array('Project', $list)) {
                continue;
            }

            $key = array_search('Project', $list);

            unset($list[$key]);
            $list = array_values($list);

            $data = [
                'fields' => [
                    'parent' => ['entityList' => $list]
                ],
            ];

            $metadata->set('entityDefs', $entityType, $data);
        }

        $metadata->save();
    }

    private function removeAdminIframeUrl(Config $config, ConfigWriter $configWriter): void
    {
        /** @var ?string $url */
        $url = $config->get('adminPanelIframeUrl');
        $url = $this->removeUrlParam($url, 'project-management', '/');

        if ($url == $config->get('adminPanelIframeUrl')) {
            return;
        }

        $configWriter->set('adminPanelIframeUrl', $url);
        $configWriter->save();
    }

    private function removeUrlParam(string $url, string $paramName, string $suffix = ''): string
    {
        $urlQuery = parse_url($url, \PHP_URL_QUERY);

        if ($urlQuery) {
            parse_str($urlQuery, $params);

            if (isset($params[$paramName])) {
                unset($params[$paramName]);

                $newUrl = str_replace($urlQuery, http_build_query($params), $url);

                if (empty($params)) {
                    /** @var string $newUrl */
                    $newUrl = preg_replace('/\/\?$/', '', $newUrl);
                    /** @var string $newUrl */
                    $newUrl = preg_replace('/\/$/', '', $newUrl);

                    $newUrl .= $suffix;
                }

                return $newUrl;
            }
        }

        return $url;
    }
}
