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

defined('_JEXEC') or die;

use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;
use Joomla\Utilities\IpHelper;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Table\Table;

define('RSFORM_FIELD_PAYMENT_IYZICO', 514);

/**
 * Class plgSystemrsfpiyzico
 */
class plgSystemrsfpiyzico extends CMSPlugin
{
	/**
	 * @var bool
	 */
	protected $autoloadLanguage = true;
	/**
	 * @var int
	 */
	protected $componentId = RSFORM_FIELD_PAYMENT_IYZICO;
	/**
	 * @var string
	 */
	protected $componentValue = 'iyzico';

	public function onRsformBackendAfterCreateFieldGroups(&$fieldGroups, $self)
	{
		$formId = Factory::getApplication()->input->getInt('formId');
		$exists = RSFormProHelper::componentExists($formId, RSFORM_FIELD_PAYMENT_IYZICO);

		$fieldGroups['payment']->fields[] = (object) array(
			'id' 	=> RSFORM_FIELD_PAYMENT_IYZICO,
			'name' 	=> Text::_('PLG_SYSTEM_RSFPIYZICO_COMPONENT'),
			'icon'  => 'rsficon rsficon-coin-dollar',
			'exists' => $exists ? $exists[0] : false
		);
	}

	/**
	 * Add a grand total and tax placeholder
	 *
	 * @param $args
	 */
	public function onRsformAfterCreatePlaceholders($args)
	{
		if ($choosePayment = RSFormProHelper::componentExists($args['form']->FormId, RSFORM_FIELD_PAYMENT_CHOOSE))
		{
			$properties = RSFormProHelper::getComponentProperties($choosePayment[0]);
			$fieldName = $properties['NAME'];

			if (!isset($args['submission']->values[$fieldName]))
			{
				return;
			}

			if ($args['submission']->values[$fieldName] != $this->componentValue)
			{
				return;
			}
			
			$grandTotal = $this->calcTax($args['submission']->values['rsfp_Total'], RSFormProHelper::getConfig('iyzico.taxvalue'), RSFormProHelper::getConfig('iyzico.taxtype'));

			$placeholders = &$args['placeholders'];
			$values       = &$args['values'];

			$placeholders[] = '{grandtotal}';
			$values[]       = $this->number_format($grandTotal);

			$placeholders[] = '{tax}';
			$values[]       = $this->number_format($grandTotal - (float) $args['submission']->values['rsfp_Total']);
		}
	}

	private function number_format($val)
	{
		return number_format((float) $val, RSFormProHelper::getConfig('payment.nodecimals'), RSFormProHelper::getConfig('payment.decimal'), RSFormProHelper::getConfig('payment.thousands'));
	}

	/**
	 * @param $placeholders
	 * @param $componentId
	 *
	 * @return mixed
	 * @since 1.2.1
	 */
	public function onRsformAfterCreateQuickAddPlaceholders(& $placeholders, $componentId)
	{
		if ($componentId == $this->componentId)
		{
			$placeholders['display'][] = '{grandtotal}';
			$placeholders['display'][] = '{tax}';
		}

		return $placeholders;
	}

	public function onRsformDefineHiddenComponents(&$hiddenComponents)
	{
		$hiddenComponents[] = $this->componentId;
	}

	/**
	 * @param $items
	 * @param $formId
	 */
	public function onRsformGetPayment(&$items, $formId)
	{
		if ($components = RSFormProHelper::componentExists($formId, $this->componentId))
		{
			$data = RSFormProHelper::getComponentProperties($components[0]);

			$item        = new stdClass();
			$item->id    = $components[0];
			$item->value = $this->componentValue;
			$item->text  = $data['LABEL'];
			
			if ($tax = RSFormProHelper::getConfig('iyzico.taxvalue'))
			{
				$item->tax = $tax;
				$item->tax_type = RSFormProHelper::getConfig('iyzico.taxtype') == '0' ? 'percent' : 'fixed';

			}

			// add to array
			$items[] = $item;
		}
	}

	protected function doReturn($formId)
	{
		// Get session object
		$session = Factory::getSession();
		$app = Factory::getApplication();
		// Get data from session
		$formparams = $session->get('com_rsform.formparams.formId'.$formId);
		if ($formparams && $formparams->redirectUrl)
		{
			// Mark form as processed
			$formparams->formProcessed = true;

			// Store new session data
			$session->set('com_rsform.formparams.formId'.$formId, $formparams);

			// Redirect
			$app->redirect($formparams->redirectUrl);
		}
	}

	public function onRsformFrontendSwitchTasks()
	{
		$input 	= Factory::getApplication()->input;
		$task 	= $input->get->getString('plugin_task');
		$code   = $input->get->get('code', '', 'raw');
		$formId = $input->getInt('formId');

		switch ($task)
        {
            case 'iyzico.checkout':
	            if ($SubmissionId = $this->_getSubmissionId($formId, $code))
                {
                    if ($form = $this->_getSubmissionValue($SubmissionId, '_IYZICO_CHECKOUT_FORM'))
                    {
	                    $mode = RSFormProHelper::getConfig('iyzico.checkoutform');

	                    if (in_array($mode, array('responsive', 'popup')))
                        {
	                        echo '<div id="iyzipay-checkout-form" class="' . $mode . '"></div>';
	                        echo $form;
                        }
                    }
                }
                break;

            case 'iyzico.return':
	            // This loads our class
	            $instance = RSFormProIyzico::getInstance();

	            $request = new \Iyzipay\Request\RetrieveCheckoutFormRequest();
	            $request->setLocale($instance->getLocale());
	            $request->setConversationId($input->post->get('conversationId', '', 'raw'));
	            $request->setToken($input->post->get('token', '', 'raw'));

	            $checkoutForm = \Iyzipay\Model\CheckoutForm::retrieve($request, $instance->options());

	            if ($checkoutForm->getStatus() === \Iyzipay\Model\Status::FAILURE)
                {
                    Factory::getApplication()->enqueueMessage($checkoutForm->getErrorMessage(), 'error');
                }
                else
                {
                    if ($SubmissionId = $this->_getSubmissionId($formId, $code))
                    {
	                    $db     = Factory::getDbo();
	                    $query  = $db->getQuery(true);

	                    if ($checkoutForm->getPaymentStatus() === 'SUCCESS')
                        {
	                        $query->clear();
	                        $query->update($db->qn('#__rsform_submission_values'))
		                        ->set($db->qn('FieldValue') . ' = ' . $db->q(1))
		                        ->where($db->qn('FieldName') . ' = ' . $db->q('_STATUS'))
		                        ->where($db->qn('FormId') . ' = ' . $db->q($formId))
		                        ->where($db->qn('SubmissionId') . ' = ' . $db->q($SubmissionId));
	                        $db->setQuery($query);
	                        $db->execute();

	                        Factory::getApplication()->enqueueMessage(Text::sprintf('PLG_SYSTEM_RSFPIYZICO_PAYMENT_HAS_BEEN_COMPLETED', $checkoutForm->getPaymentId(), $this->number_format($checkoutForm->getPaidPrice()), $checkoutForm->getCurrency()));
                        }
                        else
                        {
                            Factory::getApplication()->enqueueMessage(Text::sprintf('PLG_SYSTEM_RSFPIYZICO_YOUR_PAYMENT_STATUS_IS', $checkoutForm->getPaymentStatus()), 'warning');
                        }

	                    $query->clear();
	                    $query->update($db->qn('#__rsform_submission_values'))
		                    ->set($db->qn('FieldValue') . ' = ' . $db->q($checkoutForm->getPaymentId()))
		                    ->where($db->qn('FieldName') . ' = ' . $db->q('_TRANSACTION_ID'))
		                    ->where($db->qn('FormId') . ' = ' . $db->q($formId))
		                    ->where($db->qn('SubmissionId') . ' = ' . $db->q($SubmissionId));
	                    $db->setQuery($query);
	                    $db->execute();
                    }

	                $this->doReturn($formId);
                }

                break;
        }
	}

	protected function _getSubmissionId($formId, $code)
	{
		$db    = Factory::getDbo();
		$query = $db->getQuery(true);
		$query->select($db->qn('SubmissionId'))
			->from($db->qn('#__rsform_submissions', 's'))
			->where($db->qn('s.FormId') . ' = ' . $db->q($formId))
			->where('MD5(CONCAT(' . $db->qn('s.SubmissionId') . ',' . $db->qn('s.DateSubmitted') . ')) = ' . $db->q($code));
		$db->setQuery($query);

		if ($SubmissionId = $db->loadResult())
		{
			return $SubmissionId;
		}

		return false;
	}

	protected function _getSubmissionValue($submissionId, $componentName)
	{
		static $cache = array();

		if (!isset($cache[$submissionId])) {
			$db = Factory::getDbo();
			$query = $db->getQuery(true)
				->select($db->qn(array('FieldName', 'FieldValue')))
				->from($db->qn('#__rsform_submission_values'))
				->where($db->qn('SubmissionId') . ' = ' . $db->q($submissionId));
			$cache[$submissionId] = (array) $db->setQuery($query)->loadAssocList('FieldName');
		}

		// The _STATUS field can change, so don't cache it, grab a fresh version every time we need it.
		if ($componentName == '_STATUS')
		{
			$db = Factory::getDbo();
			$query = $db->getQuery(true)
				->select($db->qn('FieldValue'))
				->from($db->qn('#__rsform_submission_values'))
				->where($db->qn('SubmissionId') . ' = ' . $db->q($submissionId))
				->where($db->qn('FieldName') . ' = ' . $db->q($componentName));
			$cache[$submissionId][$componentName]['FieldValue'] = $db->setQuery($query)->loadResult();
		}

		if (!empty($cache[$submissionId]) && isset($cache[$submissionId][$componentName])) {
			return $cache[$submissionId][$componentName]['FieldValue'];
		}

		return null;
	}

	/**
	 * @param $payValue
	 * @param $formId
	 * @param $SubmissionId
	 * @param $price
	 * @param $products
	 * @param $code
	 *
	 * @throws Exception
	 */
	public function onRsformDoPayment($payValue, $formId, $SubmissionId, $price, $products, $code)
	{
		// execute only for our plugin
		if ($payValue != $this->componentValue)
		{
			return false;
		}

		if ($price > 0)
		{
		    try
            {
	            $mode       = RSFormProHelper::getConfig('iyzico.checkoutform');
	            $instance   = RSFormProIyzico::getInstance();
	            $row        = $this->getTable();

	            if (!$row)
	            {
		            return false;
	            }

	            $row->load($formId);

	            if ($row->vars)
	            {
		            $row->vars = unserialize($row->vars);
	            }

	            list($replace, $with) = RSFormProHelper::getReplacements($SubmissionId);

	            if ($mode === 'paywithiyzico')
	            {
		            $request = new \Iyzipay\Request\CreatePayWithIyzicoInitializeRequest();
	            }
	            else
	            {
		            $request = new \Iyzipay\Request\CreateCheckoutFormInitializeRequest();
	            }

	            /**
	             * Get the calculated price (with tax)
	             */
	            if ($tax = RSFormProHelper::getConfig('iyzico.taxvalue'))
	            {
		            $price = $this->calcTax($price, RSFormProHelper::getConfig('iyzico.taxvalue'), RSFormProHelper::getConfig('iyzico.taxtype'));
	            }

	            $request->setLocale($instance->getLocale());
	            $request->setConversationId($code);
	            $request->setPrice(number_format($price, 2, '.' ,''));
	            $request->setPaidPrice(number_format($price, 2, '.' ,''));
	            $request->setCurrency(RSFormProHelper::getConfig('payment.currency'));
	            $request->setBasketId('SUBMISSION_' . $SubmissionId);

	            $requestVars = isset($row->vars['request']) ? $row->vars['request'] : array();
	            foreach ($requestVars as $var => $placeholder)
                {
                    call_user_func(array($request, 'set' . $var), str_replace($replace, $with, $placeholder));
                }
                if (!$request->getPaymentGroup())
                {
	                $request->setPaymentGroup(\Iyzipay\Model\PaymentGroup::PRODUCT);
                }

	            $request->setCallbackUrl(Uri::root() . 'index.php?option=com_rsform&formId=' . $formId . '&task=plugin&plugin_task=iyzico.return&code=' . urlencode($code));

	            // Set buyer
	            $buyer = new \Iyzipay\Model\Buyer();
	            $buyerVars = isset($row->vars['buyer']) ? $row->vars['buyer'] : array();
	            if ($buyerVars)
                {
                    foreach ($buyerVars as $var => $placeholder)
                    {
                        call_user_func(array($buyer, 'set' . $var), str_replace($replace, $with, $placeholder));
                    }
                }

	            // Populate these
	            $user = Factory::getUser();
	            if (!$user->guest)
                {
	                $buyer->setRegistrationDate($user->registerDate);
	                $buyer->setLastLoginDate($user->lastvisitDate);

	                if (!$buyer->getId())
                    {
	                    $buyer->setId('JOOMLA_' . $user->id);
                    }
                }

                // Set IP
                $buyer->setIp(IpHelper::getIp());

	            // Set shipping address
	            $shippingAddress = new \Iyzipay\Model\Address();
	            $shippingVars = isset($row->vars['shippingaddress']) ? $row->vars['shippingaddress'] : array();
	            if ($shippingVars)
	            {
		            foreach ($shippingVars as $var => $placeholder)
		            {
			            call_user_func(array($shippingAddress, 'set' . $var), str_replace($replace, $with, $placeholder));
		            }
	            }

	            // Set billing address
	            $billingAddress = new \Iyzipay\Model\Address();
	            $billingVars = isset($row->vars['billingaddress']) ? $row->vars['billingaddress'] : array();
	            if ($billingVars)
	            {
		            foreach ($billingVars as $var => $placeholder)
		            {
			            call_user_func(array($billingAddress, 'set' . $var), str_replace($replace, $with, $placeholder));
		            }
	            }

	            // Set basket items
	            $basketItems = array();
	            $firstBasketItem = new \Iyzipay\Model\BasketItem();
	            $basketVars = isset($row->vars['basketitems']) ? $row->vars['basketitems'] : array();
	            if ($basketVars)
                {
                    foreach ($basketVars as $var => $placeholder)
                    {
                        call_user_func(array($firstBasketItem, 'set' . $var), str_replace($replace, $with, $placeholder));
                    }
                }

	            $firstBasketItem->setId("BI101");
	            $firstBasketItem->setName(implode(', ', $products));
	            $firstBasketItem->setItemType(\Iyzipay\Model\BasketItemType::PHYSICAL);
	            if (!$firstBasketItem->getItemType())
                {
	                $firstBasketItem->setItemType(\Iyzipay\Model\BasketItemType::PHYSICAL);
                }
	            $firstBasketItem->setPrice($price);
	            $basketItems[0] = $firstBasketItem;

	            if (strlen($row->code))
                {
                    eval($row->code);
                }

                if (!empty($buyer))
                {
	                $request->setBuyer($buyer);
                }

                if (!empty($shippingAddress))
                {
	                $request->setShippingAddress($shippingAddress);
                }

	            if (!empty($billingAddress))
                {
	                $request->setBillingAddress($billingAddress);
                }

                if (!empty($basketItems))
                {
	                $request->setBasketItems($basketItems);
                }

	            if ($mode === 'paywithiyzico')
	            {
		            $payWithIyzicoInitialize = \Iyzipay\Model\PayWithIyzicoInitialize::create($request, $instance->options());

		            if ($payWithIyzicoInitialize->getStatus() === \Iyzipay\Model\Status::FAILURE)
		            {
			            throw new Exception($payWithIyzicoInitialize->getErrorMessage());
		            }

		            Factory::getApplication()->redirect($payWithIyzicoInitialize->getPayWithIyzicoPageUrl());
	            }
	            else
	            {
		            $checkoutFormInitialize = \Iyzipay\Model\CheckoutFormInitialize::create($request, $instance->options());

		            if ($checkoutFormInitialize->getStatus() === \Iyzipay\Model\Status::FAILURE)
		            {
			            throw new Exception($checkoutFormInitialize->getErrorMessage());
		            }

		            switch ($mode)
		            {
			            case 'common':
				            Factory::getApplication()->redirect($checkoutFormInitialize->getPaymentPageUrl());
				            break;

			            default:
				            $value = (object) array(
					            'FormId' 		=> $formId,
					            'SubmissionId' 	=> $SubmissionId,
					            'FieldName'		=> '_IYZICO_CHECKOUT_FORM',
					            'FieldValue'	=> $checkoutFormInitialize->getCheckoutFormContent()
				            );
				            Factory::getDbo()->insertObject('#__rsform_submission_values', $value);

				            Factory::getApplication()->redirect(Route::_('index.php?option=com_rsform&formId=' . $formId . '&task=plugin&plugin_task=iyzico.checkout&code=' . urlencode($code), false));
				            break;
		            }
	            }
            }
			catch (Exception $e)
            {
	            Factory::getApplication()->enqueueMessage($e->getMessage(), 'error');
            }
		}
	}

	/**
	 * @param array $args
	 */
	public function onRsformBackendAfterCreateComponentPreview($args = array())
	{
		if ($args['ComponentTypeName'] == $this->componentValue)
		{
			$args['out'] = '<span style="font-size:24px;margin-right:5px" class="rsficon rsficon-coin-dollar"></span> ' . $args['data']['LABEL'];
		}
	}

	/**
	 *
	 */
	public function onRsformBackendAfterShowFormEditTabsTab()
	{
		?>
		<li><a href="javascript: void(0);" id="rsfpiyzico"><span class="rsficon rsficon-coin-dollar"></span><span class="inner-text"><?php echo Text::_('PLG_SYSTEM_RSFPIYZICO_TAB'); ?></span></a></li>
		<?php
	}

	/**
	 * @throws Exception
	 */
	public function onRsformBackendAfterShowFormEditTabs()
	{
		$formId = Factory::getApplication()->input->getInt('formId', 0);
		$row    = $this->getTable();

		if (!$row)
		{
			return;
		}

		if (!$row->load($formId))
        {
            // Some defaults
            $row->vars = 'a:3:{s:5:"buyer";a:1:{s:2:"id";s:15:"{global:userid}";}s:11:"basketitems";a:2:{s:9:"category1";s:8:"Software";s:8:"itemtype";s:7:"VIRTUAL";}s:7:"request";a:1:{s:12:"paymentgroup";s:7:"PRODUCT";}}';
        }

		if ($row->vars)
		{
			$row->vars = unserialize($row->vars);
		}

		$groups = $this->standardFields();
		?>
        <div id="iyzicodiv">
            <?php foreach ($groups as $group => $fields) { ?>
            <h3 class="rsfp-legend"><?php echo Text::_('PLG_SYSTEM_RSFPIYZICO_GROUP_' . $group); ?></h3>
            <table class="admintable table table-bordered">
            <?php foreach ($fields as $id => $field) { ?>
                <tr>
                    <td width="80" align="right" nowrap="nowrap" class="key" valign="top">
                        <?php echo Text::_('PLG_SYSTEM_RSFPIYZICO_FIELD_' . strtoupper($field)); ?>
                    </td>
                    <td valign="top">
                        <input name="iyzico[vars][<?php echo RSFormProHelper::htmlEscape($group); ?>][<?php echo RSFormProHelper::htmlEscape($field); ?>]" id="iyzico_vars<?php echo RSFormProHelper::htmlEscape($group . '_' . $id); ?>" value="<?php echo RSFormProHelper::htmlEscape(isset($row->vars[$group][$field]) ? $row->vars[$group][$field] : ''); ?>" type="text" class="rs_inp rs_80"  data-delimiter=" " data-placeholders="display" />
                    </td>
                </tr>
            <?php } ?>
            </table>
            <?php } ?>
            <table class="admintable table">
                <tr class="info">
                    <td width="250" align="right" class="key" style="width: 250px;"><?php echo Text::_('PLG_SYSTEM_RSFPIYZICO_PHP_CODE'); ?></td>
                    <td><?php echo Text::_('PLG_SYSTEM_RSFPIYZICO_PHP_CODE_DESC'); ?></td>
                </tr>
                <tr>
                    <td colspan="2"><?php echo RSFormProHelper::showEditor('iyzico[code]', $row->code, array('classes' => 'rs_100', 'syntax' => 'php')); ?></td>
                </tr>
            </table>
        </div>
		<?php
	}

	/**
	 * @param $form
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function onRsformFormSave($form)
	{
		$application = Factory::getApplication();

		try
		{
			$data            = $application->input->get('iyzico', array(), 'array');
			$data['form_id'] = $form->FormId;
			$row             = $this->getTable();

			if (!$row)
			{
				throw new Exception ('Could not get an instance of the Iyzico Table');
			}
			if (!$row->save($data))
			{
				throw new Exception ($row->getError());
			}
		}
		catch (Exception $e)
		{
			$application->enqueueMessage($e->getMessage(), 'error');
		}

		return true;
	}

	public function onRsformBackendFormCopy($args)
	{
		$formId = $args['formId'];
		$newFormId = $args['newFormId'];

		if ($row = $this->getTable())
		{
			if ($row->load($formId))
			{
				$row->form_id = $newFormId;
				if ($row->check())
				{
					$row->store();
				}
			}
		}
	}

	/**
	 * @param $tabs
	 */
	public function onRsformBackendAfterShowConfigurationTabs($tabs)
	{
		$tabs->addTitle(Text::_('PLG_SYSTEM_RSFPIYZICO_LABEL'), 'page-iyzico');
		$tabs->addContent($this->configurationScreen());
	}

	private function loadFormData()
	{
		$data 	= array();
		$db 	= Factory::getDbo();

		$query = $db->getQuery(true)
			->select('*')
			->from($db->qn('#__rsform_config'))
			->where($db->qn('SettingName') . ' LIKE ' . $db->q('iyzico.%', false));
		if ($results = $db->setQuery($query)->loadObjectList())
		{
			foreach ($results as $result)
			{
				$data[$result->SettingName] = $result->SettingValue;
			}
		}

		return $data;
	}

	/**
	 * @return string
	 */
	public function configurationScreen()
	{
		ob_start();

		Form::addFormPath(__DIR__ . '/forms');

		$form = Form::getInstance( 'plg_system_rsfpiyzico.configuration', 'configuration', array('control' => 'rsformConfig'), false, false );
		$form->bind($this->loadFormData());

		?>
		<div id="page-iyzico" class="form-horizontal">
		<?php
		foreach ($form->getFieldsets() as $fieldset)
		{
			if ($fields = $form->getFieldset($fieldset->name))
			{
				foreach ($fields as $field)
				{
					// This is a workaround because our fields are named "iyzico." and Joomla! uses the dot as a separator and transforms the JSON into [iyzico][api] instead of [iyzico.api].
					echo str_replace('"rsformConfig[iyzico][', '"rsformConfig[iyzico.', $form->renderField($field->fieldname));
				}
			}
		}
		?>
		</div>
		<?php

		$contents = ob_get_contents();
		ob_end_clean();

		return $contents;
	}

	/**
	 * @param $formId
	 *
	 * @return mixed
	 */
	protected function _getFields($formId)
	{
		$db    = Factory::getDbo();
		$query = $db->getQuery(true)
			->select($db->qn('p.PropertyValue'))
			->from($db->qn('#__rsform_components', 'c'))
			->join('LEFT', $db->qn('#__rsform_properties', 'p') . ' ON (' . $db->qn('c.ComponentId') . '=' . $db->qn('p.ComponentId') . ')')
			->where($db->qn('c.FormId') . '=' . $db->q($formId))
			->where($db->qn('p.PropertyName') . '=' . $db->q('NAME'))
			->order($db->qn('c.Order') . ' ' . $db->escape('ASC'));

		return $db->setQuery($query)->loadColumn();
	}

	/**
	 * @param $price
	 * @param $amount
	 * @param $type
	 *
	 * @return mixed
	 */
	public function calcTax($price, $amount, $type)
	{
		$price = (float) $price;
		$amount = (float) $amount;
		switch ($type)
		{
			case false:
				$price = $price + (($price * $amount) / 100);
				break;

			case true:
				$price = $price + $amount;
				break;
		}

		return $price;
	}

	/**
	 * @return array
	 */
	private function standardFields()
	{
	    return array(
	        'buyer' => array('id', 'name', 'surname', 'gsmnumber', 'email', 'identitynumber', 'registrationaddress', 'city', 'country', 'zipcode'),
            'shippingaddress' => array('contactname', 'city', 'country', 'address', 'zipcode'),
            'billingaddress' => array('contactname', 'city', 'country', 'address', 'zipcode'),
            'basketitems' => array('category1', 'category2', 'itemtype'),
            'request' => array('paymentgroup')
        );
	}

	/**
	 * @param $formId
	 */
	public function onRsformFormDelete($formId)
	{
		if ($row = $this->getTable())
		{
			$row->delete($formId);
		}
	}

	/**
	 * @param $form
	 * @param $xml
	 * @param $fields
	 */
	public function onRsformFormBackup($form, $xml, $fields)
	{
		if ($row = $this->getTable())
		{
			if ($row->load($form->FormId))
			{
				$row->check();

				$data = $row->getProperties();
				unset($data['form_id']);

				$xml->add('iyzico');
				foreach ($data as $property => $value)
				{
					$xml->add($property, $value);
				}
				$xml->add('/iyzico');
			}
		}
	}

	/**
	 * @param $form
	 * @param $xml
	 * @param $fields
	 */
	public function onRsformFormRestore($form, $xml, $fields)
	{
		if (isset($xml->iyzico))
		{
			$data = array(
				'form_id' => $form->FormId
			);
			foreach ($xml->iyzico->children() as $property => $value)
			{
				$data[$property] = (string) $value;
			}
			$row = $this->getTable();
			$row->save($data);
		}
	}

	/**
	 *
	 */
	public function onRsformBackendFormRestoreTruncate()
	{
		Factory::getDbo()->truncateTable('#__rsform_iyzico');
	}

	protected function getTable()
	{
		return Table::getInstance('RSForm_Iyzico', 'Table');
	}
}

/**
 * Class RSFormProIyzico
 */
class RSFormProIyzico
{
	/**
	 * @return RSFormProIyzico
	 */
	public static function getInstance()
	{
		static $inst;
		if (!$inst)
		{
			$inst = new RSFormProIyzico;
		}

		return $inst;
	}

	/**
	 * RSFormProIyzico constructor.
	 */
	public function __construct()
	{
		require_once JPATH_ADMINISTRATOR . '/components/com_rsform/helpers/iyzico/IyzipayBootstrap.php';

		IyzipayBootstrap::init();
	}

	public static function options()
	{
		$options = new \Iyzipay\Options();

		if (RSFormProHelper::getConfig('iyzico.mode'))
        {
	        $options->setApiKey(RSFormProHelper::getConfig('iyzico.live_api'));
	        $options->setSecretKey(RSFormProHelper::getConfig('iyzico.live_secret'));
	        $options->setBaseUrl('https://api.iyzipay.com');
        }
        else
        {
	        $options->setApiKey(RSFormProHelper::getConfig('iyzico.sandbox_api'));
	        $options->setSecretKey(RSFormProHelper::getConfig('iyzico.sandbox_secret'));
	        $options->setBaseUrl('https://sandbox-api.iyzipay.com');
        }

		return $options;
	}

	public static function getLocale()
    {
        $locale = RSFormProHelper::getConfig('iyzico.locale');

        if ($locale === 'auto')
        {
	        $tag = Factory::getLanguage()->getTag();
	        if (strpos($tag, '-') !== false)
	        {
		        list($locale, $tmp) = explode('-', $tag, 2);
	        }
        }

        switch (strtoupper($locale))
        {
            default:
	            return \Iyzipay\Model\Locale::TR;
                break;

            case 'EN':
            case 'US':
            case 'CA':
	            return \Iyzipay\Model\Locale::EN;
                break;
        }
    }
}