<?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.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class CMGiftCardTableCard extends Table
{
	/**
	 * Constructor.
	 *
	 * @param   JDatabaseDriver  &$_db  Database connector object
	 *
	 * @since   1.0.0
	 */
	public function __construct(&$_db)
	{
		parent::__construct('#__cmgiftcard_cards', 'id', $_db);
	}

	/**
	 * Overloaded check method to ensure data integrity.
	 *
	 * @return  boolean   True on success.
	 *
	 * @since   1.0.0
	 */
	public function check()
	{
		$table = Table::getInstance('Card', 'CMGiftCardTable');

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

			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)
	{
		if ($this->id)
		{
			$this->modified_by	= Factory::getUser()->id;
			$this->modified		= Factory::getDate()->toSql();
		}

		if (empty($this->deliver_date))
		{
			$this->deliver_date = null;
		}

		if (empty($this->delivered))
		{
			$this->delivered = null;
		}

		if (empty($this->redeemed))
		{
			$this->redeemed = null;
		}

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