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

/**
 * 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',
				'amount',
				'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'));

		$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);
		$jinput = Factory::getApplication()->input;
		$keyword = $jinput->get('keyword', '', 'html');
		$cardType = $jinput->get('card_type', '');
		$orderStatus = $jinput->get('order_status', '');
		$cardDelivered = $jinput->get('card_delivered', '');

		$validCardTypes = array('physical', 'electronic');
		$validORderStatus = array('paid', 'unpaid', 'refunded');

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

		if ($orderStatus != '' && !in_array($orderStatus, $validORderStatus))
		{
			$orderStatus = '';
		}

		if ($cardDelivered != '' && $cardDelivered != '1' && $cardDelivered != '0')
		{
			$cardDelivered = '';
		}

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

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

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

		if (trim($keyword) != '')
		{
			$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($keyword), true) . '%'));

			$orderSubQuery = $db->getQuery(true)
				->select($db->qn('b.id'))
				->from($db->qn('#__cmgiftcard_orders', 'b'))
				->where('(' . $db->qn('b.first_name') . ' LIKE ' . $search . ' OR '
				. $db->qn('b.last_name') . ' LIKE ' . $search . ' OR '
				. $db->qn('b.email') . ' LIKE ' . $search . ' OR '
				. $db->qn('b.address_1') . ' LIKE ' . $search . ' OR '
				. $db->qn('b.address_2') . ' LIKE ' . $search . ' OR '
				. $db->qn('b.address_3') . ' LIKE ' . $search . ' OR '
				. $db->qn('b.postal_box') . ' LIKE ' . $search . ' OR '
				. $db->qn('b.city') . ' LIKE ' . $search . ' OR '
				. $db->qn('b.state') . ' LIKE ' . $search . ' OR '
				. $db->qn('b.postal_code') . ' LIKE ' . $search . ' OR '
				. $db->qn('b.country') . ' LIKE ' . $search . ')');

			$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 . ' OR '
				. $db->qn('a.order_id') . ' IN (' . $orderSubQuery->__toString() . ')' . ')');
		}

		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));
		}

		if ($orderStatus != '')
		{
			$statusSubQuery = $db->getQuery(true)
				->select($db->qn('o.order_status'))
				->from($db->qn('#__cmgiftcard_orders', 'o'))
				->where($db->qn('o.id') . ' = ' . $db->qn('a.order_id'));

			$query->where('(' . $statusSubQuery . ') = ' . $db->q($orderStatus));
		}

		if ($cardDelivered == '1')
		{
			$query->where($db->qn('a.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()
	{
		$params = ComponentHelper::getParams('com_cmgiftcard');
		$limit = (int) $params->get('cron_max_delivery', 5);
		$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, 0, $limit)->loadObjectList();
	}

	/**
	 * Get filter form.
	 *
	 * @param   array    $data      data
	 * @param   boolean  $loadData  load current data
	 *
	 * @return  Form/false  the Form object or false
	 *
	 * @since   1.0.0
	 */
	public function getFilterForm($data = array(), $loadData = true)
	{
		Form::addFormPath(JPATH_COMPONENT . '/models/forms');
		$form = Form::getInstance('com_cmgiftcard.cards.filer', 'filter_cards');
		$jinput = Factory::getApplication()->input;

		$keyword = trim($jinput->get('keyword', '', 'html'));
		$cardType = $jinput->get('card_type', '');
		$orderStatus = $jinput->get('order_status', '');
		$cardDelivered = $jinput->get('card_delivered', '');

		$validCardTypes = array('physical', 'electronic');
		$validORderStatus = array('paid', 'unpaid', 'refunded');

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

		if ($orderStatus != '' && !in_array($orderStatus, $validORderStatus))
		{
			$orderStatus = '';
		}

		if ($cardDelivered != '' && $cardDelivered != '1' && $cardDelivered != '0')
		{
			$cardDelivered = '';
		}

		$filterData = array(
			'keyword'			=> $keyword,
			'card_type'			=> $cardType,
			'order_status'		=> $orderStatus,
			'card_delivered'	=> $cardDelivered,
		);

		$form->bind($filterData);

		return $form;
	}
}
