<?php
/**
 * @package    RSForm! Pro
 * @copyright  (c) 2020 RSJoomla!
 * @link       https://www.rsjoomla.com
 * @license    GNU General Public License http://www.gnu.org/licenses/gpl-3.0.en.html
 */

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

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

class plgSystemRsfppayfastInstallerScript
{
	protected static $minJoomla = '3.10.0';
	protected static $minComponent = '3.1.0';
	
	/**
	 * @param $type
	 * @param $parent
	 *
	 * @return bool
	 */
	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(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!');
			}

			if (!file_exists(JPATH_PLUGINS . '/system/rsfppayment/rsfppayment.php'))
			{
				throw new Exception('Please install the RSForm! Pro Payment Package before continuing.');
			}

			$this->copyFiles($parent);

			// Update? Run our SQL file
			if ($type == 'update')
			{
				$db = Factory::getDbo();
				$query = $db->getQuery(true)
					->update('#__rsform_config')
					->set($db->qn('SettingName') . ' = ' . $db->q('payfast.taxtype'))
					->where($db->qn('SettingName') . ' = ' . $db->q('payfast.tax.type'));
				$db->setQuery($query)->execute();

				$query = $db->getQuery(true)
					->update('#__rsform_config')
					->set($db->qn('SettingName') . ' = ' . $db->q('payfast.taxvalue'))
					->where($db->qn('SettingName') . ' = ' . $db->q('payfast.tax.value'));
				$db->setQuery($query)->execute();

				$this->runSQL($source, 'install');
			}
		} 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;
	}

	/**
	 * @param $parent
	 */
	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');
		}
	}

	/**
	 * @param $source
	 * @param $file
	 *
	 * @throws Exception
	 */
	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();
					}
				}
			}
		}
	}

	/**
	 * @param $type
	 * @param $parent
	 */
	public function postflight($type, $parent)
	{
		if ($type == 'install')
		{
			$db    = Factory::getDbo();
			$query = $db->getQuery(true);
			$query->update($db->qn('#__extensions'))
				->set($db->qn('enabled') . ' = ' . $db->q(1))
				->where($db->qn('element') . ' = ' . $db->q('rsfppayfast'))
				->where($db->qn('type') . '=' . $db->q('plugin'))
				->where($db->qn('folder') . '=' . $db->q('system'));
			$db->setQuery($query);
			$db->execute();
		}
	}
}