Your IP : 216.73.216.240


Current Path : /home/juvelize/www/plugins/icagenda/payment_paypal/
Upload File :
Current File : /home/juvelize/www/plugins/icagenda/payment_paypal/payment_paypal.php

<?php
/**
 *----------------------------------------------------------------------------
 * iCagenda     Plugin Payment :: Paypal
 *----------------------------------------------------------------------------
 * @version     2.0.1 2024-05-14
 *
 * @package     iCagenda.Plugin
 * @subpackage  icagenda.payment_paypal
 * @link        https://www.icagenda.com
 *
 * @author      Cyril Rezé
 * @copyright   (c) 2012-2024 Cyril Rezé / iCagenda. All rights reserved.
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @since       iCagenda 3.8
 *----------------------------------------------------------------------------
*/

defined('_JEXEC') or die;

use Joomla\CMS\Form\Form;
use iCutilities\Event\Event as icagendaEvent;

/**
 * plgIcagendaPayment_paypal
 */
class plgIcagendaPayment_paypal extends JPlugin
{
	/**
	 * Load the language file on instantiation.
	 *
	 * @var boolean
	 * @since 1.0
	 */
	protected $autoloadLanguage = true;

	function onContentPrepareForm(Form $form, $data)
	{
		$app    = JFactory::getApplication();
		$input  = $app->input;
		$option = $input->get('option');
		$view   = $input->get('view');
		$layout = $input->get('layout');

		$name = $form->getName();

		$iCparams = JComponentHelper::getParams('com_icagenda');

		if ($name == 'com_icagenda.event'
			&& $iCparams->get('icsys') == 'pro')
		{
			JForm::addFormPath(__DIR__ . '/forms');
			$form->loadFile('event_actions', true);

			$statusReg       = ($iCparams->get('statutReg') == 1) ? 'statutReg!:0' : 'statutReg:1';
			$actions_control = ($iCparams->get('registration_actions') == 'tickets.payment')
								? '[AND]registration_actions!:0'
								: '[AND]registration_actions!:0[AND]registration_actions!:';
			$sandbox_mode    = ($iCparams->get('paypal_mode', 1) == 1)
								? ''
								: '[AND]paypal_mode!:';
			$production_mode = ($iCparams->get('paypal_mode', 1) == 0)
								? ''
								: '[AND]paypal_mode!:';

			$asterisk = ' *';

			$form->setFieldAttribute('registration_actions_title', 'showon', $statusReg, 'params');
			$form->setFieldAttribute('registration_actions', 'showon', $statusReg, 'params');
			$form->setFieldAttribute('registration_actions_spacer', 'showon', $statusReg, 'params');

			$form->setFieldAttribute('paypal_mode', 'showon', $statusReg . $actions_control, 'params');
			$form->setFieldAttribute('sandbox_account', 'showon', $statusReg . $actions_control . '[AND]paypal_mode:1', 'params');
			$form->setFieldAttribute('sandbox_account', 'label', JText::_('PLG_ICAGENDA_PAYMENT_PAYPAL_SANDBOX_ACCOUNT_LABEL') . $asterisk, 'params');
			$form->setFieldAttribute('sandbox_clientID', 'showon', $statusReg . $actions_control . '[AND]paypal_mode:1', 'params');
			$form->setFieldAttribute('sandbox_clientID', 'label', JText::_('PLG_ICAGENDA_PAYMENT_PAYPAL_SANDBOX_CLIENTID_LABEL') . $asterisk, 'params');
			$form->setFieldAttribute('sandbox_secret', 'showon', $statusReg . $actions_control . '[AND]paypal_mode:1', 'params');
			$form->setFieldAttribute('sandbox_secret', 'label', JText::_('PLG_ICAGENDA_PAYMENT_PAYPAL_SANDBOX_SECRET_LABEL') . $asterisk, 'params');
			$form->setFieldAttribute('paypal_account', 'showon', $statusReg . $actions_control . '[AND]paypal_mode:0', 'params');
			$form->setFieldAttribute('paypal_account', 'label', JText::_('PLG_ICAGENDA_PAYMENT_PAYPAL_LIVE_ACCOUNT_LABEL') . $asterisk, 'params');
			$form->setFieldAttribute('paypal_clientID', 'showon', $statusReg . $actions_control . '[AND]paypal_mode:0', 'params');
			$form->setFieldAttribute('paypal_clientID', 'label', JText::_('PLG_ICAGENDA_PAYMENT_PAYPAL_LIVE_CLIENTID_LABEL') . $asterisk, 'params');
			$form->setFieldAttribute('paypal_secret', 'showon', $statusReg . $actions_control . '[AND]paypal_mode:0', 'params');
			$form->setFieldAttribute('paypal_secret', 'label', JText::_('PLG_ICAGENDA_PAYMENT_PAYPAL_LIVE_SECRET_LABEL') . $asterisk, 'params');

			$form->setFieldAttribute('paypal_options_label', 'showon', $statusReg . $actions_control, 'params');
			$form->setFieldAttribute('ticket_price', 'showon', $statusReg . $actions_control, 'params');
			$form->setFieldAttribute('currency_code', 'showon', $statusReg . $actions_control, 'params');

			$form->setFieldAttribute('payment_options', 'showon', $statusReg . $actions_control, 'params');
			$form->setFieldAttribute('consent_payment', 'showon', $statusReg . $actions_control, 'params');
			$form->setFieldAttribute('consent_payment_label', 'showon', $statusReg . $actions_control . '[AND]consent_payment:1', 'params');
			$form->setFieldAttribute('consent_payment_text', 'showon', $statusReg . $actions_control . '[AND]consent_payment:1', 'params');

			$eventParams = icagendaEvent::getParams($input->getInt('id'));
			$statutReg = $eventParams->get('statutReg', $iCparams->get('statutReg'));
			$registration_actions = $eventParams->get('registration_actions', $iCparams->get('registration_actions'));

			$consentPayment = $eventParams->get('consent_payment', $iCparams->get('consent_payment'));

			JFactory::getDocument()->addScriptDeclaration("
				document.addEventListener('DOMContentLoaded', function() {
					var mode0 = document.getElementById('jform_params_paypal_mode0'),
						mode1 = document.getElementById('jform_params_paypal_mode1'),
						mode2 = document.getElementById('jform_params_paypal_mode2'),
						sa = document.getElementById('jform_params_sandbox_account'),
						sc = document.getElementById('jform_params_sandbox_clientID'),
						ss = document.getElementById('jform_params_sandbox_secret'),
						pa = document.getElementById('jform_params_paypal_account'),
						pc = document.getElementById('jform_params_paypal_clientID'),
						ps = document.getElementById('jform_params_paypal_secret');

					if (mode1.labels[0].className == 'btn active btn-success') {
						setSandbox();
					}
					else if (mode2.labels[0].className == 'btn active btn-danger') {
						setProduction();
					}
					else {
						setGlobal();
					}

					mode0.addEventListener('click', setGlobal);
					mode1.addEventListener('click', setSandbox);
					mode2.addEventListener('click', setProduction);

					function setGlobal() {
						sa.removeAttribute('required');
						sc.removeAttribute('required');
						ss.removeAttribute('required');
						pa.removeAttribute('required');
						pc.removeAttribute('required');
						ps.removeAttribute('required');
					}
					function setSandbox() {
						sa.setAttribute('required', 'true');
						sc.setAttribute('required', 'true');
						ss.setAttribute('required', 'true');
						pa.removeAttribute('required');
						pc.removeAttribute('required');
						ps.removeAttribute('required');
					}
					function setProduction() {
						pa.setAttribute('required', 'true');
						pc.setAttribute('required', 'true');
						ps.setAttribute('required', 'true');
						sa.removeAttribute('required');
						sc.removeAttribute('required');
						ss.removeAttribute('required');
					}


					var paymentPaypal = document.getElementById('jform_params_registration_actions'),
						statutReg = document.getElementById('jform_params_statutReg'),
						paymentPaypalGlobal = '" . $iCparams->get('registration_actions') . "',
						statutRegGlobal = '" . $iCparams->get('statutReg') . "';

					if (paymentPaypal == '') {
						paymentPaypal = paymentPaypalGlobal;
					}
					if (statutReg == '') {
						statutReg = statutRegGlobal;
					}

					if (paymentPaypal == '' && statutReg == '')
					{
						consentIsDisabled();
					}

					var registrationDefault = document.getElementById('jform_params_statutReg0'),
						registrationEnabled = document.getElementById('jform_params_statutReg1'),
						registrationDisabled = document.getElementById('jform_params_statutReg2'),
						paymentDefault = document.getElementById('jform_params_registration_actions0'),
						paymentEnabled = document.getElementById('jform_params_registration_actions1'),
						paymentDisabled = document.getElementById('jform_params_registration_actions2'),
						consentDefault = document.getElementById('jform_params_consent_payment0'),
						consentEnabled = document.getElementById('jform_params_consent_payment1'),
						consentDisabled = document.getElementById('jform_params_consent_payment2'),
						consentLabel = document.getElementById('jform_params_consent_payment_text').labels[0].textContent;
						consentText = document.getElementById('jform_params_consent_payment_text').value,
						consentPayment = '" . $consentPayment . "';

					if (consentEnabled.checked == true && '" . $registration_actions . "' == 'tickets.payment' && '" . $statutReg . "' == '1') {
						consentIsEnabled();
//					} else if (consentPayment == 1 && '" . $registration_actions . "' == 'tickets.payment' && '" . $statutReg . "' == '1') {
//						consentIsEnabled();
					} else if ('" . $statutReg . "' == '0') {
						consentIsDisabled();
					} else if ('" . $registration_actions . "' == '') {
						consentIsDisabled();
					} else {
						consentIsDisabled();
					}

					registrationDefault.addEventListener('click', consentIsDefault);
					registrationEnabled.addEventListener('click', consentIsEnabled);
					if (registrationDisabled) registrationDisabled.addEventListener('click', consentIsDisabled);
					paymentDefault.addEventListener('click', consentIsDefault);
					paymentEnabled.addEventListener('click', consentIsEnabled);
					paymentDisabled.addEventListener('click', consentIsDisabled);
					consentDefault.addEventListener('click', consentIsDefault);
					consentEnabled.addEventListener('click', consentIsEnabled);
					consentDisabled.addEventListener('click', consentIsDisabled);

					function consentIsDefault() {
						if (consentLabel.indexOf('*') == -1) {
							document.getElementById('jform_params_consent_payment_text-lbl').innerHTML = consentLabel + ' *';
						}
						if (registrationDefault.checked == true
							&& '" . $iCparams->get('statutReg') . "' == '1'
							&& ((paymentDefault.checked == true && '" . $iCparams->get('registration_actions') . "' == 'tickets.payment')
								|| paymentEnabled.checked == true)
							&& consentEnabled.checked == true
							)
						{
							document.getElementById('jform_params_consent_payment_text-lbl').classList.add('required');
							document.getElementById('jform_params_consent_payment_text').setAttribute('required', 'true');
						}
//						else if (consentEnabled.checked == true && '" . $registration_actions . "' == 'tickets.payment' && '" . $statutReg . "' == '1' && registrationDefault.checked == false)
//						{
//							document.getElementById('jform_params_consent_payment_text-lbl').classList.add('required');
//							document.getElementById('jform_params_consent_payment_text').setAttribute('required', 'true');
//						}
						else
						{
							document.getElementById('jform_params_consent_payment_text-lbl').classList.remove('required');
							document.getElementById('jform_params_consent_payment_text').removeAttribute('required');
						}
					}
					function consentIsEnabled() {
						if (consentLabel.indexOf('*') == -1) {
							document.getElementById('jform_params_consent_payment_text-lbl').innerHTML = consentLabel + ' *';
						}
						if (((paymentDefault.checked == true && '" . $iCparams->get('registration_actions') . "' == 'tickets.payment')
								|| paymentEnabled.checked == true)
							&& consentEnabled.checked == true) {
							document.getElementById('jform_params_consent_payment_text-lbl').classList.add('required');
							document.getElementById('jform_params_consent_payment_text').setAttribute('required', 'true');
						} else {
							document.getElementById('jform_params_consent_payment_text-lbl').classList.remove('required');
							document.getElementById('jform_params_consent_payment_text').removeAttribute('required');
						}
					}
					function consentIsDisabled() {
						document.getElementById('jform_params_consent_payment_text-lbl').classList.remove('required');
						document.getElementById('jform_params_consent_payment_text').removeAttribute('required');
					}
				});
			");
		}

		if ($name == 'com_icagenda.registration'
			&& $iCparams->get('icsys') == 'pro')
		{
			$eventID   = $app->input->getInt('id') ?: $app->input->getInt('eventID');
			$eventParams = icagendaEvent::getParams($eventID);
			$evtParams = ($eventParams->get('consent_payment') == '') ? $iCparams : $eventParams;

			$consentboxLabel = $evtParams->get('consent_payment_label', 'COM_ICAGENDA_REGISTRATION_CONSENT_PAYMENT_LABEL');
			$consentboxText  = $evtParams->get('consent_payment_text');

			$registration_actions = (bool) (($evtParams->get('registration_actions') == 'tickets.payment')
									|| ($eventParams->get('registration_actions') == ''
										&& $iCparams->get('registration_actions') == 'tickets.payment'));
			$consent_payment      = $evtParams->get('consent_payment');
			$consent_payment_text = trim($evtParams->get('consent_payment_text', ''));

			if ($consent_payment && $registration_actions && $consent_payment_text)
			{
				// Display Payment Consent if Payment is enabled and Consent Text is set.
				JForm::addFormPath(__DIR__ . '/forms');
				$form->loadFile('payment_consent', true);

				$form->setFieldAttribute('consent_payment', 'label', $consentboxLabel, 'consent');

				$consent_payment = $form->getFieldXml('consent_payment', 'consent');
				$child = $consent_payment->addChild('option', $consentboxText);
				$child->addAttribute('value', 'payment_consent');
			}
		}

		if ($name == 'com_config.component'
			&& $app->isClient('administrator')
			&& $app->input->get('component') == 'com_icagenda'
			&& $iCparams->get('icsys') == 'pro')
		{
			JForm::addFormPath(__DIR__ . '/forms');
			$form->loadFile('config_payment', false);

			JFactory::getDocument()->addScriptDeclaration("
				document.addEventListener('DOMContentLoaded', function() {
					var consentDisabled = document.getElementById('jform_consent_payment0'),
						consentEnabled = document.getElementById('jform_consent_payment1'),
						consentLabel = document.getElementById('jform_consent_payment_text').labels[0].textContent;

					if (consentEnabled.check == true) {
						consentIsEnabled();
					} else {
						consentIsDisabled();
					}

					consentDisabled.addEventListener('click', consentIsDisabled);
					consentEnabled.addEventListener('click', consentIsEnabled);

					function consentIsDisabled() {
						document.getElementById('jform_consent_payment_text-lbl').classList.remove('required');
						document.getElementById('jform_consent_payment_text').removeAttribute('required');
					}
					function consentIsEnabled() {
						if (consentLabel.indexOf('*') == -1) {
							document.getElementById('jform_consent_payment_text-lbl').innerHTML = consentLabel + ' *';
						}
						document.getElementById('jform_consent_payment_text-lbl').classList.add('required');
						document.getElementById('jform_consent_payment_text').setAttribute('required', 'true');
					}
				});
			");
		}

		return true;
	}


	public function onICagendaRegistrationsGetItems($context, &$item)
	{
		if ($context == 'com_icagenda.registrations')
		{
			if ( ! isset($item->actions)) $item->actions = array();

			$db = JFactory::getDbo();
			$query = $db->getQuery(true)
				->select('po.*')
				->from('#__icagenda_payment_orders AS po')
				->where('po.registration_id = ' . (int) $item->id);
			$db->setQuery($query);

			$result = $db->loadObjectList();

			if (count($result) > 0)
			{
				$item->actions['payment_paypal.payment_details'] = $result;
			}
			else
			{
				$query = $db->getQuery(true)
					->select('r.*')
					->from('#__icagenda_registration AS r')
					->where('r.status = 2')
					->where('r.id = ' . (int) $item->id);
				$db->setQuery($query);

				$result = $db->loadObjectList();

				if ($result)
				{
					$item->actions['payment_paypal.payment_details'] = $result;
				}
			}
		}
	}


	public function onICagendaRegistrationActionsFieldPeople($context, &$item)
	{
		$ticket_price  = $item->params->get('ticket_price', '0.00');
		$currency_code = $item->params->get('currency_code', 'USD');
		$tickets       = isset($item->default_tickets) ? $item->default_tickets : $item->tickets;

		$priceLabel  = JText::_('PLG_ICAGENDA_TICKETS_FIELD_PEOPLE_TICKET_PRICE_LABEL');

		// @todo: create a layout
		if ($tickets > 1)
		{
			$style = ';';
			$priceInput  = '<div style="padding-top: 5px;">' . JText::sprintf('PLG_ICAGENDA_TICKETS_FIELD_PEOPLE_TICKET_PRICE_AND_CURRENCY', $ticket_price, $currency_code) . '</div>';
		}
		else
		{
			$style = 'font-weight: bolder;';
			$priceInput  = '<div style="padding-top: 4px; font-size: larger;">' . JText::sprintf('PLG_ICAGENDA_TICKETS_FIELD_PEOPLE_TICKET_PRICE_AND_CURRENCY', $ticket_price, $currency_code) . '</div>';
		}

		$html = '</div></div><div style="clear: both; ' . $style . '"><div>';

		$layout = new JLayoutFile('joomla.form.renderfield', $basePath = null);

		$ticketPrice = array('label' => $priceLabel, 'input' => $priceInput, 'name' => 'ticketPrice');

		$html.= $layout->render($ticketPrice);

		if ($tickets > 1)
		{
			JFactory::getDocument()->addScriptDeclaration('
				jQuery(document).ready(function($) {
					var tickets = $("#jform_people");
					$("#payment-total").html($(tickets).val() * ' . $ticket_price . ');
					$(tickets).change(function() {
						$("#payment-total").html($(tickets).val() * ' . $ticket_price . ');
					})
				});
			');

			$totalLabel   = '<span style="font-weight: bolder;">' . JText::_('PLG_ICAGENDA_TICKETS_FIELD_PEOPLE_PAYMENT_TOTAL_LABEL') . '</span>';
			$totalInput   = '<div style="padding-top: 4px; font-size: larger; font-weight: bolder;"><div style="display: inline-block;" id="payment-total">0.00</div> ' . $currency_code . '</div>';
			$PaymentTotal = array('label' => $totalLabel, 'input' => $totalInput, 'name' => 'PaymentTotal');

			$html.= $layout->render($PaymentTotal);
		}

//		$html = '<br />' . JText::sprintf('PLG_ICAGENDA_TICKETS_FIELD_PEOPLE_TICKET_PRICE_LABEL', $ticket_price, $currency_code)
//				. '<br /><div class="btn ic-btn-total">' . JText::_('Total ')
//				. '<span class="badge badge-info">'
//				. '<div style="display: inline-block;" id="payment-total">0.00</div> '
//				. $currency_code . '</span>'
//				. '</div>';

//		$html = '<div class="ticket-price-info">' . JText::sprintf('PLG_ICAGENDA_TICKETS_FIELD_PEOPLE_TICKET_PRICE_INFO', $ticket_price, $currency_code) . '</div><div>&nbsp;</div></div><div>';

		return $html;
	}

	public function onICagendaRegistrationActions($context, &$item, &$params)
	{
		$app   = JFactory::getApplication();
		$input = $app->input;

		$regdata = $app->getUserState('com_icagenda.registration.regdata', '');
		$regid   = $app->getUserState('com_icagenda.registration.regid', '');

		if ($input->getCmd('option') === 'com_icagenda'
			&& $input->getCmd('layout') === 'actions'
			&& $item
			&& $app->isClient('site')
			&& $regdata
			&& $regid
			)
		{
			// PayPal Params
			$paypal_mode        = $item->params->get('paypal_mode', 1);
			$sandbox_clientID   = ($paypal_mode != '')
								? $item->params->get('sandbox_clientID', '')
								: $params->get('sandbox_clientID', '');
			$paypal_clientID    = ($paypal_mode != '')
								? $item->params->get('paypal_clientID', '')
								: $params->get('paypal_clientID', '');

			$accessToken = self::getAccessToken();

			if ( ! $accessToken)
			{
				// @todo: add a redirection when PayPal Client Authentication failed (clientID and/or secret keys wrong).
				return false;
			}

			$environment        = $paypal_mode ? 'sandbox' : 'production';

			// Event Registration Options
			$ticket_price       = $item->params->get('ticket_price', '0.00');
			$currency_code      = $item->params->get('currency_code', 'USD');

			// Registration Data
			$nb_of_tickets      = (int) $regdata['people'];
			$total              = ($nb_of_tickets * $ticket_price);

			$paypalHtml = '<script src="https://www.paypalobjects.com/api/checkout.js"></script>';
			$paypalHtml.= '<div id="paypal-button-container"></div>';

			$paypalScript = "
<script>

	// Render the PayPal button
//	var EXECUTE_PAYMENT_URL = 'index.php?option=com_icagenda&view=registration&layout=actions';
	paypal.Button.render({

		// Set environment

		env: '" . $environment . "', // sandbox | production

		// Specify the style of the button

		commit: true,

		style: {
			layout: 'vertical',  // horizontal | vertical
			size:   'medium',    // medium | large | responsive
			shape:  'rect',      // pill | rect
			color:  'gold'       // gold | blue | silver | black
		},

		// Specify allowed and disallowed funding sources
		//
		// Options:
		// - paypal.FUNDING.CARD
		// - paypal.FUNDING.CREDIT
		// - paypal.FUNDING.ELV

		funding: {
			allowed: [ paypal.FUNDING.CARD ],
			disallowed: [ ]
		},

		// PayPal Client IDs
		// Create a PayPal app: https://developer.paypal.com/developer/applications/create

		client: {
			sandbox:    '" . $sandbox_clientID . "',
			production: '" . $paypal_clientID . "'
		},

		payment: function(data, actions) {
			return actions.payment.create({
				payment: {
					transactions: [
						{
							amount: { total: '" . $total . "', currency: '" . $currency_code . "' },
							item_list: {
								items: [
									{
									name: '" . htmlspecialchars(JText::plural('PLG_ICAGENDA_PAYMENT_PAYPAL_TICKETS_LABEL', $nb_of_tickets)) . "',
									description: '" . htmlspecialchars($item->title) . "',
									quantity: '" . $nb_of_tickets . "',
									price: '" . $ticket_price . "',
									currency: '" . $currency_code . "'
									}
								]
							}
						}
					],
//					note_to_payer: 'Contact us for any questions on your order.'
				}
			});
		},

		onAuthorize: function(data, actions) {

			var paymentID = data.paymentID,
				payerID = data.payerID,
				paymentToken = data.paymentToken;

			return actions.payment.get().then(function(data) {

				var getData = {
						total: data.transactions[0].amount.total,
						currency: data.transactions[0].amount.currency,
						paymentID: paymentID,
						payerID: payerID,
						paymentToken: paymentToken
					};

				var paymentData = btoa(JSON.stringify(getData));

				return actions.payment.execute().then(function() {

					window.location=('index.php?option=com_icagenda&task=registration.actions&eventID=" . $item->id . "&Itemid=" . $app->input->getInt('Itemid') . "&action=payment&type=paypal&processed=true&data='+paymentData);

				});
			});
		}

	}, '#paypal-button-container');

</script>
";
			
			return $paypalHtml . $paypalScript;
		}

		return false;
	}


	public function onICagendaRegistrationActionsAbandon($context, $data, $regid = null)
	{
		// Cancellation of the registration before payment should not be stored in database.
		if ($regid && empty($data))
		{
			$db = JFactory::getDbo();
			$query = $db->getQuery(true)
				->delete($db->quoteName('#__icagenda_registration'))
				->where('id = ' . (int) $regid);
			$db->setQuery($query);
			$db->execute();

			return true;
		}

		return false;
	}

	public function onICagendaRegistrationActionsComplete($context, $data, $regData, $eventID)
	{
		$app   = JFactory::getApplication();
		$user  = JFactory::getUser();

		$data  = base64_decode($data);
		$regid = $regData['id'];

		if ($data && $regid)
		{
			$paymentPayPal = self::paymentPayPalCheck($data, $regData, $eventID);

			if ($paymentPayPal)
			{
				// Status (item published state)
				$state  = '1';

				// Payment Registration State
				$transaction_state = $paymentPayPal->transactions[0]->related_resources[0]->sale->state;
				$status            = ($transaction_state == 'completed') ? '1' : '2';

				// Update Registration
				$db = JFactory::getDbo();
				$query = $db->getQuery(true)
					->update($db->quoteName('#__icagenda_registration'))
					->set('state = ' . (int) $state)
					->set('status = ' . (int) $status)
//					->set('params = ' . $db->quote($data))
					->where('id = ' . (int) $regid);
				$db->setQuery($query);
				$db->execute();

				// Save Order
				$order = new \stdClass();
				$order->registration_id      = $regid;
				$order->user_id              = $user->get('id');
				$order->order_amount_total   = $paymentPayPal->transactions[0]->amount->total;
				$order->order_currency       = $paymentPayPal->transactions[0]->amount->currency;
				$order->order_processor      = $paymentPayPal->payer->payment_method;
				$order->order_ref            = $paymentPayPal->id;
//				$order->order_state          = $paymentPayPal->state;
				$order->order_state          = $paymentPayPal->transactions[0]->related_resources[0]->sale->state;
				$order->order_transaction_id = $paymentPayPal->transactions[0]->related_resources[0]->sale->id;
				$order->published            = '1';
				$order->created              = date('Y-m-d H:i:s', strtotime($paymentPayPal->create_time));

				$result = $db->insertObject('#__icagenda_payment_orders', $order, 'id');

				// Save Ticket (unique ticket type)
				$ticket = new \stdClass();
				$ticket->order_id        = $order->id;
				$ticket->ticket_id       = '0'; // none when single ticket type.
				$ticket->ticket_price    = $paymentPayPal->transactions[0]->item_list->items[0]->price;
				$ticket->ticket_quantity = $paymentPayPal->transactions[0]->item_list->items[0]->quantity;
				$ticket->ticket_currency = $paymentPayPal->transactions[0]->item_list->items[0]->currency;
				$ticket->published       = '1';
				$ticket->created         = date('Y-m-d H:i:s', strtotime($paymentPayPal->create_time));

				$result = $db->insertObject('#__icagenda_payment_tickets', $ticket, 'id');

				return true;
			}
			else
			{
				$app->enqueueMessage(Jtext::_('PLG_ICAGENDA_PAYMENT_PAYPAL_ERROR_TRANSACTION_NOT_COMPLETED_MESSAGE'), 'error');
			}
		}

		return false;
	}


	public function onICagendaRegistrationActionsCompleteEmail($context, $data, $regData)
	{
		$data = json_decode(base64_decode($data));

		// MAIL REPLACEMENTS
		$replacements = array(
				'[TICKETS]' => $regData->people . JText::_('\n')
								. JText::_('PLG_ICAGENDA_PAYMENT_PAYPAL_COMPLETE_PAYMENT_ID_LABEL') . ': ' . $data->paymentID . JText::_('\n')
								. JText::_('PLG_ICAGENDA_PAYMENT_PAYPAL_COMPLETE_PAYMENT_TOTAL_LABEL') . ': ' . $data->total . ' ' . $data->currency,
		);

		return $replacements;
	}


	public function onICagendaRegistrationCompleteAfterDataDisplay($context, &$item, &$params)
	{
		$app = JFactory::getApplication();
		$input = $app->input;

		if ($input->getCmd('option') === 'com_icagenda'
			&& $input->getCmd('view') === 'registration'
			&& $input->getCmd('layout') === 'complete'
			&& $app->isClient('site'))
		{

			$id = $app->input->getInt('eventID');

			$action    = $app->input->get('action', '');
			$data      = $app->input->get('data', null);
			$complete  = $app->input->get('complete', '');
			$status    = $app->input->get('status', '');

			$regid     = $app->getUserState('com_icagenda.registration.regid', '');
			$regData   = $app->getUserState('com_icagenda.registration.regdata', null );

			$data      = $app->getUserState('com_icagenda.actions.data', null);
			
			$data = $data ? json_decode(base64_decode($data)) : '';

			$content =  '';

			if ($data)
			{
				$content.=  '<div class="ic-divRow">';
				$content.=  '<div class="ic-label">' . JText::_('PLG_ICAGENDA_PAYMENT_PAYPAL_COMPLETE_PAYMENT_ID_LABEL') . '</div>'
							. '<div class="ic-value">' . $data->paymentID . '</div>';
				$content.=  '</div>';

				$content.=  '<div class="ic-divRow">';
				$content.=  '<div class="ic-label">' . JText::_('PLG_ICAGENDA_PAYMENT_PAYPAL_COMPLETE_PAYMENT_TOTAL_LABEL') . '</div>'
							. '<div class="ic-value">' . $data->total . ' ' . $data->currency . '</div>';
				$content.=  '</div>';
			}

			// Flush the data from the session.
			$app->setUserState('com_icagenda.registration.regid', null);
			$app->setUserState('com_icagenda.registration.regdata', null );
			$app->setUserState('com_icagenda.registration.actions', null );
			$app->setUserState('com_icagenda.actions.data', null);

			return $content;
		}
	}

	public function getPaypalCredentials()
	{
		$app   = JFactory::getApplication();
		$input = $app->input;

		// PayPal Params
		$eventParams    = icagendaEvent::getParams($input->getInt('id'));

		$paypalParams   = ($eventParams->get('paypal_mode') == '')
						? JComponentHelper::getParams('com_icagenda')
						: $eventParams;

		$paypal_mode        = $paypalParams->get('paypal_mode', 1);			
		$sandbox_account    = $paypalParams->get('sandbox_account');			
		$sandbox_clientID   = $paypalParams->get('sandbox_clientID');			
		$sandbox_secret     = $paypalParams->get('sandbox_secret');			
		$paypal_account     = $paypalParams->get('paypal_account');			
		$paypal_clientID    = $paypalParams->get('paypal_clientID');			
		$paypal_secret      = $paypalParams->get('paypal_secret');			

		// Set PayPal Credentials
		$PayPalCredentials = new \stdClass();

		$PayPalCredentials->paypal_mode     = $paypal_mode;			
		$PayPalCredentials->PayPal_BASE_URL	= $paypal_mode ? 'https://api.sandbox.paypal.com/v1/' : 'https://api.paypal.com/v1/';
		$PayPalCredentials->account         = $paypal_mode ? $sandbox_account : $paypal_account;
		$PayPalCredentials->clientId        = $paypal_mode ? $sandbox_clientID : $paypal_clientID;
		$PayPalCredentials->secret          = $paypal_mode ? $sandbox_secret : $paypal_secret;

		return $PayPalCredentials;
	}

	public function getAccessToken()
	{
		$app = JFactory::getApplication();

		$PayPalCredentials = self::getPaypalCredentials();			
		$accessToken       = null;

		// Get an access token - cURL
		$curl = curl_init();

		curl_setopt($curl, CURLOPT_URL, $PayPalCredentials->PayPal_BASE_URL . 'oauth2/token');
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_USERPWD, $PayPalCredentials->clientId . ":" . $PayPalCredentials->secret);
		curl_setopt($curl, CURLOPT_POSTFIELDS, "grant_type=client_credentials");

		$result = curl_exec($curl);

		curl_close($curl);

		if (empty($result))
		{
			$app->enqueueMessage('The connection to PayPal failed.');

			return false;
		}

		$json = json_decode($result);

		if (isset($json->error))
		{
			$app->enqueueMessage(JText::sprintf('PLG_ICAGENDA_PAYMENT_PAYPAL_ERROR_CONNECTION_MESSAGE', $json->error, $json->error_description), 'error');

			return false;
		}

		$accessToken = $json->access_token;

		return $accessToken;
	}

	public function paymentPayPalCheck($data, $regData, $eventID)
	{
		$app         = JFactory::getApplication();
		$eventParams = icagendaEvent::getParams($eventID);

		$PayPalCredentials  = self::getPaypalCredentials();			
		$accessToken        = self::getAccessToken();

		if ( ! $accessToken)
		{
			return false;
		}
		else
		{
			$ticket = json_decode($data);

			$curl = curl_init($PayPalCredentials->PayPal_BASE_URL . 'payments/payment/' . $ticket->paymentID);

			curl_setopt($curl, CURLOPT_POST, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_HEADER, false);
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_HTTPHEADER, array(
				'Authorization: Bearer ' . $accessToken,
				'Accept: application/json',
				'Content-Type: application/xml'
			));

			$response = curl_exec($curl);
			$result   = json_decode($response);

			$total    = $result->transactions[0]->amount->total;
			$currency = $result->transactions[0]->amount->currency;
			$state    = $result->transactions[0]->related_resources[0]->sale->state;
			$payee    = $result->transactions[0]->payee->email;

			curl_close($curl);

			// Event Ticket Options
			$ticket_price  = $eventParams->get('ticket_price', '0.00');			
			$currency_code = $eventParams->get('currency_code', 'USD');			

			// Registration Data
			$nb_of_tickets = (int) $regData['people'];			
			$total_price   = ($nb_of_tickets * $ticket_price);			

			// The status of the captured payment.
			// The possible values are:
			//    • COMPLETED. The funds for this captured payment were credited to the payee's PayPal account.
			//    • DECLINED. The funds could not be captured.
			//    • PARTIALLY_REFUNDED. An amount less than this captured payment's amount was partially refunded to the payer.
			//    • PENDING. The funds for this captured payment was not yet credited to the payee's PayPal account. For more information, see status.details.
			//    • REFUNDED. An amount greater than or equal to this captured payment's amount was refunded to the payer.

			if ($state == 'completed'
				&& $total == $total_price
				&& $currency == $currency_code
				&& $payee == $PayPalCredentials->account
				)
			{
				return $result;
			}
			else
			{
				return false;
			}
		}
	}
}