<?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\HTML\HTMLHelper;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\MVC\Model\ListModel;

/**
 * Model class for gift card list.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class CMGiftCardModelCards 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',
				'card_code', 'a.card_code',
				'order_number',
				'created',
				'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.id', $direction = 'desc')
	{
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search'));
		$this->setState('filter.status', $this->getUserStateFromRequest($this->context . '.filter.status', 'filter_status', '', 'string'));
		$this->setState('filter.card_type', $this->getUserStateFromRequest($this->context . '.filter.card_type', 'filter_card_type', '', 'string'));
		$this->setState('filter.delivery', $this->getUserStateFromRequest($this->context . '.filter.delivery', 'filter_delivery', '', 'string'));

		$params = ComponentHelper::getParams('com_cmgiftcard');
		$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);
		$user = Factory::getUser();

		$query->select('a.*')
			->from($db->qn('#__cmgiftcard_cards') . ' AS a');

		$query->select($db->qn('o.created') . ' AS created')
			->select($db->qn('o.completed') . ' AS completed')
			->select($db->qn('o.order_number') . ' AS order_number')
			->select($db->qn('o.user_id') . ' AS user_id')
			->select($db->qn('o.order_status') . ' AS order_status')
			->join('LEFT', $db->qn('#__cmgiftcard_orders') . ' AS o ON '
				. $db->qn('o.id') . ' = ' . $db->qn('a.order_id')
			);

		$query->select($db->qn('d.image') . ' AS design_image')
			->select($db->qn('d.card_type') . ' AS card_type')
			->join('LEFT', $db->qn('#__cmgiftcard_designs') . ' AS d ON '
				. $db->qn('d.id') . ' = ' . $db->qn('a.design_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')
			);

		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where($db->qn('a.id') . ' = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
				$query->where('(' . $db->qn('a.card_code') . ' LIKE ' . $search . ' OR '
					. $db->qn('a.from_name') . ' LIKE ' . $search . ' OR '
					. $db->qn('a.to_name') . ' LIKE ' . $search . ' OR '
					. $db->qn('a.to_email') . ' LIKE ' . $search . ' OR '
					. $db->qn('a.to_address_1') . ' LIKE ' . $search . ' OR '
					. $db->qn('a.to_address_2') . ' LIKE ' . $search . ' OR '
					. $db->qn('a.to_address_3') . ' LIKE ' . $search . ' OR '
					. $db->qn('a.to_postal_box') . ' LIKE ' . $search . ' OR '
					. $db->qn('a.to_city') . ' LIKE ' . $search . ' OR '
					. $db->qn('a.to_state') . ' LIKE ' . $search . ' OR '
					. $db->qn('a.to_postal_code') . ' LIKE ' . $search . ' OR '
					. $db->qn('a.to_country') . ' LIKE ' . $search . ')');
			}
		}

		$status = $this->getState('filter.status');
		$validStatuses = array('unpaid', 'paid', 'refunded');

		if (in_array($status, $validStatuses))
		{
			$query->where($db->qn('o.order_status') . ' = ' . $db->q($status));
		}

		$cardType = $this->getState('filter.card_type');
		$validCardTypes = array('physical', 'electronic');

		if ($cardType != '' && !in_array($cardType, $validCardTypes))
		{
			$cardType = '';
		}

		if ($cardType != '')
		{
			$typeSubQuery = $db->getQuery(true)
				->select($db->qn('d.card_type'))
				->from($db->qn('#__cmgiftcard_designs', 'd'))
				->where($db->qn('d.id') . ' = ' . $db->qn('a.design_id'));

			$query->where('(' . $typeSubQuery . ') = ' . $db->q($cardType));
		}

		$delivery = $this->getState('filter.delivery');

		if (is_numeric($delivery) && $delivery == 0)
		{
			$query->where($db->qn('delivered') . ' IS NULL');
		}
		elseif (is_numeric($delivery) && $delivery == 1)
		{
			$query->where($db->qn('delivered') . ' IS NOT NULL');
		}

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

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

		return $query;
	}

	/**
	 * Get electronic gift cards to deliver.
	 *
	 * @return  DatabaseQuery
	 *
	 * @since   1.0.0
	 */
	public function getElectronicCards()
	{
		$today = HTMLHelper::_('date', 'now', 'Y-m-d', false);

		$db = $this->getDbo();

		$query = $db->getQuery(true)
			->select('a.*')
			->from($db->qn('#__cmgiftcard_cards') . ' AS a')
			->where($db->qn('deliver_date') . ' = ' . $db->q($today))
			->where($db->qn('delivered') . ' IS NULL')
			->where($db->qn('d.card_type') . ' = ' . $db->q('electronic'))
			->where($db->qn('o.order_status') . ' = ' . $db->q('paid'));

		$query
			->select($db->qn('o.first_name') . ' AS sender_first_name')
			->select($db->qn('o.last_name') . ' AS sender_last_name')
			->select($db->qn('o.email') . ' AS sender_email')
			->select($db->qn('o.created') . ' AS created')
			->select($db->qn('o.completed') . ' AS completed')
			->select($db->qn('o.order_number') . ' AS order_number')
			->select($db->qn('o.order_status') . ' AS order_status')
			->join('LEFT', $db->qn('#__cmgiftcard_orders') . ' AS o ON '
				. $db->qn('o.id') . ' = ' . $db->qn('a.order_id')
			);

		$query->select($db->qn('d.image') . ' AS design_image')
			->select($db->qn('d.card_type') . ' AS card_type')
			->join('LEFT', $db->qn('#__cmgiftcard_designs') . ' AS d ON '
				. $db->qn('d.id') . ' = ' . $db->qn('a.design_id')
			);

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

		$query->select('(' . $amountSubQuery . ') AS order_amount');

		return $db->setQuery($query)->loadObjectList();
	}
}
