<?php
/**
* @package RSForm!Pro
* @copyright (C) 2007-2020 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 plgSystemRsfpmailchimpInstallerScript
{
	protected static $minJoomla = '3.10.0';
	protected static $minComponent = '3.0.0';
	
	public function preflight($type, $parent)
	{
		if ($type == 'uninstall')
		{
			return true;
		}

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

			$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!');
			}

			$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;
	}

	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();
					}
				}
			}
		}
	}
	
	public function update($parent)
	{
		require_once JPATH_ADMINISTRATOR . '/components/com_rsform/helpers/rsform.php';
		
		$db = Factory::getDbo();

		// Run our SQL file
		$this->runSQL($parent->getParent()->getPath('source'), 'install');
		
		$columns = $db->getTableColumns('#__rsform_mailchimp');
		if (isset($columns['mc_send_goodbye']))
		{
			$db->setQuery("ALTER TABLE #__rsform_mailchimp DROP mc_send_welcome, DROP mc_send_goodbye, DROP mc_send_notify")->execute();
			$db->setQuery("ALTER TABLE #__rsform_mailchimp ADD mc_cached_values text NOT NULL AFTER `mc_merge_vars`")->execute();
			
			$query = $db->getQuery(true);
			$query->select('*')
				->from($db->qn('#__rsform_mailchimp'))
				->where($db->qn('mc_merge_vars') . ' != ' . $db->q(''));
			if ($results = $db->setQuery($query)->loadObjectList())
			{
				foreach ($results as $result)
				{
					$mc_merge_vars = @unserialize($result->mc_merge_vars);
					if (is_array($mc_merge_vars))
					{
						$new_merge_vars = array();
						foreach ($mc_merge_vars as $merge_var => $field)
						{
							$new_merge_vars[$merge_var] = '';
							
							if ($field != '- IGNORE -')
							{
								if ($exists = RSFormProHelper::componentNameExists($field, $result->form_id, 0, 'ComponentTypeId'))
								{
									if ($exists[0] == RSFORM_FIELD_FILEUPLOAD)
									{
										$new_merge_vars[$merge_var] = '{' . $field . ':path}';
									}
									else
									{
										$new_merge_vars[$merge_var] = '{' . $field . ':value}';
									}
								}
							}
						}
						
						$query->clear()
							->update('#__rsform_mailchimp')
							->set($db->qn('mc_merge_vars') . ' = ' . $db->q(serialize($new_merge_vars)))
							->where($db->qn('form_id') . ' = ' . $db->q($result->form_id));
						
						$db->setQuery($query)->execute();
					}
				}
			}
		}
		
		if (!isset($columns['mc_tags']))
		{
			$db->setQuery("ALTER TABLE `#__rsform_mailchimp` ADD `mc_tags` text NOT NULL AFTER `mc_interest_groups` ");
			$db->execute();
		}
		
		if (!isset($columns['mc_append_tags']))
		{
			$db->setQuery("ALTER TABLE `#__rsform_mailchimp` ADD `mc_append_tags` tinyint(1) NOT NULL AFTER `mc_interest_groups` ");
			$db->execute();
		}
		
		if (!isset($columns['mc_trigger_tags_automation']))
		{
			$db->setQuery("ALTER TABLE `#__rsform_mailchimp` ADD `mc_trigger_tags_automation` tinyint(1) NOT NULL DEFAULT '1' AFTER `mc_interest_groups` ");
			$db->execute();
		}

		if (!isset($columns['mc_language']))
		{
			$db->setQuery("ALTER TABLE `#__rsform_mailchimp` ADD `mc_language` VARCHAR(255) NOT NULL DEFAULT '' AFTER `mc_delete_member` ");
			$db->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');
		}
	}
}