<?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\Response\JsonResponse;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Session\Session;

/**
 * Controller class for gift card's AJAX tasks.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class CMGiftCardControllerCard extends BaseController
{
	/**
	 * Send email for electronic gift card to recipient.
	 *
	 * @return  boolean
	 *
	 * @since   1.0.0
	 */
	public function sendEmail()
	{
		Session::checkToken('get') or jexit(Text::_('JINVALID_TOKEN'));

		$app = Factory::getApplication();
		$cardId = $this->input->getInt('id');
		$card = BaseDatabaseModel::getInstance('Card', 'CMGiftCardModel')->getItem($cardId);

		if (empty($card->id))
		{
			echo new JsonResponse(null, Text::_('COM_CMGIFTCARD_ERROR_CARD_NOT_EXIST'), true);

			return true;
		}

		if ($card->card_type != 'electronic')
		{
			echo new JsonResponse(null, Text::_('COM_CMGIFTCARD_ERROR_CARD_NOT_ELECTRONIC'), true);

			return true;
		}

		$sent = CMGiftCardHelper::sendGiftCardEmail($card);

		if ($sent)
		{
			echo new JsonResponse(null, Text::_('COM_CMGIFTCARD_EGIFT_CARD_SENT'));
		}
		else
		{
			echo new JsonResponse(null, Text::_('COM_CMGIFTCARD_ERROR_EGIFT_CARD_NOT_SENT'), true);
		}

		return true;
	}
}