<?php
/**
 * @version        1.24.0
 * @package        Joomla
 * @subpackage     Edocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2011 - 2025 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
defined('_JEXEC') or die('Direct Access to this location is not allowed.');

use Joomla\CMS\Factory;
use Joomla\Filesystem\Folder;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Path;
use Joomla\Registry\Registry;

/**
 * Change the db structure of the previous version
 *
 */

class com_edocmanInstallerScript
{

	public static $languageFiles = ['en-GB.com_edocman.ini'];

	/**
	 * Minimum PHP version
	 */
	private const MIN_PHP_VERSION = '7.4.0';

	/**
	 * Minimum Joomla version
	 */
	private const MIN_JOOMLA_VERSION = '4.2.0';

	/**
	 * Constructor
	 */
	public function __construct()
	{
		$this->app = Factory::getApplication();
	}

	function preflight($type, $parent)
	{

		if (version_compare(JVERSION, self::MIN_JOOMLA_VERSION, '<'))
		{
			Factory::getApplication()->enqueueMessage(
				'Cannot install Edocman in a Joomla! release prior to ' . self::MIN_JOOMLA_VERSION,
				'error'
			);

			return false;
		}

		if (version_compare(PHP_VERSION, self::MIN_PHP_VERSION, '<'))
		{
			Factory::getApplication()->enqueueMessage(
				'Edocman requires PHP ' . self::MIN_PHP_VERSION . '+ to work. Please contact your hosting provider, ask them to update PHP version for your hosting account.',
				'error'
			);

			return false;
		}

		
		
		if (is_dir(Path::clean(JPATH_ROOT . '/edocman')))
		{
			// Change folder permission back to 0755
			@chmod(JPATH_ROOT . '/edocman', 0755);
		}
		

		if (strtolower($type) != 'update')
		{
			return true;
		}

		foreach (self::$languageFiles as $languageFile)
		{
			if (is_file(Path::clean(JPATH_ROOT . '/language/en-GB/' . $languageFile)))
			{
				File::copy(JPATH_ROOT . '/language/en-GB/' . $languageFile, JPATH_ROOT . '/language/en-GB/bak.' . $languageFile);
			}

			if (is_file(Path::clean(JPATH_ROOT . '/administrator/language/en-GB/' . $languageFile)))
			{
				File::copy(JPATH_ROOT . '/administrator/language/en-GB/' . $languageFile, JPATH_ROOT . '/administrator/language/en-GB/bak.' . $languageFile);
			}
		}

		if (is_file(Path::clean(JPATH_ADMINISTRATOR . '/components/com_edocman/model/forms/document.xml')))
		{
			File::copy(JPATH_ADMINISTRATOR . '/components/com_edocman/model/forms/document.xml', JPATH_ADMINISTRATOR . '/components/com_edocman/model/forms/bak.document.xml');
		}
	}

	function install($parent)
	{
		self::com_install();
	}

	function update($parent)
	{
		self::com_install();
	}

	function postflight($type, $parent)
	{
		// We do not have to do anything on uninstall
		if (strtolower($type) == 'uninstall')
		{
			return;
		}
		if (strtolower($type) == 'install')
		{
			//Setup default permissions
			$db		= Factory::getContainer()->get('db');
			$query = $db->getQuery(true);
			$query->select('id')
				->from('#__assets')
				->where('name="com_edocman"');
			$db->setQuery($query);
			$assetId = (int) $db->loadResult();
			if ($assetId)
			{
				$query->clear();
				$query->update('#__assets')
					->set('rules=' . $db->quote('{"core.admin":[],"core.manage":[],"core.create":[],"core.delete":[],"core.edit":[],"core.edit.state":[],"core.edit.own":[],"edocman.download":{"1":1},"edocman.assign_documents_to_users":{"6":1,"7":1}}'))
					->where('id=' . $assetId);
				$db->setQuery($query);
				$db->execute();
			}
		}

		foreach (self::$languageFiles as $languageFile)
		{
			$registry			= new Registry;
			$backupFile			= JPATH_ROOT . '/language/en-GB/bak.' . $languageFile;
			$currentFile		= JPATH_ROOT . '/language/en-GB/' . $languageFile;
			if (is_file(Path::clean($currentFile)) && is_file(Path::clean($backupFile)))
			{
				$registry->loadFile($currentFile, 'INI');
				$currentItems	= $registry->toArray();
				$registry->loadFile($backupFile, 'INI');
				$backupItems	= $registry->toArray();
				$items			= array_merge($currentItems, $backupItems);
				$content		= "";
				foreach ($items as $key => $value)
				{
					$content	.= "$key=\"$value\"\n";
				}
				File::write($currentFile, $content);
				//Delete the backup file
				//File::delete($backupFile);
			}

			/*

			$registry			= new Registry;
			$backupFile			= JPATH_ADMINISTRATOR . '/language/en-GB/bak.' . $languageFile;
			$currentFile		= JPATH_ADMINISTRATOR . '/language/en-GB/' . $languageFile;
			if (is_file(Path::clean($currentFile)) && is_file(Path::clean($backupFile)))
			{
				$registry->loadFile($currentFile, 'INI');
				$currentItems	= $registry->toArray();
				$registry->loadFile($backupFile, 'INI');
				$backupItems	= $registry->toArray();
				$items			= array_merge($currentItems, $backupItems);
				$content		= "";
				foreach ($items as $key => $value)
				{
					$content	.= "$key=\"$value\"\n";
				}
				File::write($currentFile, $content);
			}
			*/
		}

		$backupFile				= JPATH_ADMINISTRATOR . '/components/com_edocman/model/forms/bak.document.xml';
		$currentFile			= JPATH_ADMINISTRATOR . '/components/com_edocman/model/forms/document.xml';
		if (is_file(Path::clean($currentFile)) && is_file(Path::clean($backupFile)))
		{
			//File::copy($backupFile, $currentFile);
		}

		$customCss = JPATH_ROOT . '/components/com_edocman/assets/css/custom.css';
		if (!file_exists($customCss))
		{
			$fp = fopen($customCss, 'w');
			fclose($fp);
			@chmod($customCss, 0777);
		}

		// Enable required plugins
		self::enableRequiredPlugin($type);
	}

	/**
	 * Enable the plugins which are needed for the extension to work properly
	 *
	 * @return void
	 */
	public static function enableRequiredPlugin($type = '')
	{
		$db = Factory::getContainer()->get('db');
		$query = $db->getQuery(true);

		$publishedItems = [
			'installer' => [
				'edocman',
			],
		];

		foreach ($publishedItems as $folder => $plugins)
		{
			foreach ($plugins as $plugin)
			{
				$query->clear()
					->update('#__extensions')
					->set('enabled = 1')
					->where('element = ' . $db->quote($plugin))
					->where('folder = ' . $db->quote($folder));
				$db->setQuery($query)
					->execute();
			}
		}
	}

	public static function com_install()
	{
		$db  = Factory::getDbo();
		$sql = 'SELECT COUNT(*) FROM #__edocman_configs';
		$db->setQuery($sql);
		$total = $db->loadResult();
		if (!$total)
		{
			$configSql = JPATH_ADMINISTRATOR . '/components/com_edocman/sql/config.edocman.sql';
			$sql       = file_get_contents($configSql);
			$queries   = $db->splitSql($sql);
			if (count($queries))
			{
				foreach ($queries as $query)
				{
					$query = trim($query);
					if ($query != '' && $query[0] != '#')
					{
						$db->setQuery($query);
						$db->execute();
					}
				}
			}
		}
		//Get document path config option
		$sql = 'SELECT config_value FROM #__edocman_configs WHERE config_key="documents_path"';
		$db->setQuery($sql);
		$path = $db->loadResult();
		if (!$path)
		{
			$path = JPATH_ROOT . '/edocman';
			if (!is_dir(Path::clean($path)))
			{
				//Create the folder
				Folder::create($path);
				//Copy htaccess file
				File::copy(JPATH_ADMINISTRATOR . '/components/com_edocman/htaccess.txt', $path . '/.htaccess');
			}
			$path = str_replace("\\", "/", $path);
			$sql  = 'UPDATE #__edocman_configs SET config_value="' . $path . '" WHERE config_key="documents_path"';
			$db->setQuery($sql);
			$db->execute();
		}

		$sql = "Select count(id) from #__edocman_configs where config_key like 'user_group_ids'";
		$db->setQuery($sql);
		$count = $db->loadResult();
		if((int)$count == 0){
			$db->setQuery("Insert into #__edocman_configs(id, config_key,config_value) values (NULL,'user_group_ids','1')");
			$db->execute();
		}

		$sql = "Select count(id) from #__edocman_configs where config_key like 'show_alias_form'";
		$db->setQuery($sql);
		$count = $db->loadResult();
		if((int)$count == 0){
			$db->setQuery("Insert into #__edocman_configs(id, config_key,config_value) values (NULL,'show_alias_form','1')");
			$db->execute();
		}

		$sql = "Select count(id) from #__edocman_configs where config_key like 'show_thumb_form'";
		$db->setQuery($sql);
		$count = $db->loadResult();
		if((int)$count == 0){
			$db->setQuery("Insert into #__edocman_configs(id, config_key,config_value) values (NULL,'show_thumb_form','1')");
			$db->execute();
		}

		$sql = "Select count(id) from #__edocman_configs where config_key like 'show_meta_form'";
		$db->setQuery($sql);
		$count = $db->loadResult();
		if((int)$count == 0){
			$db->setQuery("Insert into #__edocman_configs(id, config_key,config_value) values (NULL,'show_meta_form','1')");
			$db->execute();
		}

		$sql = "Select count(id) from #__edocman_configs where config_key like 'show_tag_form'";
		$db->setQuery($sql);
		$count = $db->loadResult();
		if((int)$count == 0){
			$db->setQuery("Insert into #__edocman_configs(id, config_key,config_value) values (NULL,'show_tag_form','1')");
			$db->execute();
		}

		$sql = 'SELECT config_value FROM #__edocman_configs WHERE config_key="default_sort_option"';
		$db->setQuery($sql);
		$defaultSortOption = $db->loadResult();
		if ($defaultSortOption)
		{
			$defaultSortOption = str_replace('a.', 'tbl.', $defaultSortOption);
			$sql               = "UPDATE #__edocman_configs SET config_value='$defaultSortOption' WHERE config_key='default_sort_option'";
			$db->setQuery($sql);
			$db->execute();
		}

		$fields = array_keys($db->getTableColumns('#__edocman_licenses'));
		if (!in_array('default_license', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_licenses` ADD `default_license` tinyint(1) NOT NULL DEFAULT '0' AFTER `published`;";
			$db->setQuery($sql);
			$db->execute();
		}

		$fields = array_keys($db->getTableColumns('#__edocman_categories'));
		if (in_array('directory', $fields))
		{
			//We need to update data here
			$sql = 'SELECT a.id, a.filename, c.path FROM #__edocman_documents AS a '
				. 'INNER JOIN #__edocman_document_category AS b '
				. 'ON a.id = b.document_id '
				. 'INNER JOIN #__edocman_categories AS c '
				. 'ON b.category_id = c.id ';
			$db->setQuery($sql);
			$rows = $db->loadObjectList();
			for ($i = 0, $n = count($rows); $i < $n; $i++)
			{
				$row = $rows[$i];
				if ($row->path != "")
				{
					$newFileName = $row->path . '/' . $row->filename;
					$sql         = 'UPDATE #__edocman_documents SET filename="' . $newFileName . '" WHERE id=' . $row->id;
					$db->setQuery($sql);
					$db->execute();
				}
			}
			//Now, remove the unnecessary columns
			$sql = 'ALTER TABLE #__edocman_categories DROP COLUMN `directory`';
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('auto_approval', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `auto_approval` TINYINT(1) NULL DEFAULT  '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('level', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `level` TINYINT( 4 ) NOT NULL DEFAULT '1';";
			$db->setQuery($sql);
			$db->execute();

			// Update level for categories
			$query = $db->getQuery(true);
			$query->select('id, title, parent_id');
			$query->from('#__edocman_categories');
			$query->where('published=1');
			$db->setQuery($query);
			$rows = $db->loadObjectList();
			// first pass - collect children
			if (count($rows))
			{
				$children = array();
				foreach ($rows as $v)
				{
					$pt   = $v->parent_id;
					$list = @$children[$pt] ? $children[$pt] : array();
					array_push($list, $v);
					$children[$pt] = $list;
				}

				require_once JPATH_ROOT . '/components/com_edocman/helper/helper.php';
				$list = EDocmanHelper::calculateCategoriesLevel(0, array(), $children, 4);
				foreach ($list as $id => $category)
				{
					$sql = "UPDATE #__edocman_categories SET `level`=$category->level WHERE id=$id";
					$db->setQuery($sql);
					$db->execute();
				}
			}

		}
		if (!in_array('user_ids', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `user_ids` VARCHAR( 255 ) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}


		if (!in_array('notify_group_ids', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `notify_group_ids` VARCHAR( 255 ) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('language', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `language` VARCHAR( 50 ) NULL DEFAULT  '*';";
			$db->setQuery($sql);
			$db->execute();

			$sql = 'UPDATE #__edocman_categories SET `language`="*" ';
			$db->setQuery($sql);
			$db->execute();
		}
		if (!in_array('notification_emails', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `notification_emails` VARCHAR( 255 ) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('hide_download', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `hide_download` TINYINT(1) NULL DEFAULT  '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('show_view', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `show_view` TINYINT(1) NULL DEFAULT  '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('accesspicker', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `accesspicker` TINYINT(1) NULL DEFAULT  '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('sort_option', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `sort_option` varchar(255) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('sort_direction', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `sort_direction` varchar(255) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('path', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `path` VARCHAR( 255 ) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}
	
		
		//fix issue on Joomla4 check in component
		$sql = "ALTER TABLE `#__edocman_categories` ADD INDEX(`checked_out`); ";
		$db->setQuery($sql);
		$db->execute();

		$sql = "ALTER TABLE `#__edocman_categories` CHANGE `checked_out` `checked_out` INT(10) UNSIGNED NULL DEFAULT NULL; ";
		$db->setQuery($sql);
		$db->execute();

		if (!in_array('number_documents_in_grid', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `number_documents_in_grid` tinyint(2) NULL DEFAULT  '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('number_columns', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `number_columns` tinyint(2) NULL DEFAULT  '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('css_class', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `css_class`  	varchar(50) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('documents_layout', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `documents_layout` tinyint(1) NULL DEFAULT  '2';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('menu_id', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `menu_id` int(11) NULL DEFAULT  '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		/* 1.25.4 - change gallery layout */
		$db->setQuery("Update #__edocman_categories set `category_layout` = 'gallery' where `category_layout` = 'columns'");
		$db->execute();

		if(is_file(Path::clean(JPATH_ROOT . '/components/com_edocman/view/category/tmpl/columns.php')))
		{
			File::delete(JPATH_ROOT . '/components/com_edocman/view/category/tmpl/columns.php');
		}

		if(is_file(Path::clean(JPATH_ROOT . '/components/com_edocman/view/category/tmpl/columns.xml')))
		{
			File::delete(JPATH_ROOT . '/components/com_edocman/view/category/tmpl/columns.xml');
		}

		if (!in_array('exclude_indexing', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `exclude_indexing` tinyint( 1 ) NULL DEFAULT  '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('owner_group_ids', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `owner_group_ids` VARCHAR( 255 ) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('searchable', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `searchable` TINYINT(1) DEFAULT '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('apply_owner_to_child', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_categories` ADD  `apply_owner_to_child` TINYINT(1) DEFAULT '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		//fix issue on Joomla4 check in component
		$sql = "ALTER TABLE `#__edocman_documents` ADD INDEX(`checked_out`); ";
		$db->setQuery($sql);
		$db->execute();

		$sql = "ALTER TABLE `#__edocman_documents` CHANGE `checked_out` `checked_out` INT(10) UNSIGNED NULL DEFAULT NULL; ";
		$db->setQuery($sql);
		$db->execute();

		$fields = array_keys($db->getTableColumns('#__edocman_documents'));
		if (!in_array('user_ids', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `user_ids` VARCHAR( 255 ) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}
		if (!in_array('owner_group_ids', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `owner_group_ids` VARCHAR( 255 ) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}
		if (!in_array('language', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `language` VARCHAR( 50 ) NULL DEFAULT  '*';";
			$db->setQuery($sql);
			$db->execute();

			$sql = 'UPDATE #__edocman_documents SET `language`="*" ';
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('indexed_content', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `indexed_content` TEXT NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('tags', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `tags` LONGTEXT NULL DEFAULT NULL;";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('indicators', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `indicators` VARCHAR( 50 ) NULL;";
			$db->setQuery($sql);
			$db->execute();
		}
		if (!in_array('publish_up', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `publish_up` datetime NOT NULL DEFAULT '0000-00-00 00:00:00';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('publish_down', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `publish_down` datetime NOT NULL DEFAULT '0000-00-00 00:00:00';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('params', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `params` text NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('view_url', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `view_url` varchar(255) DEFAULT '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('file_size', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `file_size` varchar(100) NOT NULL;";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('document_history', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `document_history` text NOT NULL ;";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('document_version', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `document_version` varchar(10) NOT NULL;";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('is_locked', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `is_locked` tinyint(1) NOT NULL DEFAULT '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('locked_by', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `locked_by` int(11) NOT NULL DEFAULT '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('locked_time', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `locked_time` datetime NOT NULL;";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('accesspicker', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `accesspicker` TINYINT(1) NULL DEFAULT  '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('download_limit_per_user', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `download_limit_per_user` INT(5) NULL DEFAULT  '-1';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('send_reminder', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `send_reminder` TINYINT(1) NULL DEFAULT  '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('download_password', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `download_password` VARCHAR (50) NULL DEFAULT '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('exclude_indexing', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `exclude_indexing` tinyint(1) NULL DEFAULT '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('missing_files', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `missing_files` tinyint(1) NULL DEFAULT '0';";
			$db->setQuery($sql);
			$db->execute();
		}
		if (!in_array('checked_on', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `checked_on` int(11) NULL DEFAULT '0';";
			$db->setQuery($sql);
			$db->execute();
		}
		if (!in_array('disable_download', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `disable_download` int(11) NULL DEFAULT '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('hide_search_engines', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `hide_search_engines` tinyint(1) NULL DEFAULT '0';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('cloud_provider', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_documents` ADD  `cloud_provider` varchar(50) NULL DEFAULT '';";
			$db->setQuery($sql);
			$db->execute();
		}

		$sql = "SHOW INDEX FROM `#__edocman_documents` WHERE Index_type = 'FULLTEXT'";
		$db->setQuery($sql);
		$indexes = $db->loadObjectList();

		$indexedContentFound = false;

		if ($indexes) {
			foreach ($indexes as $index) {
				if ($index->Column_name === 'indexed_content') {
					$indexedContentFound = true;
					break;
				}
			}
		}


		if(!$indexedContentFound)
		{
			//$sql = "ALTER TABLE `#__edocman_documents` CHANGE `indexed_content` `indexed_content` TEXT DEFAULT NULL; ";
			//$db->setQuery($sql);
			//$db->execute();

			$sql = "SHOW INDEX FROM `#__edocman_documents` WHERE Key_name = 'ft_document_title_data'";
			$db->setQuery($sql);
			$indexExists = $db->loadResult();

			if (!$indexExists) {
				
				try
				{
					$sql = "ALTER TABLE `#__edocman_documents` ADD FULLTEXT INDEX ft_document_title_data (title, short_description, description, indexed_content);";
					$db->setQuery($sql);
					$db->execute();
				}
				catch (Exception $e) {
					$sql = "ALTER TABLE `#__edocman_documents` ADD FULLTEXT INDEX ft_document_title_data (title, short_description, description);";
					$db->setQuery($sql);
					$db->execute();
				}

			}
		}

		$fields = array_keys($db->getTableColumns('#__edocman_document_category'));
		if (!in_array('is_main_category', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_document_category` ADD  `is_main_category` TINYINT NOT NULL DEFAULT  '0' ;";
			$db->setQuery($sql);
			$db->execute();

			$sql = 'UPDATE #__edocman_document_category SET is_main_category=1';
			$db->setQuery($sql);
			$db->execute();
		}

		#Add index to improve the speed
		$sql = 'SHOW INDEX FROM #__edocman_document_category';
		$db->setQuery($sql);
		$rows   = $db->loadObjectList();
		$fields = array();
		for ($i = 0, $n = count($rows); $i < $n; $i++)
		{
			$row      = $rows[$i];
			$fields[] = $row->Column_name;
		}
		if (!in_array('document_id', $fields))
		{
			$sql = 'ALTER TABLE `#__edocman_document_category` ADD INDEX ( `document_id` )';
			$db->setQuery($sql);
			$db->execute();
		}
		if (!in_array('category_id', $fields))
		{
			$sql = 'ALTER TABLE `#__edocman_document_category` ADD INDEX ( `category_id` )';
			$db->setQuery($sql);
			$db->execute();
		}
		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__edocman_unsubscribe_emails` (
						  `id` int(11) NOT NULL AUTO_INCREMENT,
						  `email` varchar(255) NOT NULL,
						  PRIMARY KEY (`id`)
						)  AUTO_INCREMENT=1 ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;");
		$db->execute();

		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__edocman_ratings` (
						  `id` int(11) NOT NULL AUTO_INCREMENT,
						  `document_id` int(11) DEFAULT NULL,
						  `user_id` int(11) DEFAULT NULL,
						  `rate` tinyint(1) UNSIGNED DEFAULT NULL,
						  `rated_on` date DEFAULT NULL,
						  PRIMARY KEY (`id`)
						)  AUTO_INCREMENT=1 ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;");
		$db->execute();

		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__edocman_menus` (
						  `id` int(11) NOT NULL AUTO_INCREMENT,
						  `menu_name` varchar(255) DEFAULT NULL,
						  `menu_parent_id` int(11) DEFAULT NULL,
						  `menu_link` varchar(255) DEFAULT NULL,
						  `published` tinyint(1) UNSIGNED DEFAULT NULL,
						  `ordering` int(11) DEFAULT NULL,
						  `menu_class` varchar(255) DEFAULT NULL,
						  PRIMARY KEY (`id`)
						)  AUTO_INCREMENT=1 ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;");
		$db->execute();

		$db->setQuery("TRUNCATE TABLE `#__edocman_menus`");
		$db->execute();
		
		$db->setQuery("INSERT INTO `#__edocman_menus` (`id`, `menu_name`, `menu_parent_id`, `menu_link`, `published`, `ordering`, `menu_class`) VALUES
					(11, 'EDOCMAN_DASHBOARD', 0, 'index.php?option=com_edocman&view=dashboard', 1, 1, 'home'),
					(12, 'EDOCMAN_CATEGORIES', 0, 'index.php?option=com_edocman&view=categories', 1, 3, 'folder '),
					(13, 'EDOCMAN_DOCUMENTS', 0, 'index.php?option=com_edocman&view=documents', 1, 4, 'book'),
					(14, 'EDOCMAN_LICENSE', 15, 'index.php?option=com_edocman&view=licenses', 1, 4, 'shuffle'),
					(15, 'EDOCMAN_OTHERS', 0, '', 1, 6, 'puzzle-piece'),
					(16, 'EDOCMAN_BATCH_UPLOAD', 31, 'index.php?option=com_edocman&view=upload', 1, 1, 'tasks'),
					(17, 'EDOCMAN_BULK_IMPORT', 31, 'index.php?option=com_edocman&view=import', 1, 2, 'upload'),
					(18, 'EDOCMAN_DOWNLOADLOGS', 32, 'index.php?option=com_edocman&view=downloadlogs', 1, 3, 'download'),
					(19, 'EDOCMAN_TRANSLATION', 15, 'index.php?option=com_edocman&view=language', 1, 4, 'flag'),
					(20, 'EDOCMAN_REMOVE_ORPHAN_DOCUMENTS', 33, 'index.php?option=com_edocman&view=documents&layout=remove_orphan', 1, 5, 'delete'),
					(21, 'EDOCMAN_SEF_OPTIMIZE', 33, 'index.php?option=com_edocman&view=sefoptimize', 1, 6, 'link'),
					(22, 'EDOCMAN_CONFIGURATION', 0, 'index.php?option=com_edocman&view=configuration', 1, 2, 'cog'),
					(23, 'EDOCMAN_CLEAN_EDOCMAN_TEMP_FOLDER', 33, 'index.php?option=com_edocman&task=cleantmpfolder', 1, 7, 'delete'),
					(24, 'EDOCMAN_IMPORT_CATEGORIES_THROUGH_CSV', 31, 'index.php?option=com_edocman&view=categoryimport', 1, 8, 'upload'),
					(25, 'EDOCMAN_DOCUMENT_RATING', 32, 'index.php?option=com_edocman&view=ratings', 1, 9, 'star'),
					(26, 'EDOCMAN_DOWNLOAD_CHART', 32, 'index.php?option=com_edocman&view=chart', 1, 10, 'chart'),
					(27, 'EDOCMAN_EXPORT_DOCUMENTS', 31, 'index.php?option=com_edocman&task=document.export', 1, 11, 'download'),
					(28, 'EDOCMAN_SEARCH_TERMS', 32, 'index.php?option=com_edocman&view=terms', 1, 12, 'search'),
					(29, 'EDOCMAN_REMOVE_DOCUMENTS_ROOT_PATH', 33, 'index.php?option=com_edocman&view=deletedocuments', 1, 7, 'delete'),
					(30, 'EDOCMAN_MANAGE_TAGS', 15, 'index.php?option=com_edocman&view=tags', 1, 13, 'tags'),
					(31, 'EDOCMAN_IMPORT_EXPORT', 0, NULL, 1, 5, 'database'),
					(32, 'EDOCMAN_REPORT', 0, NULL, 1, 8, 'pie'),
					(33, 'EDOCMAN_MAINTENANCE_TOOLS', 0, NULL, 1, 7, 'tools'),
					(34, 'EDOCMAN_DATABASE_TOOLS', 31, 'index.php?option=com_edocman&view=exportimport', 1, 8, 'database');");
		$db->execute();

		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__edocman_document_versions` (
				  `id` int NOT NULL AUTO_INCREMENT,
				  `document_id` int NOT NULL,
				  `version_number` int NOT NULL,
				  `file_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
				  `file_url` varchar(1024) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
				  `file_size` int DEFAULT NULL,
				  `created_by` int DEFAULT NULL,
				  `created_at` datetime DEFAULT NULL,
				  `note` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
				  `cloud_provider` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
				  `cloud_file_id` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
				  PRIMARY KEY (`id`),
				  KEY `document_id` (`document_id`)
				) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
		$db->execute();

		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__edocman_export_import_log` (
				  `id` int NOT NULL AUTO_INCREMENT,
				  `user_id` int NOT NULL DEFAULT '0',
				  `type` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
				  `details` text COLLATE utf8mb4_unicode_ci,
				  `status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'success',
				  `created_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
				  PRIMARY KEY (`id`),
				  KEY `idx_user_id` (`user_id`),
				  KEY `idx_type` (`type`),
				  KEY `idx_created_time` (`created_time`)
				) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
		$db->execute();

		$db->setQuery("CREATE TABLE IF NOT EXISTS `#__edocman_associations` (
						  `id` int(11) NOT NULL AUTO_INCREMENT,
						  `document_id` int(11) DEFAULT '0',
						  `lang_code` varchar(10) DEFAULT '',
						  `assoc_id` int(11) DEFAULT '0',
						  `assoc_lang` varchar(10) DEFAULT '',
						  PRIMARY KEY (`id`)
						)  AUTO_INCREMENT=5 ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;");
		$db->execute();

		$fields = array_keys($db->getTableColumns('#__edocman_statistics'));
		if (!in_array('name', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_statistics` ADD  `name` VARCHAR( 255 ) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('email', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_statistics` ADD  `email` VARCHAR( 255 ) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}

		if (!in_array('download_code', $fields))
		{
			$sql = "ALTER TABLE  `#__edocman_statistics` ADD  `download_code` VARCHAR( 50 ) NULL DEFAULT  '';";
			$db->setQuery($sql);
			$db->execute();
		}

		$sql = "CREATE TABLE IF NOT EXISTS `#__edocman_tags` (
				`id` int(11) NOT NULL AUTO_INCREMENT,
				`tag` varchar(100) DEFAULT NULL,
				`published` tinyint(3) unsigned DEFAULT NULL,
				PRIMARY KEY (`id`)
				) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;";

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

		$sql = "CREATE TABLE IF NOT EXISTS `#__edocman_document_tags` (
				`id` int(11) NOT NULL AUTO_INCREMENT,
				`document_id` int(11) DEFAULT NULL,
				`tag_id` int(11) DEFAULT NULL,
				PRIMARY KEY (`id`)
				) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;";
		$db->setQuery($sql);
		$db->execute();

		$sql = "CREATE TABLE IF NOT EXISTS `#__edocman_googledrive` (
				  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
				  `type` tinyint(1) NOT NULL DEFAULT '0',
				  `element_id` int(11) NOT NULL DEFAULT '0',
				  `element_name` varchar(255) NOT NULL,
				  `cloud_id` varchar(255) NOT NULL DEFAULT '',
				  PRIMARY KEY (`id`)
				)  AUTO_INCREMENT=1 ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;";
		$db->setQuery($sql);
		$db->execute();

		$sql = "CREATE TABLE IF NOT EXISTS `#__edocman_googledrive_credentials` (
				  `credentials` text NOT NULL
				)  ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;";
		$db->setQuery($sql);
		$db->execute();

		$sql = "CREATE TABLE IF NOT EXISTS `#__edocman_urls` (
			  `id` int(11) NOT NULL AUTO_INCREMENT,
			  `md5_key` text,
			  `query` text,
			  `object_name` varchar(50) DEFAULT NULL,
			  `object_id` int(11) NOT NULL DEFAULT '0',
			  PRIMARY KEY (`id`)
			)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;";
		$db->setQuery($sql);
		$db->execute();


		$sql = "CREATE TABLE IF NOT EXISTS `#__edocman_galleries` (
			  `id` int(11) NOT NULL AUTO_INCREMENT,
			  `document_id` int(10) UNSIGNED DEFAULT '0',
			  `title` varchar(255) DEFAULT NULL,
			  `image` varchar(255) DEFAULT NULL,
			  `ordering` int(11) UNSIGNED DEFAULT '0',
			  PRIMARY KEY (`id`),
			  KEY `idx_document_id` (`document_id`)
			)  AUTO_INCREMENT=1 ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;";
		$db->setQuery($sql);
		$db->execute();

		$sql = "CREATE TABLE IF NOT EXISTS `#__edocman_levels` (
				  `id` int(11) NOT NULL AUTO_INCREMENT,
				  `data_type` tinyint(1) NOT NULL DEFAULT '0',
				  `item_id` int(11) NOT NULL DEFAULT '0',
				  `groups` varchar(255) NOT NULL,
				  PRIMARY KEY (`id`)
				)  AUTO_INCREMENT=1 ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;";
		$db->setQuery($sql);
		$db->execute();

		$sql = "CREATE TABLE IF NOT EXISTS `#__edocman_search_terms` (
				  `id` int(11) NOT NULL AUTO_INCREMENT,
				  `keyword` varchar(255) DEFAULT NULL,
				  `searched_on` date DEFAULT NULL,
				  `tag_id` int(11) DEFAULT 0,
				  `ip_address` varchar(255) NOT NULL DEFAULT '',
				  `address` varchar(255) NOT NULL DEFAULT '',
				  `city` varchar(255) NOT NULL DEFAULT '',
				  `postcode` varchar(50) NOT NULL DEFAULT '',
				  `country` varchar(50) NOT NULL DEFAULT '',
				  PRIMARY KEY (`id`)
				)  AUTO_INCREMENT=1 ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;";
		$db->setQuery($sql);
		$db->execute();

		$db->setQuery("ALTER TABLE `#__edocman_documents` CHANGE `document_version` `document_version` VARCHAR(10) NOT NULL DEFAULT ''; ");
		$db->execute();
		$db->setQuery("ALTER TABLE `#__edocman_documents` CHANGE `file_size` `file_size` VARCHAR(100) NOT NULL DEFAULT '', CHANGE `locked_time` `locked_time` DATETIME NULL; ");
		$db->execute();
		$db->setQuery("ALTER TABLE `#__edocman_documents` CHANGE `document_history` `document_history` TEXT NULL; ");
		$db->execute();

		$db->setQuery("Update #__edocman_categories set parent_id = '0' where parent_id = id");
		$db->execute();

		$sql = "TRUNCATE TABLE `#__edocman_urls`";
		$db->setQuery($sql);
		$db->execute();

		// Fix documents date from old version
		$query = $db->getQuery(true);
		$query->select('id, filename, created_time, modified_time')
			->from('#__edocman_documents')
			->where('(created_time LIKE "0000-00-00 00:00:00" OR created_time IS NULL OR modified_time LIKE "0000-00-00 00:00:00" OR modified_time IS NULL)')
			->where('document_url LIKE "" OR document_url IS NULL');
		$db->setQuery($query);
		$documents = $db->loadObjectList();
		if (count($documents))
		{
			$sql = 'SELECT config_value FROM #__edocman_configs WHERE config_key="documents_path"';
			$db->setQuery($sql);
			$documentPath = $db->loadResult();
			foreach ($documents as $document)
			{
				$filePath = $documentPath . '/' . $document->filename;
				if (file_exists($filePath))
				{
					/*
					$createDate   = (empty($document->created_time) || $document->created_time = '0000-00-00 00:00:00' || $document->created_time = 'NULL') ? Factory::getDate(strftime('%Y-%m-%d %H:%M:%S', filectime($filePath))) : $document->created_time;
					$modifiedDate = (empty($document->modified_time) || $document->modified_time = '0000-00-00 00:00:00' || $document->modified_time = 'NULL') ? Factory::getDate(strftime('%Y-%m-%d %H:%M:%S', filemtime($filePath))) : $document->created_time;
					$query->clear();
					$query->update('#__edocman_documents')
						->set('created_time=' . $db->quote($createDate))
						->set('modified_time=' . $db->quote($modifiedDate))
						->where('id=' . (int) $document->id);
					$db->setQuery($query);
					$db->execute();
					*/
				}
			}
		}

		if(is_file(Path::clean(JPATH_ROOT.'/components/com_edocman/view/play/tmpl/default.xml')))
		{
			File::delete(JPATH_ROOT.'/components/com_edocman/view/play/tmpl/default.xml');
		}


		if (!is_dir(Path::clean(JPATH_ROOT . '/images/com_edocman')))
		{
			Folder::create(JPATH_ROOT . '/images/com_edocman');
		}

		if (!is_dir(Path::clean(JPATH_ROOT . '/images/com_edocman/galleries')))
		{
			Folder::create(JPATH_ROOT . '/images/com_edocman/galleries');
		}
	}
}
