<?php
/**
* @package RSform!Pro
* @copyright (C) 2015 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

// no direct access
defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Filesystem\Folder;

class plgSystemRsfpzohocrmInstallerScript
{
	protected static $minJoomla = '3.10.0';
	protected static $minComponent = '3.0.0';

	public function preflight($type, $parent)
	{
		if ($type == 'uninstall')
		{
			return true;
		}

		try
		{
			$source = $parent->getParent()->getPath('source');

			if (!class_exists('\\Joomla\\CMS\\Version'))
			{
				throw new Exception('Please upgrade to at least Joomla! ' . static::$minJoomla . ' before continuing!');
			}

			$jversion = new \Joomla\CMS\Version;

			if (!$jversion->isCompatible(static::$minJoomla))
			{
				throw new Exception('Please upgrade to at least Joomla! ' . static::$minJoomla . ' before continuing!');
			}

			if (!file_exists(JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/rsform.php'))
			{
				throw new Exception('Please install the RSForm! Pro component before continuing.');
			}

			if (!file_exists(JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/assets.php') || !file_exists(JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/version.php'))
			{
				throw new Exception('Please upgrade RSForm! Pro to at least version ' . static::$minComponent . ' before continuing!');
			}

			require_once JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/version.php';

			if (!class_exists('RSFormProVersion') || version_compare((string) new RSFormProVersion, static::$minComponent, '<'))
			{
				throw new Exception('Please upgrade RSForm! Pro to at least version ' . static::$minComponent . ' before continuing!');
			}

			if (!function_exists('curl_init'))
			{
				throw new Exception('The Zoho CRM Plugin cannot work without cURL installed and enabled. Please contact your hosting provider for assistance on how to do that.');
			}

			$this->copyFiles($parent);
		}
		catch (Exception $e)
		{
			if (class_exists('\Joomla\CMS\Factory'))
			{
				$app = \Joomla\CMS\Factory::getApplication();
			}
			elseif (class_exists('JFactory'))
			{
				$app = JFactory::getApplication();
			}

			if (!empty($app))
			{
				$app->enqueueMessage($e->getMessage(), 'error');
			}

			return false;
		}

		return true;
	}
	
	public function update($parent)
	{
		$db 		= Factory::getDbo();
		$columns 	= $db->getTableColumns('#__rsform_zohocrm');		
		
		if (!isset($columns['zh_debug']))
		{
			$db->setQuery("ALTER TABLE `#__rsform_zohocrm` ADD `zh_debug` TINYINT( 1 ) NOT NULL AFTER `zh_merge_vars` ");
			$db->execute();
		}
		
		if (!isset($columns['zh_track_ga']))
		{
			$db->setQuery("ALTER TABLE `#__rsform_zohocrm` ADD `zh_track_ga` TINYINT( 1 ) NOT NULL AFTER `zh_merge_vars` ");
			$db->execute();
		}
		
		if (!isset($columns['zh_layout_id']))
		{
			$db->setQuery("ALTER TABLE `#__rsform_zohocrm` ADD `zh_layout_id` VARCHAR( 255 ) NOT NULL AFTER `zh_format` ");
			$db->execute();
		}
		
		if (!isset($columns['zh_lar_id']))
		{
			$db->setQuery("ALTER TABLE `#__rsform_zohocrm` ADD `zh_lar_id` VARCHAR( 100 ) NOT NULL AFTER `zh_track_ga` ");
			$db->execute();
		}

		if (!isset($columns['zh_action']))
		{
			$db->setQuery("ALTER TABLE `#__rsform_zohocrm` ADD `zh_action` TINYINT( 1 ) NOT NULL DEFAULT '1' AFTER `zh_published` ");
			$db->execute();
		}

		if (!isset($columns['zh_action_field']))
		{
			$db->setQuery("ALTER TABLE `#__rsform_zohocrm` ADD `zh_action_field` VARCHAR( 255 ) NOT NULL DEFAULT '' AFTER `zh_action` ");
			$db->execute();
		}
	
		// remove the "crm." part from the zohorm.host config
		$query = $db->getQuery(true);
		$query->select($db->qn('SettingValue'))
			  ->from($db->qn('#__rsform_config'))
			  ->where($db->qn('SettingName') .'='.$db->q('zohocrm.host'));
		$db->setQuery($query);
		$zoho_host = $db->loadResult();

		if (!empty($zoho_host) && strpos($zoho_host, 'crm.') === 0) {
			$zoho_host = str_replace('crm.', '', $zoho_host);
			$query = $db->getQuery(true);
			$query->update($db->qn('#__rsform_config'))
				  ->set($db->qn('SettingValue') .'='.$db->q($zoho_host))
				  ->where($db->qn('SettingName') .'='.$db->q('zohocrm.host'));
			
			$db->setQuery($query);
			$db->execute();
		}
		
		$this->runSQL($parent->getParent()->getPath('source'), 'install');
	}

	protected function runSQL($source, $file)
	{
		$db = Factory::getDbo();
		$sqlfile = $source . '/sql/mysql/' . $file . '.sql';

		if (file_exists($sqlfile))
		{
			$buffer = file_get_contents($sqlfile);
			if ($buffer !== false)
			{
				$queries = $db->splitSql($buffer);
				foreach ($queries as $query)
				{
					$query = trim($query);
					if ($query != '')
					{
						$db->setQuery($query)->execute();
					}
				}
			}
		}
	}
	
	protected function copyFiles($parent)
	{
		$app 		= Factory::getApplication();
		$installer 	= $parent->getParent();
		$src 		= $installer->getPath('source').'/admin';
		$dest 		= JPATH_ADMINISTRATOR.'/components/com_rsform';
		
		if (!Folder::copy($src, $dest, '', true))
		{
			$app->enqueueMessage('Could not copy to '.str_replace(JPATH_SITE, '', $dest).', please make sure destination is writable!', 'error');
		}
	}
}