<?php
/**
* @package RSForm!Pro
* @copyright (C) 2007-2019 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 plgSystemRsfpvtigerInstallerScript
{
	protected static $minJoomla = '3.10.0';
	protected static $minComponent = '3.0.0';

	public function preflight($type, $parent)
	{
		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(sprintf('Please upgrade to at least Joomla! %s before continuing!', static::$minJoomla));
			}

			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(sprintf('Please upgrade RSForm! Pro to at least version %s before continuing!', static::$minComponent));
			}

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

			if (!class_exists('RSFormProVersion') || version_compare((string) new RSFormProVersion, static::$minComponent, '<'))
			{
				throw new Exception(sprintf('Please upgrade RSForm! Pro to at least version %s before continuing!', static::$minComponent));
			}
		}
		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)
	{
		$this->copyFiles($parent);
		$this->runSQL($parent->getParent()->getPath('source'), 'install');
		
		$db 		= Factory::getDbo();
		$columns 	= $db->getTableColumns('#__rsform_vtiger', false);		
		
		if ($columns['vt_accesskey']->Type == 'varchar(50)') {
			$db->setQuery("ALTER TABLE `#__rsform_vtiger` CHANGE `vt_accesskey` `vt_accesskey` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL");
			$db->execute();
			$db->setQuery("ALTER TABLE `#__rsform_vtiger` CHANGE `vt_username` `vt_username` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL");
			$db->execute();
			$db->setQuery("ALTER TABLE `#__rsform_vtiger` CHANGE `vt_hostname` `vt_hostname` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL");
			$db->execute();
		}
		
		if (!isset($columns['vt_fields'])) {
			$query = $db->getQuery(true);
			
			// Grab all Vtiger integrations from db.
			$query->select('*')
				  ->from($db->qn('#__rsform_vtiger'));
			$db->setQuery($query);
			$results = $db->loadObjectList();
			
			// Add missing table.
			$db->setQuery("ALTER TABLE `#__rsform_vtiger` ADD `vt_fields` MEDIUMTEXT NOT NULL AFTER `form_id`");
			$db->execute();
			
			foreach ($results as $result) {				
				$newFields = array();
				foreach ($result as $oldField => $oldValue) {
					// Skip these fields
					if (!in_array($oldField, array('form_id', 'vt_debug', 'vt_accesskey', 'vt_username', 'vt_hostname', 'vt_debugEmail', 'vt_published'))) {
						// Special handling
						if ($oldField == 'vt_custom_fields') {
							if ($oldValue && ($customFields = unserialize($oldValue))) {
								foreach ($customFields as $customField) {
									$newFields[$customField->api_name] = $customField->value;
								}
							}
						} else {
							$newFields[substr($oldField, 3)] = $oldValue;
						}
					}
				}
				
				$query = $db->getQuery(true);
				if ($newFields) {
					$query->update($db->qn('#__rsform_vtiger'))
						  ->set($db->qn('vt_fields').'='.$db->q(serialize($newFields)))
						  ->where($db->qn('form_id').'='.$db->q($result->form_id));
					$db->setQuery($query);
					$db->execute();
				}
			}
		}

		if (!isset($columns['vt_debug'])) {
			// Add missing table.
			$db->setQuery("ALTER TABLE `#__rsform_vtiger` ADD `vt_debug` TINYINT(1) NOT NULL DEFAULT '1' AFTER `vt_hostname`");
			$db->execute();
		}
	}
	
	public function install($parent) {
		$this->copyFiles($parent);
	}
	
	protected function copyFiles($parent) {
		$src 	= $parent->getParent()->getPath('source').'/admin';
		$dest 	= JPATH_ADMINISTRATOR.'/components/com_rsform';
		
		if (!Folder::copy($src, $dest, '', true))
		{
			Factory::getApplication()->enqueueMessage('Could not copy to '.str_replace(JPATH_SITE, '', $dest).', please make sure destination is writable!', 'error');
		}
	}

	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();
					}
				}
			}
		}
	}
}