<?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\Form\Form;

/**
 * Model class for tool form.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class CMGiftCardModelTools extends BaseDatabaseModel
{
	/**
	 * Get form for uploading new gift card code.
	 *
	 * @return  mixed  A Form object on success, false on failure
	 *
	 * @since   1.0.0
	 */
	public function getCodeForm()
	{
		Form::addFormPath(JPATH_COMPONENT . '/models/forms');

		try
		{
			$form = Form::getInstance('com_cmgiftcard.cards.code_upload', 'codeupload');
		}
		catch (Exception $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		return $form;
	}

	/**
	 * Import code.
	 *
	 * @param   string   $code     Code.
	 * @param   string   $created  Created date.
	 * @param   integer  $userId   Current admin's user ID.
	 *
	 * @return  mixed  A Form object on success, false on failure
	 *
	 * @since   1.0.0
	 */
	public function importCode($code, $created = null, $userId = null)
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select('COUNT(' . $db->qn('id') . ')')
			->from($db->qn('#__cmgiftcard_codes'))
			->where($db->qn('code') . ' = ' . $db->q($code));
		$count = $db->setQuery($query)->loadResult();

		if ($count > 0)
		{
			return false;
		}

		$query->clear()
			->select('COUNT(' . $db->qn('id') . ')')
			->from($db->qn('#__cmgiftcard_cards'))
			->where($db->qn('card_code') . ' = ' . $db->q($code));
		$count = $db->setQuery($query)->loadResult();

		if ($count > 0)
		{
			return false;
		}

		$query->clear()
			->select('MAX(' . $db->qn('ordering') . ')')
			->from($db->qn('#__cmgiftcard_codes'));
		$ordering = (int) $db->setQuery($query)->loadResult();

		$ordering++;

		$columns = array(
			$db->qn('code'),
			$db->qn('gift_card_id'),
			$db->qn('published'),
			$db->qn('ordering'),
			$db->qn('created'),
			$db->qn('created_by'),
		);

		if ($created == null)
		{
			$created = Factory::getDate()->toSql();
		}

		if ($userId == null)
		{
			$userId = Factory::getUser()->id;
		}

		$values = array(
			$db->q($code),
			$db->q(0),
			$db->q(1),
			$db->q($ordering),
			$db->q($created),
			$db->q($userId),
		);

		$query->clear()
			->insert($db->qn('#__cmgiftcard_codes'))
			->columns(implode(', ', $columns))
			->values(implode(', ', $values));

		return $db->setquery($query)->execute();
	}
}
