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

	/**
	 * Overloaded check method to ensure data integrity.
	 *
	 * @return  boolean   True on success.
	 *
	 * @since   1.0.0
	 */
	public function check()
	{
		$this->order_number = (int) $this->order_number;

		if ($this->order_number <= 0 )
		{
			$this->setError(Text::_('COM_CMGIFTCARD_ERROR_ORDER_INVALID_ORDER_NUMBER'));

			return false;
		}

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

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

			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->completed))
		{
			$this->completed = null;
		}

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