<?php
/*
 * Package GMapFP Free pour Joomla! 4, 5 et 6
 * Version 6.1.0
 * Creation date: Août 2026
 * Author: Fabrice4821 - https://www.gmapfp.org/
 * License GNU/GPL
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\Registry\Registry;
use Joomla\Database\DatabaseInterface;
use Joomla\Filesystem\Folder;

class pkg_gmapfpInstallerScript
{
    public function postflight($type, $parent): bool
    {
        if ($type !== 'install' && $type !== 'update') {
            return true;
        }

        try {
            $this->log('Début du post-traitement du package : ' . $type);
            $this->enableRetainedPlugins();
            $this->log('Plugins conservés activés');
            $this->removeObsoletePlugins();
            $this->log('Plugins obsolètes retirés');
            $this->removeExcludedModules();
            $this->log('Modules exclus de Free retirés');
            $this->cleanRetainedPluginParams();
            $this->log('Paramètres des plugins nettoyés');
        } catch (\Throwable $e) {
            $this->log('ERREUR : ' . $e->getMessage() . ' dans ' . $e->getFile() . ':' . $e->getLine());
            Factory::getApplication()->enqueueMessage(
                'Migration GMapFP interrompue : ' . $e->getMessage(),
                'error'
            );

            return false;
        }

        return true;
    }

    private function enableRetainedPlugins(): void
    {
        $db = Factory::getContainer()->get(DatabaseInterface::class);
        $plugins = [
            ['content', 'gmapfp_map'],
            ['editors-xtd', 'gmapfpmap'],
            ['gmapfp-map', 'google'],
            ['gmapfp-map', 'openstreet'],
            ['quickicon', 'gmapfp'],
            ['finder', 'gmapfp'],
            ['content', 'gmapfppagenavigation'],
            ['osmap', 'gmapfp'],
        ];

        foreach ($plugins as [$folder, $element]) {
            $query = $db->getQuery(true)
                ->update($db->quoteName('#__extensions'))
                ->set($db->quoteName('enabled') . ' = 1')
                ->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
                ->where($db->quoteName('folder') . ' = ' . $db->quote($folder))
                ->where($db->quoteName('element') . ' = ' . $db->quote($element));
            $db->setQuery($query)->execute();
        }
    }

    private function removeObsoletePlugins(): void
    {
        $db = Factory::getContainer()->get(DatabaseInterface::class);
        $plugins = [
            ['gmapfp-geocoding', 'ersi'],
            ['gmapfp-geocoding', 'esri'],
            ['gmapfp-geocoding', 'google'],
            ['fields', 'pictoslist'],
            ['fields', 'pictos_list'],
            ['content', 'fastsocialshare'],
        ];

        foreach ($plugins as [$folder, $element]) {
            $query = $db->getQuery(true)
                ->select($db->quoteName('extension_id'))
                ->from($db->quoteName('#__extensions'))
                ->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
                ->where($db->quoteName('folder') . ' = ' . $db->quote($folder))
                ->where($db->quoteName('element') . ' = ' . $db->quote($element));
            $extensionId = (int) $db->setQuery($query)->loadResult();

            if ($extensionId > 0) {
                $query = $db->getQuery(true)
                    ->update($db->quoteName('#__extensions'))
                    ->set($db->quoteName('enabled') . ' = 0')
                    ->where($db->quoteName('extension_id') . ' = ' . $extensionId);
                $db->setQuery($query)->execute();

                $query = $db->getQuery(true)
                    ->delete($db->quoteName('#__update_sites_extensions'))
                    ->where($db->quoteName('extension_id') . ' = ' . $extensionId);
                $db->setQuery($query)->execute();

                $query = $db->getQuery(true)
                    ->delete($db->quoteName('#__extensions'))
                    ->where($db->quoteName('extension_id') . ' = ' . $extensionId);
                $db->setQuery($query)->execute();

                $pluginPath = JPATH_PLUGINS . '/' . $folder . '/' . $element;
                if (is_dir($pluginPath)) {
                    Folder::delete($pluginPath);
                }
            }
        }
    }

    private function removeExcludedModules(): void
    {
        $db = Factory::getContainer()->get(DatabaseInterface::class);
        $elements = ['mod_gmapfp_a_venir', 'mod_gmapfp_calendar'];

        foreach ($elements as $element) {
            $query = $db->getQuery(true)
                ->select($db->quoteName('id'))
                ->from($db->quoteName('#__modules'))
                ->where($db->quoteName('module') . ' = ' . $db->quote($element));
            $moduleIds = array_map('intval', $db->setQuery($query)->loadColumn());

            if ($moduleIds) {
                $query = $db->getQuery(true)
                    ->delete($db->quoteName('#__modules_menu'))
                    ->where($db->quoteName('moduleid') . ' IN (' . implode(',', $moduleIds) . ')');
                $db->setQuery($query)->execute();

                $query = $db->getQuery(true)
                    ->delete($db->quoteName('#__modules'))
                    ->where($db->quoteName('id') . ' IN (' . implode(',', $moduleIds) . ')');
                $db->setQuery($query)->execute();
            }

            $query = $db->getQuery(true)
                ->select($db->quoteName('extension_id'))
                ->from($db->quoteName('#__extensions'))
                ->where($db->quoteName('type') . ' = ' . $db->quote('module'))
                ->where($db->quoteName('element') . ' = ' . $db->quote($element));
            $extensionId = (int) $db->setQuery($query)->loadResult();

            if ($extensionId > 0) {
                $query = $db->getQuery(true)
                    ->delete($db->quoteName('#__update_sites_extensions'))
                    ->where($db->quoteName('extension_id') . ' = ' . $extensionId);
                $db->setQuery($query)->execute();

                $query = $db->getQuery(true)
                    ->delete($db->quoteName('#__extensions'))
                    ->where($db->quoteName('extension_id') . ' = ' . $extensionId);
                $db->setQuery($query)->execute();
            }

            $modulePath = JPATH_SITE . '/modules/' . $element;
            if (is_dir($modulePath)) {
                Folder::delete($modulePath);
            }
        }
    }

    private function cleanRetainedPluginParams(): void
    {
        $db = Factory::getContainer()->get(DatabaseInterface::class);
        $keys = [
            'gmapfp_directions', 'gmapfp_street_view', 'gmapfp_traffic', 'gmapfp_trafic',
            'gmapfp_clustering', 'gmapfp_clustering_styles', 'gmapfp_clustering_zmax',
            'gmapfp_clustering_gridSize', 'gmapfp_showCoverageOnHover', 'gmapfp_style',
        ];

        foreach ([['gmapfp-map', 'google'], ['gmapfp-map', 'openstreet']] as [$folder, $element]) {
            $query = $db->getQuery(true)
                ->select([$db->quoteName('extension_id'), $db->quoteName('params')])
                ->from($db->quoteName('#__extensions'))
                ->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
                ->where($db->quoteName('folder') . ' = ' . $db->quote($folder))
                ->where($db->quoteName('element') . ' = ' . $db->quote($element));
            $extension = $db->setQuery($query)->loadObject();

            if (!$extension) {
                continue;
            }

            $params = new Registry($extension->params);
            foreach ($keys as $key) {
                $params->remove($key);
                $params->remove('gmapfp_plug_config.' . $key);
            }

            $query = $db->getQuery(true)
                ->update($db->quoteName('#__extensions'))
                ->set($db->quoteName('params') . ' = ' . $db->quote((string) $params))
                ->where($db->quoteName('extension_id') . ' = ' . (int) $extension->extension_id);
            $db->setQuery($query)->execute();
        }
    }

    private function log(string $message): void
    {
        $line = '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL;
        @file_put_contents(JPATH_ADMINISTRATOR . '/logs/gmapfp_migration.log', $line, FILE_APPEND);
    }
}
