<?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\Language\Text;
use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Response\JsonResponse;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Layout\FileLayout;

/**
 * Controller for scanning gift card's QR code.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       2.2.0
 */
class CMGiftCardControllerScanner extends BaseController
{
	/**
	 * Proxy for getModel.
	 *
	 * @param   string  $name    The model name. Optional.
	 * @param   string  $prefix  The class prefix. Optional.
	 * @param   array   $config  The array of possible config values. Optional.
	 *
	 * @return  object  The model.
	 *
	 * @since   2.2.0
	 */
	public function getModel($name = 'Card', $prefix = 'CMGiftCardModel', $config = ['ignore_request' => true])
	{
		$model = parent::getModel($name, $prefix, $config);

		return $model;
	}

	/**
	 * Check permission and get gift card.
	 *
	 * @return  mixed
	 *
	 * @since   2.2.0
	 */
	private function getGiftCard()
	{
		$app = Factory::getApplication();
		$jinput = $this->input;

		if (!Session::checkToken('get'))
		{
			echo new JResponseJson(null, Text::_('JINVALID_TOKEN'), true);

			$app->close();
		}

		$code = $jinput->get('code');

		if (!$code)
		{
			echo new JsonResponse(null, Text::_('COM_CMGIFTCARD_ERROR_CARD_NOT_FOUND'), true);

			$app->close();
		}

		$card = $this->getModel()->getCardByCode($code);

		if (!$card)
		{
			echo new JsonResponse(null, Text::_('COM_CMGIFTCARD_ERROR_CARD_NOT_FOUND'), true);

			$app->close();
		}

		return $card;
	}

	/**
	 * Find gift card by gift card's code.
	 *
	 * @return  boolean
	 *
	 * @since   2.2.0
	 */
	public function find()
	{
		$card = $this->getGiftCard();

		$jinput = $this->input;
		$getRecent = $jinput->get('recent', 0);
		$code = $jinput->get('code');
		$data = [];
		$params = ComponentHelper::getParams('com_cmgiftcard');

		if ($getRecent)
		{
			$session = Factory::getSession();
			$scannedCards = $session->get('scanned_cards', [], 'com_cmgiftcard');

			if (!isset($scannedCards[$code]))
			{
				$scannedCards = array_merge([$code => [
					'id'	=> $card->id,
					'date'	=> Factory::getDate()->toSql()
				]], $scannedCards);

				$max = $params->get('recent_scanned_card_quantity', 15);

				if (count($scannedCards) > $max)
				{
					array_pop($scannedCards);
				}

				$session->set('scanned_cards', $scannedCards, 'com_cmgiftcard');
			}

			$recentLayout = new FileLayout('scanned_cards', JPATH_ROOT . '/administrator/components/com_cmgiftcard/layouts');
			$recentHtml = $recentLayout->render([
				'cards'		=> $scannedCards,
				'params'	=> $params,
			]);

			$data['recent'] = $recentHtml;
		}

		$cardLayout = new FileLayout('scanned_card', JPATH_ROOT . '/administrator/components/com_cmgiftcard/layouts');
		$cardHtml = $cardLayout->render([
			'card' 		=> $card,
			'params'	=> $params,
		]);

		$data['card'] = [
			'html'		=> $cardHtml,
			'redeemed'	=> $card->redeemed,
		];

		echo new JsonResponse($data);

		return true;
	}

	/**
	 * Staff makes or cancels a redemptation.
	 *
	 * @return  boolean
	 *
	 * @since   2.2.0
	 */
	public function setRedemption()
	{
		$card = $this->getGiftCard();

		$jinput = $this->input;
		$redeemed = $jinput->getInt('redeemed', -1);

		if ($redeemed != 1 && $redeemed != 0)
		{
			echo new JsonResponse(null, Text::_('COM_CMGIFTCARD_STAFF_REDEMPTION_FAILURE'), true);

			return true;
		}

		$result = $this->getModel()->setRedemptionStatus($card->id, $redeemed);

		if (!$result)
		{
			echo new JsonResponse(null, Text::_('COM_CMGIFTCARD_STAFF_REDEMPTION_FAILURE'), true);

			return true;
		}

		$card->redeemed = $redeemed ? Factory::getDate()->toSql() : null;

		$params = ComponentHelper::getParams('com_cmgiftcard');
		$cardLayout = new FileLayout('scanned_card', JPATH_ROOT . '/administrator/components/com_cmgiftcard/layouts');
		$cardHtml = $cardLayout->render([
			'card'		=> $card,
			'params'	=> $params,
		]);

		$data['card'] = [
			'html'		=> $cardHtml,
			'redeemed'	=> $card->redeemed,
		];

		echo new JsonResponse($data);

		return true;
	}
}