<?php
/**
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @copyright   Copyright (C) 2016-2024 CMExension
 * @license     GNU General Public License version 2 or later
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Router\Route;

use Joomla\CMS\Plugin\PluginHelper;

/**
 * Controller for com_cmgiftcard.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class CMGiftCardController extends BaseController
{
	/**
	 * Method to display a view.
	 *
	 * @param   boolean  $cachable   If true, the view output will be cached
	 * @param   array    $urlparams  An array of safe url parameters and their variable types, for valid values see {@link JFilterInput::clean()}.
	 *
	 * @return  BaseController  This object to support chaining.
	 *
	 * @since   1.0.0
	 */
	public function display($cachable = false, $urlparams = array())
	{
		$cachable = false;

		// Set the default view name and format from the Request.
		$vName = $this->input->get('view', 'default');
		$this->input->set('view', $vName);

		if ($vName == 'form')
		{
			$type = $this->input->get('type', '');

			if ($type != 'electronic' && $type != 'physical')
			{
				$this->setRedirect(CMGiftCardHelper::prepareRoute('index.php?option=com_cmgiftcard&view=default'));

				return true;
			}
		}
		elseif (($vName == 'orders' || $vName == 'order') && Factory::getUser()->guest)
		{
			$returnUrl = base64_encode(Uri::getInstance()->toString());
			$this->setMessage(Text::_('JGLOBAL_YOU_MUST_LOGIN_FIRST'));
			$this->setRedirect(Route::_('index.php?option=com_users&view=login&return=' . $returnUrl, false));

			return true;
		}
		elseif ($vName == 'cards' || $vName == 'card' || $vName == 'staff')
		{
			$user = Factory::getUser();

			if ($user->guest)
			{
				$returnUrl = base64_encode(Uri::getInstance()->toString());
				$this->setMessage(Text::_('JGLOBAL_YOU_MUST_LOGIN_FIRST'));
				$this->setRedirect(Route::_('index.php?option=com_users&view=login&return=' . $returnUrl, false));

				return true;
			}

			$staffGroup = ComponentHelper::getParams('com_cmgiftcard')->get('staff_group');
			$isStaff = false;

			if ($staffGroup > 0)
			{
				$userGroups = $user->groups;

				if (isset($userGroups[$staffGroup]))
				{
					$isStaff = true;
				}
			}

			if (!$isStaff)
			{
				CMGiftCardHelper::throwException(Text::_('JERROR_ALERTNOAUTHOR'), 403);
			}
		}
		elseif ($vName == 'default')
		{
			$cachable = true;
		}

		$safeurlparams = array(
			'id' => 'INT',
			'limit' => 'UINT',
			'limitstart' => 'UINT',
			'showall' => 'INT',
			'return' => 'BASE64',
			'filter' => 'STRING',
			'filter_order' => 'CMD',
			'filter_order_Dir' => 'CMD',
			'filter_search' => 'STRING',
			'print' => 'BOOLEAN',
			'lang' => 'CMD'
		);

		parent::display($cachable, $safeurlparams);

		return $this;
	}

	/**
	 * Callback from payment gateways.
	 *
	 * @return  void
	 *
	 * @since   1.0.0
	 */
	public function callback()
	{
		$app = Factory::getApplication();
		$gatewayId = $this->input->get('gateway', '', 'word');
		$valid = false;

		PluginHelper::importPlugin('cmgiftcard');
		$gateways = $app->triggerEvent('onCMGCValidateCallback');

		foreach ($gateways as $p)
		{
			if ($p['gateway_id'] == $gatewayId && $p['valid'] === true)
			{
				$valid = true;
				$validation = $p;
			}
		}

		if ($valid)
		{
			$orderModel = BaseDatabaseModel::getInstance('Order', 'CMGiftCardModel');
			$result = $orderModel->updatePaidOrder($validation['order_id'], $validation['transaction_id']);

			if ($result)
			{
				CMGiftCardHelper::sendOrderEmail($validation['order_id']);

				// Check if order has electronic gift cards and send them if they need to be sent instantly.
				CMGiftCardHelper::sendElectronicCardEmail($validation['order_id']);

				// Check if order has physical gift cards and send notifications to admins.
				CMGiftCardHelper::sendPhysicalCardEmail($validation['order_id']);
			}
		}

		echo 'Received';
		$app->close();
	}
}
