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

/**
 * Model class for order list.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class CMGiftCardModelOrders extends ListModel
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @since   1.0.0
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'order_number', 'a.order_number',
				'created', 'a.created',
				'commpleted', 'a.completed',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.0.0
	 */
	protected function populateState($ordering = 'a.created', $direction = 'desc')
	{
		$params = Factory::getApplication()->getParams();
		$this->setState('params', $params);

		parent::populateState($ordering, $direction);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  DatabaseQuery
	 *
	 * @since   1.0.0
	 */
	protected function getListQuery()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$amountSubQuery = $db->getQuery(true);
		$cardSubQuery = $db->getQuery(true);
		$user = Factory::getUser();

		$amountSubQuery->select('SUM(' . $db->qn('c.amount') . ')')
			->from($db->qn('#__cmgiftcard_cards') . ' AS c')
			->where($db->qn('c.order_id') . ' = ' . $db->qn('a.id'));

		$cardSubQuery->select('COUNT(' . $db->qn('gc.id') . ')')
			->from($db->qn('#__cmgiftcard_cards') . ' AS gc')
			->where($db->qn('gc.order_id') . ' = ' . $db->qn('a.id'));

		$query->select('a.*')
			->select('(' . $amountSubQuery->__toString() . ') as amount')
			->select('(' . $cardSubQuery->__toString() . ') as card_quantity')
			->from($db->qn('#__cmgiftcard_orders') . ' AS a')
			->where($db->qn('user_id') . ' = ' . $db->q(Factory::getUser()->id));

		$query->select($db->qn('uc.name') . ' AS editor')
			->join('LEFT', $db->qn('#__users') . ' AS uc ON '
				. $db->qn('uc.id') . ' = ' . $db->qn('a.checked_out')
			);

		$orderCol = $this->state->get('list.ordering', 'a.created');
		$orderDirn = $this->state->get('list.direction', 'desc');

		$query->order($db->escape($orderCol . ' ' . $orderDirn));

		return $query;
	}

	/**
	 * Method to get an array of data items.
	 *
	 * @return  mixed  An array of data items on success, false on failure.
	 *
	 * @since   1.0.0
	 */
	public function getItems()
	{
		$items = parent::getItems();

		if (count($items))
		{
			$db = $this->getDbo();
			$query = $db->getQuery(true);

			foreach ($items as &$item)
			{
				$query->clear()
					->select($db->qn('card_code'))
					->select($db->qn('id'))
					->from($db->qn('#__cmgiftcard_cards'))
					->where($db->qn('order_id') . ' = ' . $db->q($item->id));

				$item->cards = $db->setQuery($query)->loadObjectList();
			}
		}

		return $items;
	}
}
