<?php
/**
 * --------------------------------------------------------------------------------------------
 * VP Product Carousel - Joomla! 3 Module for VirtueMart 3.0
 * --------------------------------------------------------------------------------------------
 * @package    VP Product Carousel
 * @author     Abhishek Das
 * @copyright  Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2. http://www.gnu.org/licenses/gpl-2.0.html
 * @link       https://www.virtueplanet.com
 * --------------------------------------------------------------------------------------------
*/
defined('_JEXEC') or die();

use Joomla\Registry\Registry;

JFormHelper::loadFieldClass('list');

JLoader::register('VmConfig',        JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/config.php');
JLoader::register('ShopFunctions',   JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/shopfunctions.php');
JLoader::register('TableCategories', JPATH_ADMINISTRATOR . '/components/com_virtuemart/tables/categories.php');
JLoader::register('VmModel',         JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/vmmodel.php');

VmConfig::loadConfig();

class JFormFieldVMProducts extends JFormFieldList
{
	public $type = 'VMProducts';
	
	protected static $products = null;
	
	protected function getInput()
	{
		$id    = isset($this->element['id']) ? $this->element['id'] : null;
		$cssId = '#' . $this->getId($id, $this->element['name']);
		
		$chosenAjaxSettings = new Registry(
			array(
				'selector'      => $cssId,
				'type'          => 'GET',
				'url'           => JUri::root() . 'index.php?option=com_ajax&plugin=vpframework&format=json&vpfmethod=getProducts',
				'dataType'      => 'json',
				'jsonTermKey'   => 'like',
				'minTermLength' => 3
			)
		);

		JHtml::_('formbehavior.ajaxchosen', $chosenAjaxSettings);
		
		if (is_string($this->value))
		{
			$this->value = explode(',', $this->value);
		}
		
		return parent::getInput();
	}
	
	protected function getOptions()
	{
		$options = array();
		
		if(!empty($this->value))
		{
			VmConfig::loadJLang('com_virtuemart', true);
			
			$model = VmModel::getModel('Product');
			$product_ids = array_map('intval', $this->value);
			$products = $model->getProducts($product_ids);
			
			if(!empty($products))
			{
				foreach ($products as $product)
				{
					$value = (int) $product->virtuemart_product_id;
					$text = htmlspecialchars($product->product_name, ENT_COMPAT, 'UTF-8', false);
					$options[] = JHTML::_('select.option', $value, $text);
				}
			}
		}
		
		return array_merge(parent::getOptions(), $options);
	}
}