<?php
/**
 * @package         Cache Cleaner
 * @version         9.7.5PRO
 * 
 * @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\Installer\Manifest\PackageManifest as JPackageManifest;
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 PlgSystemCacheCleanerInstallerScript
{
    public function postflight($install_type, $adapter)
    {
        if ( ! in_array($install_type, ['install', 'update']))
        {
            return true;
        }

        self::deleteJoomla3Files();
        self::deleteOldFiles();
        self::publishConsolePlugin();

        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 publishConsolePlugin()
    {
        $manifest = new JPackageManifest(JPATH_PLUGINS . '/console/cachecleaner/cachecleaner.xml');
        $current_version = trim($manifest->version ?? '');

        if(version_compare($current_version, '9.4.0') > 0) {
            return;
        }

        $db = JFactory::getContainer()->get(JDatabaseInterface::class);

        $query = $db->getQuery(true)
            ->update('#__extensions')
            ->set($db->quoteName('enabled') . ' = 1')
            ->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
            ->where($db->quoteName('folder') . ' = ' . $db->quote('console'))
            ->where($db->quoteName('element') . ' = ' . $db->quote('cachecleaner'));
        $db->setQuery($query);
        $db->execute();
    }

    private static function deleteJoomla3Files()
    {
        self::delete(
            [
                JPATH_SITE . '/media/cachecleaner/images',
                JPATH_SITE . '/media/cachecleaner/less',
                JPATH_SITE . '/plugins/system/cachecleaner/vendor',
                JPATH_SITE . '/plugins/system/cachecleaner/src/Cache/JotCache.php',
                JPATH_SITE . '/plugins/system/cachecleaner/src/Cache/JotCacheMainModelMain.php',
            ]
        );
    }

    private static function deleteOldFiles()
    {
        self::delete(
            [
                JPATH_SITE . '/plugins/system/cachecleaner/src/Clean.php',
                JPATH_SITE . '/plugins/system/cachecleaner/src/Helper.php',
                JPATH_SITE . '/plugins/system/cachecleaner/src/Plugin.php',
                JPATH_SITE . '/plugins/system/cachecleaner/src/Protect.php',
            ]
        );
    }
}
