<?php
/**
* @package      ui/Theme-Builder Lite
* @author       Stephan W.
* @author url   https://www.ui-themebuilder.com/
* @copyright Copyright (C) 2021 ui-themebuilder.com, All rights reserved.
* @developer Stephan Wittling - https://www.ui-themebuilder.com/

*               ui/Theme-Builder Lite is distributed in the hope that it will be useful,
*               but WITHOUT ANY WARRANTY; without even the implied warranty of
*               MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*               See the GNU General Public License for more details.

* @license      http://www.gnu.org/licenses/gpl.html GNU/GPL
*********************************************************************************/
// No direct access
defined ('_JEXEC') or die ('Restricted access');


use Joomla\CMS\Application\ApplicationHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Table\Table;
use Joomla\CMS\Installer\Adapter\PackageAdapter;

class Pkg_uithemebuilderLiteInstallerScript {

	/**
	 * Minimum Joomla version to check
	 *
	 * @var    string
	 * @since  v.0.0.55
	 */
	private $minimumJoomlaVersion = '5.0';

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


	public function install($parent) {

		$db    = Factory::getDbo();

		$query = $db->getQuery(true)->update('#__template_styles')->set('home = 0')->where('`client_id` = 0')->where('`home` = 1');
		$db->setQuery($query)->execute();
		$query = $db->getQuery(true)->update('#__template_styles')->set('home = 1')->where('`client_id` = 0')->where('`template` = ' . $db->quote('uithemebuilder'));
		$db->setQuery($query)->execute();

		return true;

	}

	public function uninstall($parent) {

		$db    = Factory::getDbo();

		$query = $db->getQuery(true)->update('#__template_styles')->set('home = 0')->where('`client_id` = 0')->where('`home` = 1');
		$db->setQuery($query)->execute();
		$query = $db->getQuery(true)->update('#__template_styles')->set('home = 0')->where('`client_id` = 0')->where('`template` = ' . $db->quote('uithemebuilder'));
		$db->setQuery($query)->execute();

		// JFormFieldAutoorder::cleanCache(true);
	}

	public function update($parent) {

	}

	public function preflight($type, $parent) {

		// Do not run on uninstall.
		if ($type === 'uninstall')
		{
			return true;
		}

		// delete warp folder
		jimport('joomla.filesystem.folder');
		$warp = JPATH_ROOT . '/templates/uithemebuilder/warp';
		if (file_exists($warp)) {
			JFolder::delete($warp);
		}

	}


	/**
	 * method to run after an install/update/uninstall method
	 *
	 * @return void
	 */
	public function postflight($type, $parent) {

		$db    = Factory::getDbo();
		$query = $db->getQuery(true);

		$status = new stdClass;
		$status->packages = array();

		$query->update('#__extensions')->set('enabled = 1')->where('element = ' . $db->quote('uithemebuilderlite'));
		$db->setQuery($query);
		$db->execute();
		$conf    = Factory::getConfig();
		$options = array(
			'defaultgroup' => '',
			'storage' => $conf->get('cache_handler', ''),
			'caching' => true,
			'cachebase' => $conf->get('cache_path', JPATH_SITE . '/cache')
		);
		$cache   = JCache::getInstance('', $options);
		$data    = $cache->getAll();
		if ($data) {
			foreach ($data as $item) {
				$cache->clean($item->group);
			}
		}
		$cache = Factory::getCache('');
		$cache->gc();

		$conf->set('debug', false);

		if ($type == 'update') {
			// JFactory::getApplication()->enqueueMessage('Test Update.', 'error');
		}

		$this->saveContentTypes();

	}


	/**
	 * Adding content_type for tags.
	 *
	 * @return  integer|boolean  One Administrator ID.
	 *
	 * @since   v0.0.55
	 */
	private function saveContentTypes() {
		$table = Table::getInstance('Contenttype', 'JTable');

		$table->load(array('type_alias' => 'com_uithemebuilderlite.page'));

		$tablestring = '{
			"special": {
			  "dbtable": "#__uithemebuilderlite",
			  "key": "id",
			  "type": "uiTheme-Builder Lite",
			  "prefix": "SW\\Component\\uiThemeBuilderLite\\Administrator\\Table\\",
			  "config": "array()"
			},
			"common": {
			  "dbtable": "#__ucm_content",
			  "key": "ucm_id",
			  "type": "Corecontent",
			  "prefix": "JTable",
			  "config": "array()"
			}
		  }';

		$contenthistory = '{"formFile":"administrator\/components\/com_uithemebuilderlite\/forms\/page.xml", "hideFields":["created_by","modified","content","id","modified_by","hits"], "ignoreChanges":["published", "checked_out", "checked_out_time", "hits"], "convertToInt":["publish_up", "publish_down"], "displayLookup":[{"sourceColumn":"created_user_id","targetTable":"#__users","targetColumn":"id","displayColumn":"name"}, {"sourceColumn":"access","targetTable":"#__viewlevels","targetColumn":"id","displayColumn":"title"},{"sourceColumn":"modified_user_id","targetTable":"#__users","targetColumn":"id","displayColumn":"name"},{"sourceColumn":"parent_id","targetTable":"#__categories","targetColumn":"id","displayColumn":"title"}]}';

		$contenttype = array();
		$contenttype['type_id'] = ($table->type_id) ? $table->type_id : 0;
		$contenttype['type_title'] = 'uiTheme-Builder Lite';
		$contenttype['type_alias'] = 'com_uithemebuilderlite.page';
		$contenttype['table'] = $tablestring;
		$contenttype['rules'] = '';
		$contenttype['router'] = '';
		$contenttype['field_mappings'] = '';
		$contenttype['content_history_options'] = trim($contenthistory);

		$table->save($contenttype);

		return;
	}


	/**
	 * Retrieve the admin user id.
	 *
	 * @return  integer|boolean  One Administrator ID.
	 *
	 * @since   3.2
	 */
	private function getAdminId() {
		$db    = Factory::getDbo();
		$query = $db->getQuery(true);

		// Select the admin user ID
		$query
			->clear()
			->select($db->quoteName('u') . '.' . $db->quoteName('id'))
			->from($db->quoteName('#__users', 'u'))
			->join(
				'LEFT',
				$db->quoteName('#__user_usergroup_map', 'map')
				. ' ON ' . $db->quoteName('map') . '.' . $db->quoteName('user_id')
				. ' = ' . $db->quoteName('u') . '.' . $db->quoteName('id')
			)
			->join(
				'LEFT',
				$db->quoteName('#__usergroups', 'g')
				. ' ON ' . $db->quoteName('map') . '.' . $db->quoteName('group_id')
				. ' = ' . $db->quoteName('g') . '.' . $db->quoteName('id')
			)
			->where(
				$db->quoteName('g') . '.' . $db->quoteName('title')
				. ' = ' . $db->quote('Super Users')
			);

		$db->setQuery($query);
		$id = $db->loadResult();

		if (!$id || $id instanceof \Exception) {
			return false;
		}

		return $id;
	}

}