<?php

use Joomla\CMS\Factory;

// use Joomla\Database\DatabaseInterface;
// use Joomla\CMS\Installer\InstallerAdapter;

class pkg_mefisassetbridgeInstallerScript
{
    // /**
    //  * @var InstallerAdapter
    //  */
    // protected $adapter;

    // /**
    //  * @var DatabaseInterface
    //  */
    // protected $database;
    protected $minPhp      = '7.4.0';
    protected $minYootheme = '4.0.0';
    protected $minJoomla   = '4.0.0';

    public function preflight()
    {
        // verify joomls
        if (! $this->verifyJoomla()) {
            return false;
        }
        // verify yootheme
        if (! $this->verifyYooTheme()) {
            return false;
        }
        // verify PHP
        if (! $this->verifyPHP()) {
            return false;
        }

        // make sure plugin is not running during installation
        $this->changePluginState(0);

        return true;
    }
    public function postflight($type, $parent)
    {
        $this->changePluginState(1);
    }
    protected function verifyYooTheme()
    {
        $message = "<p>This application requires Yootheme Pro, version {$this->minYootheme} or higher!</p>";

        $yoothemeXml = JPATH_ROOT . '/plugins/system/yootheme/yootheme.xml';

        if (! is_file($yoothemeXml)) {
            Factory::getApplication()->enqueueMessage($message, 'warning');
            return false;
        }

        $manifest = simplexml_load_file($yoothemeXml);
        if (! $manifest || $manifest->getName() !== 'extension' || empty($manifest->version)) {
            Factory::getApplication()->enqueueMessage($message, 'warning');
            return false;
        }

        if (version_compare((string) $manifest->version, $this->minYootheme, '<')) {
            Factory::getApplication()->enqueueMessage($message, 'warning');
            return false;
        }

        return true;
    }

    protected function verifyJoomla()
    {
        if (version_compare(JVERSION, $this->minJoomla, '>=')) {
            return true;
        }

        $message = "This application requires Joomla version {$this->minJoomla} or later.";

        Factory::getApplication()->enqueueMessage("<p>" . $message . "</p>", 'warning');

        return false;
    }

    protected function verifyPHP()
    {
        if (version_compare(PHP_VERSION, $this->minPhp, '>=')) {
            return true;
        }

        Factory::getApplication()->enqueueMessage("<p>This application requires PHP version {$this->minPhp} or later.</p>", 'warning');

        return false;
    }
    protected function changePluginState($state = 1)
    {
        Factory::getDbo()
            ->setQuery(
                "UPDATE #__extensions SET enabled = {$state}, ordering = 999 WHERE type = 'plugin' AND folder = 'system' AND element = 'mefisassetbridge'",
            )
            ->execute();
    }
}
