<?php

/**
 * @package     Joomla.Administrator
 * @subpackage  com_formea
 *
 * @copyright   Copyright (C) 2010-2025 Feseur Sdn Bhd. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @version     1.3.0
 */
defined('_JEXEC') or die;

use Joomla\CMS\Date\Date;
use Joomla\CMS\Factory;
use Joomla\CMS\Installer\InstallerAdapter;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Log\Log;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\WebAsset\WebAssetManager;
use Joomla\Database\DatabaseDriver;

/**
 * Script file of Formea Component
 *
 * @since  1.0.0
 */
class pkg_formeaInstallerScript
{
	private $formeaVersion = '1.3.0';
	/**
	 * Minimum Joomla version to check
	 *
	 * @var    string
	 * @since  1.0.0
	 */
	private $minimumJoomlaVersion = '4.0';

	/**
	 * Minimum PHP version to check
	 *
	 * @var    string
	 * @since  1.0.0
	 */
	private $minimumPHPVersion = JOOMLA_MINIMUM_PHP;


	/**
	 * Method to install the extension
	 *
	 * @param   InstallerAdapter  $parent  The class calling this method
	 *
	 * @return  boolean  True on success
	 *
	 * @since  1.0.0
	 */
	public function install($parent): bool
	{
		$this->updateDatabaseSchema(false);
		$this->getWelcomeMessage(false);

		return true;
	}

	/**
	 * Method to uninstall the extension
	 *
	 * @param   InstallerAdapter  $parent  The class calling this method
	 *
	 * @return  boolean  True on success
	 *
	 * @since  1.0.0
	 */
	public function uninstall($parent): bool
	{
		echo Text::_('COM_FORMEA_INSTALLERSCRIPT_UNINSTALL');

		return true;
	}

	/**
	 * Method to update the extension
	 *
	 * @param   InstallerAdapter  $parent  The class calling this method
	 *
	 * @return  boolean  True on success
	 *
	 * @since  1.0.0
	 *
	 */
	public function update($parent): bool
	{
		$this->updateDatabaseSchema(true);
		$this->getWelcomeMessage(true);

		return true;
	}

	/**
	 * Function called before extension installation/update/removal procedure commences
	 *
	 * @param   string            $type    The type of change (install, update or discover_install, not uninstall)
	 * @param   InstallerAdapter  $parent  The class calling this method
	 *
	 * @return  boolean  True on success
	 *
	 * @throws Exception
	 * @since  1.0.0
	 *
	 */
	public function preflight($type, $parent): bool
	{
		if ($type !== 'uninstall') {
			// Check for the minimum PHP version before continuing
			if (!empty($this->minimumPHPVersion) && version_compare(PHP_VERSION, $this->minimumPHPVersion, '<')) {
				Log::add(
					Text::sprintf('JLIB_INSTALLER_MINIMUM_PHP', $this->minimumPHPVersion),
					Log::WARNING,
					'jerror'
				);

				return false;
			}

			// Check for the minimum Joomla version before continuing
			if (!empty($this->minimumJoomlaVersion) && version_compare(JVERSION, $this->minimumJoomlaVersion, '<')) {
				Log::add(
					Text::sprintf('JLIB_INSTALLER_MINIMUM_JOOMLA', $this->minimumJoomlaVersion),
					Log::WARNING,
					'jerror'
				);

				return false;
			}
		}

		return true;
	}

	/**
	 * Function called after extension installation/update/removal procedure commences
	 *
	 * @param   string            $type    The type of change (install, update or discover_install, not uninstall)
	 * @param   InstallerAdapter  $parent  The class calling this method
	 *
	 * @return  boolean  True on success
	 *
	 * @since  1.0.0
	 *
	 */
	public function postflight($type, $parent)
	{
		if ($type == 'install') {
			//Upload basic elements, themes
			//$this->installBasicExtensions();
		}

		return true;
	}

	public function updateDatabaseSchema($isUpdate)
	{
		$container = Factory::getContainer();
		/** @var DatabaseDriver $db */
		$db    = $container->get('DatabaseDriver');
		$query = $db->getQuery(true);
		if ($isUpdate) {
			$sql = 'ALTER TABLE `#__formea_submission_data` CHANGE `link_path` `link_path` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL';
			$db->setQuery($sql);
			$db->execute();

			$query->clear();
			//check for dir_path
			$submissionDataColumns = $db->getTableColumns('#__formea_submission_data');
			if (!isset($submissionDataColumns['dir_path'])) {
				$sql = 'ALTER TABLE `#__formea_submission_data` ADD `dir_path` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL AFTER `link_path`;';
				$db->setQuery($sql);
				$db->execute();
			}
		}
	}

	public function getWelcomeMessage($isUpdate)
	{
		$app  = Factory::getApplication();
		$lang = $app->getLanguage();
		$lang->load('com_formea', JPATH_ADMINISTRATOR, 'en_GB', true);
		$app = Factory::getApplication();
		/** @var WebAssetManager $wa */
		$wa        = $app->getDocument()->getWebAssetManager();
		$registrar = $wa->getRegistry();
		$registrar->addRegistryFile('media/com_formea/joomla.asset.json');
		$wa->registerAndUseStyle('com_formea.admin-formea' . Uri::root() . 'media/com_formea/css/admin.min.css');
		//$wa->useStyle('com_formea.admin-formea');

		$svg                = file_get_contents(JPATH_ROOT . '/media/com_formea/img/logo-icon.svg');
		$background         = Uri::root() . 'media/com_formea/img/intro-bg.webp';
		$version            = Text::sprintf('COM_FORMEA_VERSION_S', $this->formeaVersion);
		$welcomeMsg         = Text::_('COM_FORMEA_THANK_YOU_WELCOME');
		$onBoardMessage     = Text::_('COM_FORMEA_ONBOARD_MESSAGE');
		$docLink            = Text::_('COM_FORMEA_DOCUMENTATION_LINK');
		$supportLink        = Text::_('COM_FORMEA_SUPPORT_LINK');
		$requestFeatureLink = Text::_('COM_FORMEA_FEATURE_REQUEST_LINK');
		$update             = '';
		if ($isUpdate) {
			$update = ' <p><b class="text-success">' . Text::_('COM_FORMEA_UPDATED_SUCCESSFULLY') . '</b></p>';
		}

		$html = <<<HTML
 <div class="d-block card card-body p-0">
        <div class="row">
          <div class="col-4">
            <div class="d-flex flex-column h-100"
                 style="background: url('$background');background-repeat: no-repeat;background-size: cover">
              <div class="ps-3 pt-3">
                <div style="width: 60px;min-width:60px;">$svg</div>
              </div>
              <div class="mt-auto pb-1">
                <div class="small d-inline-block"
                     style="margin-left:5px;padding:2px 5px;background-color: rgba(255,255,255,.7)">
                 $version
                </div>
              </div>
            </div>
          </div>
          <div class="col-8">
            <div class="d-block px-3 pb-3 pt-4">
              <h5>$welcomeMsg</h5>
              $update
              $onBoardMessage
              <div class="d-flex gap-2 py-3">
                $docLink
                <div class="vr"></div>
                $supportLink
                <div class="vr"></div>
                $requestFeatureLink
              </div>
            </div>
          </div>
        </div>
      </div>
HTML;

		echo $html;
	}
}
