<?php
/**
 * @package         CDN for Joomla!
 * @version         7.3.6PRO
 * 
 * @author          Peter van Westen <info@regularlabs.com>
 * @link            https://regularlabs.com
 * @copyright       Copyright © 2025 Regular Labs All Rights Reserved
 * @license         GNU General Public License version 2 or later
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory as JFactory;
use Joomla\Database\DatabaseInterface as JDatabaseInterface;
use Joomla\Filesystem\File as JFile;
use Joomla\Filesystem\Folder as JFolder;

class PlgSystemCDNForJoomlaInstallerScript
{
    public function postflight($install_type, $adapter)
    {
        if ( ! in_array($install_type, ['install', 'update']))
        {
            return true;
        }

        self::deleteJoomla3Files();
        self::fixOldConfig();

        return true;
    }

    private static function delete($files = [])
    {
        foreach ($files as $file)
        {
            if (is_dir($file))
            {
                JFolder::delete($file);
            }

            if (is_file($file))
            {
                JFile::delete($file);
            }
        }
    }

    private static function deleteJoomla3Files()
    {
        self::delete(
            [
                JPATH_SITE . '/plugins/system/cdnforjoomla/vendor',
            ]
        );
    }

    private static function fixOldConfig()
    {
        $params = self::getConfig();

        if (empty($params))
        {
            return;
        }

        if (empty($params->cdn))
        {
            return;
        }

        $params->cdns = (object) [];

        for ($i = 0; $i <= 4; $i++)
        {
            $old_setid = ! $i ? '' : '_' . (int) ($i + 1);

            if ($i && ! $params->{'use_extra' . $old_setid})
            {
                continue;
            }

            if (empty($params->cdns->{'cdn' . $i}))
            {
                $params->cdns->{'cdn' . $i} = (object) [
                    'cdn'                   => $params->{'cdn' . $old_setid} ?? '',
                    'root'                  => $params->{'root' . $old_setid} ?? '/',
                    'filetypes'             => $params->{'filetypes' . $old_setid} ?? 'css,js,bmp,gif,jpg,jpeg,ico,png,tif,tiff,svg,doc,docx,odt,pdf,rtf,txt',
                    'ignorefiles'           => $params->{'ignorefiles' . $old_setid} ?? '',
                    'enable_in_scripts'     => $params->{'enable_in_scripts' . $old_setid} ?? 1,
                    'protocol'              => $params->{'protocol' . $old_setid} ?? 'same',
                    'use_relative_protocol' => $params->{'use_relative_protocol' . $old_setid} ?? 1,
                    'web_protocol'          => $params->{'web_protocol' . $old_setid} ?? 'both',
                    'enable_versioning'     => $params->{'enable_versioning' . $old_setid} ?? 0,
                    'versioning_filetypes'  => $params->{'versioning_filetypes' . $old_setid} ?? 'css,js',
                ];
            }

            unset($params->{'cdn' . $old_setid});
            unset($params->{'root' . $old_setid});
            unset($params->{'filetypes' . $old_setid});
            unset($params->{'ignorefiles' . $old_setid});
            unset($params->{'enable_in_scripts' . $old_setid});
            unset($params->{'protocol' . $old_setid});
            unset($params->{'use_relative_protocol' . $old_setid});
            unset($params->{'web_protocol' . $old_setid});
            unset($params->{'enable_versioning' . $old_setid});
            unset($params->{'versioning_filetypes' . $old_setid});
        }

        self::saveConfig($params);
    }

    private static function getConfig()
    {
        $db = JFactory::getContainer()->get(JDatabaseInterface::class);

        $query = $db->getQuery(true)
            ->select($db->quoteName('params'))
            ->from($db->quoteName('#__extensions'))
            ->where($db->quoteName('element') . ' = ' . $db->quote('cdnforjoomla'))
            ->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
            ->where($db->quoteName('folder') . ' = ' . $db->quote('system'));
        $db->setQuery($query);

        $params = $db->loadResult();

        return json_decode($params ?: '{}');
    }

    private static function saveConfig($params)
    {
        $db = JFactory::getContainer()->get(JDatabaseInterface::class);

        if (is_object($params))
        {
            $params = json_encode($params);
        }

        $query = $db->getQuery(true)
            ->update($db->quoteName('#__extensions'))
            ->set($db->quoteName('params') . ' = ' . $db->quote($params))
            ->where($db->quoteName('element') . ' = ' . $db->quote('cdnforjoomla'))
            ->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
            ->where($db->quoteName('folder') . ' = ' . $db->quote('system'));
        $db->setQuery($query);
        $db->execute();
    }
}
