<?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\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Component\ComponentHelper;

/**
 * Controller for running cron jobs.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       2.0.0-alpha1
 */
class CMGiftCardControllerCron extends BaseController
{
	/**
	 * Send email for electronic gift card.
	 *
	 * @since   2.0.0-alpha1
	 */
	public function deliverElectronicCards()
	{
		$app = Factory::getApplication();
		$params = ComponentHelper::getParams('com_cmgiftcard');
		$key = $params->get('cron_secret_key');
		$inputKey = $app->input->get('key');

		if (empty($inputKey) || empty($key) || $inputKey != $key)
		{
			$app->redirect('index.php');
		}

		$cards = BaseDatabaseModel::getInstance('Cards', 'CMGiftCardModel')->getElectronicCards();

		if (count($cards))
		{
			foreach ($cards as $card)
			{
				CMGiftCardHelper::sendGiftCardEmail($card);

				echo '<p>Sent email for card #' . $card->id . '</p>';
			}
		}
		else
		{
			echo '<p>No electronic gift cards found.</p>';
		}

		echo '<p>Done.</p>';

		$app->close();
	}
}