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

/**
 * Table class for gift card code.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class CMGiftCardTableCode extends Table
{
	/**
	 * Constructor.
	 *
	 * @param   JDatabaseDriver  &$_db  Database connector object
	 *
	 * @since   1.0.0
	 */
	public function __construct(&$_db)
	{
		parent::__construct('#__cmgiftcard_codes', 'id', $_db);
	}

	/**
	 * Overloaded check method to ensure data integrity.
	 *
	 * @return  boolean   True on success.
	 *
	 * @since   1.0.0
	 */
	public function check()
	{
		if (empty($this->code))
		{
			$this->setError(Text::_('COM_CMGIFTCARD_ERROR_CODE_EMPTY_CODE'));

			return false;
		}

		$table = Table::getInstance('Code', 'CMGiftCardTable');

		if ($table->load(array('code' => $this->code)) && ($table->id != $this->id || $this->id == 0))
		{
			$this->setError(Text::_('COM_CMGIFTCARD_ERROR_CODE_UNIQUE_CODE'));

			return false;
		}

		$table = Table::getInstance('Card', 'CMGiftCardTable');

		if ($table->load(array('card_code' => $this->code)))
		{
			$this->setError(Text::sprintf('COM_CMGIFTCARD_ERROR_CODE_DUPLICATED_CARD_CODE', $table->id));

			return false;
		}

		return true;
	}

	/**
	 * Store.
	 *
	 * @param   boolean  $updateNulls  True to update fields even if they are null.
	 *
	 * @return  boolean  True on success, false on failure.
	 *
	 * @since   2.0.0-alpha1
	 */
	public function store($updateNulls = true)
	{
		$userId = Factory::getUser()->id;
		$date = Factory::getDate()->toSql();

		if ($this->id)
		{
			$this->modified_by	= $userId;
			$this->modified		= $date;
		}
		else
		{
			$this->created_by	= $userId;
			$this->created		= $date;
		}

		return parent::store($updateNulls);
	}
}
