<?php
/**
 * @package     Reporter for VirtueMart
 * 
 * @copyright   Copyright (C) 2012-2019 VirtuePlanet Services LLP. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @author      Abhishek Das <info@virtueplanet.com> - https://www.virtueplanet.com
 */

defined('_JEXEC') or die;

class VpemControllerEvent extends \Joomla\CMS\MVC\Controller\FormController
{
	/**
	 * Constructor
	 *
	 * @throws Exception
	 */
	public function __construct()
	{
		$this->view_list = 'events';
		parent::__construct();
	}
	
	public function getProducts()
	{
		JLoader::register('VmConfig', JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/config.php');
		
		VmConfig::loadConfig();
		
		$app   = JFactory::getApplication();
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true);
		
		$like = trim($app->input->getString('like', null));
		
		if (empty($like))
		{
			return [];
		}
		
		$langFback = (!VmConfig::get('prodOnlyWLang', false) && VmConfig::$defaultLang != VmConfig::$vmlang && VmConfig::$langCount > 1);
		$whereOR   = [];
		
		$query->select($db->quoteName('p.virtuemart_product_id') . ' AS value')
			->select($db->quoteName('p.product_sku') . ' AS sku')
			->from($db->quoteName('#__virtuemart_products') . ' AS p')
			->where($db->quoteName('p.published') . ' = 1');
		
		if ($langFback)
		{
			if (VmConfig::$defaultLang != VmConfig::$jDefLang)
			{
				$query->select('IFNULL(l.product_name, IFNULL(ld.product_name, ljd.product_name)) AS text');
					
				$query->join('LEFT', $db->quoteName('#__virtuemart_products_' . VmConfig::$jDefLang) . ' AS ljd ON ljd.virtuemart_product_id = p.virtuemart_product_id');
				
				$whereOR[] = '(' . $db->quoteName('ljd.product_name') . ' IS NOT NULL AND ' . $db->quoteName('ljd.product_name') . ' LIKE ' . $db->quote('%' . $like . '%') . ')';
			}
			else
			{
				$query->select('IFNULL(l.product_name, ld.product_name) AS text');
			}
			
			$query->join('LEFT', $db->quoteName('#__virtuemart_products_' . VmConfig::$defaultLang) . ' AS ld ON ld.virtuemart_product_id = p.virtuemart_product_id');
			$query->join('LEFT', $db->quoteName('#__virtuemart_products_' . VmConfig::$vmlang) . ' AS l ON l.virtuemart_product_id = p.virtuemart_product_id');
			
			$whereOR[] = '(' . $db->quoteName('ld.product_name') . ' IS NOT NULL AND ' . $db->quoteName('ld.product_name') . ' LIKE ' . $db->quote('%' . $like . '%') . ')';
			$whereOR[] = '(' . $db->quoteName('l.product_name') . ' IS NOT NULL AND ' . $db->quoteName('l.product_name') . ' LIKE ' . $db->quote('%' . $like . '%') . ')';
		}
		else
		{
			$query->select($db->quoteName('l.product_name') . ' AS text');
			
			$query->join('INNER', $db->quoteName('#__virtuemart_products_' . VmConfig::$vmlang) . ' AS l ON l.virtuemart_product_id = p.virtuemart_product_id');
			
			$whereOR[] = $db->quoteName('l.product_name') . ' LIKE ' . $db->quote('%' . $like . '%');
		}
		
		$whereOR[] = $db->quoteName('p.product_sku') . ' LIKE ' . $db->quote('%' . $like . '%');
		$whereOR[] = $db->quoteName('p.virtuemart_product_id') . ' = ' . $db->quote($like);
		
		$query->where(implode(' OR ', $whereOR));
		$query->group($db->quoteName('p.virtuemart_product_id'));

		$db->setQuery($query);
		$products = $db->loadObjectList();
		
		foreach ($products as &$product)
		{
			if (!empty($product->sku))
			{
				$product->text .= ' [' . $product->sku . ']';
			}
		}
		
		$this->jsonReturn($products);
	}
	
	public function getUsers()
	{
		$app   = JFactory::getApplication();
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true);
		
		$like = trim($app->input->get('like', null));
		
		if (empty($like))
		{
			return [];
		}
		
		$query->select($db->quoteName(array('id', 'name', 'username')))
			->from($db->quoteName('#__users'))
			->order($db->quoteName('name') . ' ASC')
			->group($db->quoteName(array('id', 'name', 'username')));
		
		$whereOR = [];
		
		if (is_numeric($like))
		{
			$whereOR[] = '(' . $db->quoteName('id') . ' LIKE ' . $db->quote('%' . $like . '%') . ')';
		}
		
		$whereOR[] = '(' . $db->quoteName('name') . ' LIKE ' . $db->quote('%' . $like . '%') . ')';
		$whereOR[] = '(' . $db->quoteName('username') . ' LIKE ' . $db->quote('%' . $like . '%') . ')';
		
		$query->where(implode(' OR ', $whereOR));
		
		try
		{
			$db->setQuery($query);
			$users = $db->loadObjectList();
		}
		catch (Exception $e)
		{
			JError::raiseWarning(500, $e->getMessage());
			return false;
		}
			
		$options = [];
		
		foreach ($users as $user)
		{
			$text = $user->name . ' (' . $user->username . ')';
			
			$options[] = JHtml::_('select.option', (int) $user->id, $text);
		}
		
		$this->jsonReturn($options);
	}
	
	public function getModel($name = 'Event', $prefix = 'VpemModel', $config = ['ignore_request' => true])
	{
		return parent::getModel($name, $prefix, $config);
	}
	
	protected function jsonReturn($output = [])
	{
		$app = JFactory::getApplication();
		$obLevel = ob_get_level();
		
		if ($obLevel)
		{
			while($obLevel > 0)
			{
				ob_end_clean();
				$obLevel --;
			}
		}
		elseif (ob_get_contents())
		{
			ob_clean();
		}
		
		header('Content-type: application/json');
		header('Cache-Control: public,max-age=1,must-revalidate');
		header('Expires: ' . gmdate('D, d M Y H:i:s', ($_SERVER['REQUEST_TIME'] + 1)) . ' GMT');
		header('Last-modified: ' . gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME']) . ' GMT');
			
		if (function_exists('header_remove')) 
		{
			header_remove('Pragma');
		}
						
		echo json_encode($output);
		
		flush();
		$app->close();
	}
}