<?php

/**
 * @package     VP Neoteric Template Package
 *
 * @author      Abhishek Das <info@virtueplanet.com>
 * @link        https://www.virtueplanet.com
 * @copyright   Copyright (C) 2023-2025 Virtueplanet Services LLP. All Rights Reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt

 * @phpcs:disable PSR1.Classes.ClassDeclaration.MissingNamespace
 * @phpcs:disable PSR1.Classes.PascalCase
 */

use Joomla\CMS\Factory;
use Joomla\CMS\Installer\InstallerAdapter;
use Joomla\CMS\Installer\InstallerScript;
use Joomla\Database\DatabaseInterface;
use Joomla\Database\ParameterType;
use Joomla\Registry\Registry;

// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects

/**
 * VP Neoteric Template Package Script
 *
 * @since  1.0
 */
// phpcs:ignore
class Pkg_VP_NeotericInstallerScript extends InstallerScript
{
    /**
     * VirtuePlanet product ID required for Live Update
     *
     * @var  integer
     */
    protected const PID = 27;

    /**
     * Extension script constructor.
     */
    public function __construct()
    {
        $this->minimumJoomla   = '4.2';
        $this->minimumPhp      = '7.2.5';
        $this->allowDowngrades = true;
    }

    /**
     * Called on installation
     *
     * @param   InstallerAdapter  $parent  The object responsible for running this script
     *
     * @return  boolean  True on success
     */
    public function install($parent)
    {
        $app     = Factory::getApplication();
        $element = $parent->getElement();

        if (!$this->updatePackagePid($element)) {
            $app->enqueueMessage('Package ID information update failed. Template Live Update system may not work.');
        }

        if (!$this->enableFramework()) {
            $app->enqueueMessage('Please enable "System - VP Prime Framework" plugin.');
        }

        return true;
    }

    /**
     * Called on update
     *
     * @param   InstallerAdapter  $parent  The object responsible for running this script
     *
     * @return  boolean  True on success
     */
    public function update($parent)
    {
        $app     = Factory::getApplication();
        $element = $parent->getElement();

        if (!$this->updatePackagePid($element)) {
            $app->enqueueMessage('Package ID information update failed. Template Live Update system may not work.');
        }

        if (!$this->enableFramework()) {
            $app->enqueueMessage('Please enable "System - VP Prime Framework" plugin.');
        }

        return true;
    }

    /**
     * Method to enable VP Prime Framework Plugin
     */
    protected function enableFramework(): bool
    {
        $db    = Factory::getContainer()->get(DatabaseInterface::class);
        $query = $db->getQuery(true);

        $query->select($db->quoteName('extension_id'))
            ->from($db->quoteName('#__extensions'))
            ->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
            ->where($db->quoteName('folder') . ' = ' . $db->quote('system'))
            ->where($db->quoteName('element') . ' = ' . $db->quote('vpprime'));

        $db->setQuery($query);

        $extension_id = $db->loadResult();

        // Plugin ID not found
        if (!$extension_id) {
            return false;
        }

        /** @var \Joomla\Component\Installer\Administrator\Extension\InstallerComponent $component **/
        $component = Factory::getApplication()->bootComponent('plugins');
        $factory   = $component->getMVCFactory();

        /** @var \Joomla\Component\Plugins\Administrator\Model\PluginModel $model */
        $model = $factory->createModel('Plugin', 'Administrator', ['ignore_requests' => true]);

        if (!$model->publish($extension_id, 1)) {
            return false;
        }

        return true;
    }

    /**
     * Method to update product ID to the package params.
     *
     * @param   string   The element of the package
     *
     * @return  boolean  False in case of failure.
     */
    protected function updatePackagePid($element): bool
    {
        $db    = Factory::getContainer()->get(DatabaseInterface::class);
        $query = $db->getQuery(true);

        $query->select($db->quoteName(['extension_id', 'params']))
            ->from($db->quoteName('#__extensions'))
            ->where($db->quoteName('type') . ' = ' . $db->quote('package'))
            ->where($db->quoteName('element') . ' = ' . $db->quote($element));

        $db->setQuery($query);

        $package = $db->loadObject();

        if (empty($package)) {
            return false;
        }

        $temp = new Registry();
        $temp->loadString($package->params);

        $params        = $temp->toArray();
        $params['pid'] = self::PID;

        $temp = new Registry();
        $temp->loadArray($params);

        $paramsString = $temp->toString();

        $query->clear()
            ->update($db->quoteName('#__extensions'))
            ->set($db->quoteName('params') . ' = :params')
            ->where($db->quoteName('extension_id') . ' = :extension_id')
            ->bind(':params', $paramsString)
            ->bind(':extension_id', $package->extension_id, ParameterType::INTEGER);

        $db->setQuery($query)->execute();

        return true;
    }
}
