<?php
/**
 *---------------------------------------------------------------------------------------
 * @package       VP Ajax Search Module
 *---------------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2012-2020 VirtuePlanet Services LLP. All rights reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       Abhishek Das
 * @email         info@virtueplanet.com
 * @link          https://www.virtueplanet.com
 *---------------------------------------------------------------------------------------
 */

defined('_JEXEC') or die;

JLoader::register('VmConfig', JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/config.php');

VmConfig::loadConfig();

JLoader::register('CurrencyDisplay',        JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/currencydisplay.php');
JLoader::register('VirtueMartModelProduct', JPATH_ADMINISTRATOR . '/components/com_virtuemart/models/product.php');
JLoader::register('shopFunctionsF',         JPATH_SITE . '/components/com_virtuemart/helpers/shopfunctionsf.php');

class ModVPAjaxSearchHelper
{
	/**
	 * Display the search button as an image.
	 *
	 * @param   string  $button_text  The alt text for the button.
	 *
	 * @return  string  The HTML for the image.
	 *
	 * @since   1.5
	 */
	public static function getValidNumber($params, $param, $default = 0)
	{
		$postiveInteger = (int) $params->get($param, 0);
		
		if($postiveInteger <= 0)
		{
			return $default;
		}
		
		return $postiveInteger;
	}
	
	public static function getWidthPerRow($params, $param, $default = 0)
	{
		$per_row = self::getValidNumber($params, $param, $default);
		$width   = 100;
		
		if($per_row > 0)
		{
			$width = (100 / $per_row);
			
			if($width != round($width))
			{
				$width = number_format($width, 8, '.', '');
			}
		}
		
		return (string) $width;
	}
	
	public static function getCategoryId($params)
	{
		$category_id = 0;
		
		if($params->get('by_category', 0))
		{
			$input  = JFactory::getApplication()->input;
			$option = strtolower($input->getCmd('option', ''));
			$view   = strtolower($input->getCmd('view', ''));
			$cat_id = $input->getInt('virtuemart_category_id', 0);
			
			if($option == 'com_virtuemart' && ($view == 'category' || $view == 'productdetails') && $cat_id > 0)
			{
				$category_id = $cat_id;
			}
		}
		
		return $category_id;
	}
	
	public static function getHiddenFields($params, $action_url)
	{
		$app    = JFactory::getApplication();
		$router = $app->getRouter();
		$cat_id = self::getCategoryId($params);
		$uri    = clone JUri::getInstance($action_url);
		// $vars   = $router->parse($uri); 
		// VirtueMart router redirecting page while parsing url. So we are not using this.
		$vars   = array();
		$fields = array();
		
		if(!isset($vars['option']) || $vars['option'] != 'com_virtuemart')
		{
			$fields['option'] = 'com_virtuemart';
		}
		
		if(!isset($vars['view']) || $vars['view'] != 'category')
		{
			$fields['view'] = 'category';
		}

		if(!isset($vars['limitstart']) || $vars['limitstart'] != 0)
		{
			$fields['limitstart'] = 0;
		}
		
		if(!isset($vars['virtuemart_category_id']) || $vars['virtuemart_category_id'] != $cat_id)
		{
			$fields['virtuemart_category_id'] = (int) $cat_id;
		}
		
		$Itemid = (int) $params->get('set_itemid', 0);
		
		if($Itemid > 0 && (!isset($vars['Itemid']) || $vars['Itemid'] != $Itemid))
		{
			$fields['Itemid'] = (int) $Itemid;
		}
		
		return $fields;
	}
	
	public static function getAjax()
	{
		if(!JModuleHelper::isEnabled('mod_vp_ajax_search'))
		{
			return;
		}
		
		if(!$module = JModuleHelper::getModule('mod_vp_ajax_search'))
		{
			return;
		}
		
		VmConfig::loadConfig();
		VmConfig::loadJLang('com_virtuemart', true);
		
		$app          = JFactory::getApplication();
		$input        = $app->input;
		$limit        = $input->getInt('limit', 6);
		$limitstart   = $input->getInt('limitstart', 0);
		$keyword      = $input->getString('keyword', false);
		$params       = new JRegistry($module->params);
		$products     = self::getSearchResults($keyword, $params);
		$currency     = CurrencyDisplay::getInstance();
		$showCategory = $params->get('show_category', 1);
		$showPrice    = $params->get('show_price', 1);
		$priceType    = $params->get('displayed_price_type', 'salesPrice');
		$results      = array();
		$count        = 0;
		$end          = true;

		if(!empty($products))
		{
			$count = count($products);
			
			if($count >= $limit)
			{
				$end = false;
			}
			
			foreach($products as $product)
			{
				ob_start();
				require JModuleHelper::getLayoutPath('mod_vp_ajax_search', 'result');
				$results[] = ob_get_clean();
			}
		}
		
		$data = array(
			'query' => $keyword,
			'suggestions' => $results,
			'limitstart' => $limitstart,
			'limit' => $limit,
			'count' => $count,
			'end' => $end
		);
		
		return self::outputAjax($data);
	}
	
	private static function getSearchResults($keyword, $params)
	{
		$app         = JFactory::getApplication();
		$input       = $app->input;
		$category_id = $input->getInt('virtuemart_category_id', 0);
		//$limit       = $input->getInt('limit', 6);
		//$limitStart  = $input->getInt('limitstart', 0);
		$products    = array();

		if(!$keyword) 
		{
			return $products;
		}
		
		$input->set('virtuemart_category_id', -1);
		$input->set('view', 'ajaxsearch');
		//$input->set('limit', $limit);
		//$input->set('limitstart', $limitstart);
		
		$model = VmModel::getModel('product');
	
		$product_ids = $model->sortSearchListQuery(true, $category_id);
		
		if(!empty($product_ids))
		{
			$products = $model->getProducts($product_ids);
			
			if($params->get('show_images', 1))
			{
				$model->addImages($products, 1);
			}
		}
		
		return $products;
	}
	
	private static function outputAjax($data)
	{
		$obLevel = ob_get_level();
		
		if($obLevel)
		{
			while ($obLevel > 0) 
			{
				ob_end_clean();
				$obLevel --;
			}
		}
		else
		{
			ob_clean();
		}
		
		if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) 
		{
			header('Content-type: application/text');
		} 
		else 
		{
			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($data);
		
		JFactory::getApplication()->close();
	}
}
