<?php
/** 
 *------------------------------------------------------------------------------
 * @package       T4 Page Builder for Joomla!
 *------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2004-2020 JoomlArt.com. All Rights Reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       JoomlArt
 * @forum:        https://www.joomlart.com/forums/t/t4-builder
 * @Link:         https://demo.t4-builder.joomlart.com/
 *------------------------------------------------------------------------------
 */

defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Factory;
use Joomla\CMS\Table\Table;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;

$basePath = JPATH_ADMINISTRATOR . '/components/com_categories';
if(version_compare(JVERSION, '4', 'ge')){
	class CategoriesModelCategory extends \Joomla\Component\Categories\Administrator\Model\CategoryModel{};
}else {
	JLoader::register("CategoriesModelCategory",JPATH_ADMINISTRATOR . '/components/com_categories/models/category.php' );
}
class com_t4pagebuilderInstallerScript
{
	/**
	 * This method is called after a component is installed.
	 *
	 * @param  \stdClass $parent - Parent object calling this method.
	 *
	 * @return void
	 */
	public function install($parent) 
	{
		$this->installOrUpdate($parent);

		$db = Factory::getDBO();
		$sql = 'UPDATE `#__extensions` SET  params ='.$db->quote('{"bootstrap4":"-","loadfonts":"{\"PlayfairDisplay\":{\"name\":\"PlayfairDisplay\",\"weight\":[\"400\",\"400i\",\"700\",\"700i\"]},\"Quicksand\":{\"name\":\"Quicksand\",\"weight\":[\"400\",\"500\",\"600\",\"700\"]},\"JosefinSans\":{\"name\":\"JosefinSans\",\"weight\":[\"300\",\"400\",\"400i\",\"600\"]},\"IbarraRealNova\":{\"name\":\"IbarraRealNova\",\"weight\":[\"400\",\"400i\",\"600\",\"700\"]}}","loadconfigicons":"{\"awesome_icons\":{\"awesome_icons\":true,\"url_type\":\"cdn\",\"custom_url\":\"null\"},\"material_icons\":{\"material_icons\":true,\"url_type\":\"cdn\",\"custom_url\":\"\"}}","btAssigned":""}').'
				WHERE name = '.$db->quote('com_t4pagebuilder');
		$db->setQuery($sql);
		$db->execute();

		//get old config update to new component
		$cf_query= "SELECT params FROM `#__extensions` WHERE name = ".$db->quote('com_japagebuilder');
		$db->setQuery($cf_query);
		$config = $db->loadResult();
		if(!empty($config)){
			$conf_new = 'UPDATE `#__extensions` SET  params ='.$db->quote($config).' WHERE name = '.$db->quote('com_t4pagebuilder');
			$db->setQuery($conf_new);
			$db->execute();
		}
		self::compare_version();
		self::compare_db();
	}

	/**
	 *
	 * @param JInstallerAdapterPackage $parent
	 */
	protected function installOrUpdate($parent) {

		$sourcePath = $parent->getParent()
							 ->getPath('source');
		$return = $this->smartCopy($sourcePath . '/tpl_t4_builder', JPATH_ROOT . "/templates/t4_builder");

		if(!$return){
			$error = Text::sprintf('JLIB_INSTALLER_ABORT_PACK_INSTALL_ERROR_EXTENSION', 'Smart Slider 3', $path) . ' Please <a href="https://smartslider3.com/contact-us/support/" target="_blank">contact us</a> with this error!</p>';
			throw new RuntimeException($error);

			return false;
		}
	}
	protected function installFromPath($src,$dst) {
		$dir = opendir($src);
		@mkdir($dst);
		$return = true;
		while(false !== ( $file = readdir($dir)) ) {
			if (( $file != '.' ) && ( $file != '..' )) {
				if ( is_dir($src . '/' . $file) ) {
					$this->installFromPath($src . '/' . $file,$dst . '/' . $file);
				}
				else {
					if(!copy($src . '/' . $file,$dst . '/' . $file)){
						$return = false;
					}
				}
			}
		}
		closedir($dir);
		return$return;

	}
	protected function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
	{
		$result=false;
	   
		if (is_file($source)) {
			if ($dest[strlen($dest)-1]=='/') {
				if (!file_exists($dest)) {
					cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
				}
				$__dest=$dest."/".basename($source);
			} else {
				$__dest=$dest;
			}
			$result=copy($source, $__dest);
			chmod($__dest,$options['filePermission']);
		   
		} elseif(is_dir($source)) {
			if ($dest[strlen($dest)-1]=='/') {
				if ($source[strlen($source)-1]=='/') {
					//Copy only contents
				} else {
					//Change parent itself and its contents
					$dest=$dest.basename($source);
					@mkdir($dest);
					chmod($dest,$options['filePermission']);
				}
			} else {
				if ($source[strlen($source)-1]=='/') {
					//Copy parent directory with new name and all its content
					@mkdir($dest,$options['folderPermission']);
					chmod($dest,$options['filePermission']);
				} else {
					//Copy parent directory with new name and all its content
					@mkdir($dest,$options['folderPermission']);
					chmod($dest,$options['filePermission']);
				}
			}

			$dirHandle=opendir($source);
			while($file=readdir($dirHandle))
			{
				if($file!="." && $file!="..")
				{
					 if(!is_dir($source."/".$file)) {
						$__dest=$dest."/".$file;
					} else {
						$__dest=$dest."/".$file;
					}
					$result = $this->smartCopy($source."/".$file, $__dest, $options);
				}
			}
			closedir($dirHandle);
		   
		} else {
			$result=false;
		}
		return $result;
	} 
	protected function compare_version()
	{
		$com_ja_admin = JPATH_ADMINISTRATOR . "/components/com_japagebuilder";
		$com_ja_site = JPATH_SITE . "/components/com_japagebuilder";
		$com_ja_media = JPATH_SITE . "/media/japagebuilder";
		if(is_dir($com_ja_admin)){
			self::delete_directory($com_ja_admin);
		}
		if(is_dir($com_ja_site)){
			self::delete_directory($com_ja_site);
		}
		if(is_dir($com_ja_media)){
			self::delete_directory($com_ja_media);
		}
	}
	protected function delete_directory($dirname) {
		if (is_dir($dirname))
		   $dir_handle = opendir($dirname);
		if (!$dir_handle)
			return false;
		while($file = readdir($dir_handle)) {
			if ($file != "." && $file != "..") {
				if (!is_dir($dirname."/".$file)){
					unlink($dirname."/".$file);
				}else{
					self::delete_directory($dirname.'/'.$file);
				}
			}
		}
		closedir($dir_handle);
		rmdir($dirname);
		return true;
	}
	protected function compare_db()
	{
		$db = Factory::getDbo();
		$s1 = "DELETE FROM `#__schemas` WHERE `extension_id` = (SELECT `extension_id` FROM `#__extensions` WHERE `type` = 'component' AND `name` = 'com_japagebuilder');";
		$db->setQuery($s1);
		$db->execute();

		$s2 = "DELETE FROM `#__extensions` WHERE `name` = 'com_japagebuilder';";
		$db->setQuery($s2);
		$db->execute();

		$s3 = "DELETE FROM `#__assets` WHERE `name` = 'com_japagebuilder';";
		$db->setQuery($s3);
		$db->execute();
		//remove menu
		$s4 = "DELETE FROM `#__menu` WHERE `type` = 'component' AND `title` LIKE '%com_japagebuilder%';";
		$db->setQuery($s4);
		$db->execute();
		self::updateMenuItem();

		$s5 = "DELETE FROM `#__session` WHERE  `data` LIKE '%com_japagebuilder%';";
		$db->setQuery($s5);
		$db->execute();
	}
	protected function check_category()
	{
		
	}
	protected function updateMenuItem()
	{
		$db = Factory::getDbo();
		$query_menu = $db->getQuery(true);
		$query_menu->select('*')
			  ->from('#__menu')
			  ->where($db->quoteName('link') . " LIKE '%com_japagebuilder%'");
		$db->setQuery($query_menu);
		$list = $db->loadObjectList();

		//get id update to new component
		$cfs_query= "SELECT extension_id FROM #__extensions WHERE name = ".$db->quote('com_t4pagebuilder');
		$db->setQuery($cfs_query);
		$extension_id = $db->loadResult();
		if(!empty($list)){
			foreach ($list as $item) {
				// Fields to update.
				$fields = array(
					$db->quoteName('link') . ' = ' . $db->quote(str_replace('com_japagebuilder', 'com_t4pagebuilder', $item->link)),
					$db->quoteName('component_id') . ' = ' . $db->quote($extension_id)
				);
				$update_menu = $db->getQuery(true);
				$update_menu->clear();
				$update_menu->update('#__menu')
					  ->set($fields)
					  ->where($db->quoteName('id') . " = " . $db->quote($item->id));
				$db->setQuery($update_menu);
				$db->execute();
			}
		}
		return true;
	}
	/**
	 * This method is called after a component is uninstalled.
	 *
	 * @param  \stdClass $parent - Parent object calling this method.
	 *
	 * @return void
	 */
	public function uninstall($parent) 
	{
		echo '<p>' . Text::_('COM_JAPGEBUILDER_UNINSTALL_TEXT') . '</p>';
	}

	/**
	 * This method is called after a component is updated.
	 *
	 * @param  \stdClass $parent - Parent object calling object.
	 *
	 * @return void
	 */
	public function update($parent) 
	{
		$this->installOrUpdate($parent);
	}

	/**
	 * Runs just before any installation action is performed on the component.
	 * Verifications and pre-requisites should run in this function.
	 *
	 * @param  string    $type   - Type of PreFlight action. Possible values are:
	 *                           - * install
	 *                           - * update
	 *                           - * discover_install
	 * @param  \stdClass $parent - Parent object calling object.
	 *
	 * @return void
	 */
	public function preflight($type, $parent) 
	{
		return true;
	}

	/**
	 * Runs right after any installation action is performed on the component.
	 *
	 * @param  string    $type   - Type of PostFlight action. Possible values are:
	 *                           - * install
	 *                           - * update
	 *                           - * discover_install
	 * @param  \stdClass $parent - Parent object calling object.
	 *
	 * @return void
	 */
	function postflight($type, $parent) 
	{
		global $basePath;
		// check exist category
		$db = Factory::getDbo();
		$sql = "SELECT id FROM `#__categories` WHERE extension = 'com_t4pagebuilder'";
		$db->setQuery($sql);
		$id = $db->loadResult();
		if(!$id){
			if(version_compare(JVERSION, '4', 'ge')){
				$config = array( 'table_path' => $basePath . '/src/Table');
			}else {
				$config = array( 'table_path' => $basePath . '/tables');
			}
			$model = BaseDatabaseModel::getInstance('Category', 'CategoriesModel', array('ignore_request' => true));
			
			$catData = array( 
				'id' => null, 
				'parent_id' => 1, 
				'level' => 1, 
				'path' => 'demo',
				'extension' => 'com_t4pagebuilder', 
				'title' => 'Demo', 
				'alias' => 'demo', 
				'description' => '', 
				'published' => 1, 
				'language' => '*'
			);
			$status = $model->save( $catData);
		  
			if(!$status) 
			{
				$app = Factory::getApplication();
				$app->enqueueMessage('Unable to create default content category!');
			}
			$update = "UPDATE `#__jae_item` set `catid` = (SELECT id FROM `#__categories` WHERE `extension` = 'com_t4pagebuilder')";
			$db->setQuery($update);
			$db->execute();
			
		}

		return true;
	}
}