<?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 order's AJAX tasks.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       2.0.2
 */
class CMGiftCardControllerOrder extends BaseController
{
	/**
	 * Send order confirmation email.
	 *
	 * @return  boolean
	 *
	 * @since   2.0.2
	 */
	public function sendEmail()
	{
		Session::checkToken('get') or jexit(Text::_('JINVALID_TOKEN'));

		$app = Factory::getApplication();
		$orderId = $this->input->getInt('id');
		$order = BaseDatabaseModel::getInstance('Order', 'CMGiftCardModel')->getItem($orderId);

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

			return true;
		}

		if ($order->order_status != 'paid')
		{
			echo new JsonResponse(null, Text::_('COM_CMGIFTCARD_ERROR_ORDER_NOT_PAID'), true);

			return true;
		}

		$sent = CMGiftCardHelper::sendOrderEmail($order->id);

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

		return true;
	}
}