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

defined('_JEXEC') or die;

jimport('joomla.application.component.view');

JLoader::register('shopFunctionsF', JPATH_SITE . '/components/com_virtuemart/helpers/shopfunctionsf.php');
JLoader::register('VMEssentialsImage', JPATH_SITE . '/components/com_vmessentials/helpers/image.php');

/**
 * View class for a list of Vmessentials.
 *
 * @since  1.6
 */
class VMEssentialsViewQuickview extends JViewLegacy
{
	/**
	 * Display the view
	 *
	 * @param   string  $tpl  Template name
	 *
	 * @return void
	 *
	 * @throws Exception
	 */
	public function display($tpl = null)
	{
		$document = JFactory::getDocument();
		$app      = JFactory::getApplication();
		$input    = $app->input;
		$menus    = $app->getMenu();
		$menu     = $menus->getActive();

		$this->params = $app->getParams('com_vmessentials');
		
		if (!$this->params->get('enable_quickview', 1))
		{
			throw new Exception(JText::_('COM_VMESSENTIALS_MSG_QUICKVIEW_DISABLED'), 403);
		}
		
		$this->show_prices = (int) VmConfig::get('show_prices', 1);
		
		$pathway = $app->getPathway();
		$task    = $input->getCmd('task', '');

		$product_model       = VmModel::getModel('product');
		$this->product_model = $product_model;
		
		$virtuemart_product_id = $input->getInt('virtuemart_product_id', 0);
		$quantity              = $input->getInt('quantity', 1);

		$ratingModel = VmModel::getModel('ratings');
		
		$product_model->withRating = $this->showRating = $ratingModel->showRating($virtuemart_product_id);
		
		$product       = $product_model->getProduct($virtuemart_product_id, true, true, true, $quantity);
		$this->product = $product;

		$last_category_id = shopFunctionsF::getLastVisitedCategoryId();

		$customfieldsModel = VmModel::getModel ('Customfields');

		if ($product->customfields)
		{
			$customfieldsModel->displayProductCustomfieldFE($product, $product->customfields);
		}

		if (empty($product->slug))
		{
			//Todo this should be redesigned to fit better for SEO
			$app->enqueueMessage(vmText::_('COM_VIRTUEMART_PRODUCT_NOT_FOUND'));

			$categoryLink = '';
			
			if (!$last_category_id)
			{
				$last_category_id = $input->getInt('virtuemart_category_id', 0);
			}
			
			if ($last_category_id)
			{
				$categoryLink = '&virtuemart_category_id=' . $last_category_id;
			}

			if (VmConfig::get('handle_404',1))
			{
				$app->redirect(JRoute::_('index.php?option=com_virtuemart&view=category' . $categoryLink . '&error=404', FALSE));
			}
			else
			{
				throw new Exception('Not found', 404);
			}

			return;
		}

		$isCustomVariant = false;
		
		if (!empty($product->customfields))
		{
			foreach ($product->customfields as $k => $custom)
			{
				if ($custom->field_type == 'C' and $custom->virtuemart_product_id != $virtuemart_product_id)
				{
					$isCustomVariant = $custom;
				}
				
				if (!empty($custom->layout_pos))
				{
					$product->customfieldsSorted[$custom->layout_pos][] = $custom;
				}
				else
				{
					$product->customfieldsSorted['normal'][] = $custom;
				}
				
				unset($product->customfields);
			}
		}

		$product_model->addImages($product);

		if (isset($product->min_order_level) && (int) $product->min_order_level > 0)
		{
			$this->min_order_level = $product->min_order_level;
		}
		else
		{
			$this->min_order_level = 1;
		}

		if (isset($product->step_order_level) && (int) $product->step_order_level > 0)
		{
			$this->step_order_level = $product->step_order_level;
		}
		else
		{
			$this->step_order_level = 1;
		}

		$currency = CurrencyDisplay::getInstance();
		$this->currency = $currency;

		// Load the neighbours
		if (VmConfig::get('product_navigation', 1))
		{
			$product->neighbours = $product_model->getNeighborProducts($product);
		}


		if (VmConfig::get('show_manufacturers', 1) && !empty($this->product->virtuemart_manufacturer_id))
		{
			$manModel = VmModel::getModel('manufacturer');
			$mans = array();
			
			// Gebe die Hersteller aus
			foreach ($this->product->virtuemart_manufacturer_id as $manufacturer_id)
			{
				$manufacturer = $manModel->getManufacturer($manufacturer_id);
				$manModel->addImages($manufacturer, 1);
				$mans[]=$manufacturer;
			}
			
			$this->product->manufacturers = $mans;
		}
		
		// Load the category
		$category_model = VmModel::getModel('category');
		$seo_full = VmConfig::get('seo_full',true);
		
		if (in_array($last_category_id,$product->categories) && !$seo_full)
		{
			$product->virtuemart_category_id = $last_category_id;
		}

		if ($category_model)
		{
			$category = $category_model->getCategory($product->virtuemart_category_id);
			
			if (in_array($last_category_id,$product->categories) && !$seo_full)
			{
				$product->category_name = $category->category_name;
			}

			$category_model->addImages($category, 1);
			$this->category = $category;

			$category->children = $category_model->getChildCategoryList($product->virtuemart_vendor_id, $product->virtuemart_category_id);
			$category_model->addImages($category->children, 1);
		}

		if (!empty($tpl))
		{
			$format = $tpl;
		}
		else
		{
			$format = vRequest::getCmd('format', 'html');
		}
		
		if ($format == 'html')
		{
			// remove joomla canonical before adding it
			foreach ($document->_links as $k => $array)
			{
				if ( $array['relation'] == 'canonical' )
				{
					unset($document->_links[$k]);
					break;
				}
			}

			// Set Canonic link
			if ($isCustomVariant !==false && !empty($isCustomVariant->usecanonical) && !empty($product->product_parent_id))
			{
				$parent = $product_model->getProduct($product->product_parent_id);
				$document->addHeadLink( JUri::getInstance()->toString(array('scheme', 'host', 'port')).JRoute::_($parent->canonical), 'canonical', 'rel', '');
			}
			else
			{
				$document->addHeadLink( JUri::getInstance()->toString(array('scheme', 'host', 'port')).JRoute::_($product->canonical), 'canonical', 'rel', '');
			}

		}
		elseif ($format == 'pdf')
		{
			defined('K_PATH_IMAGES') or define ('K_PATH_IMAGES', VMPATH_ROOT);
		}

		// Set the titles
		// $document->setTitle should be after the additem pathway
		if ($product->customtitle)
		{
			$document->setTitle(strip_tags(html_entity_decode($product->customtitle,ENT_QUOTES)));
		}
		else
		{
			$document->setTitle(strip_tags(html_entity_decode(($category->category_name ? (vmText::_($category->category_name) . ' : ') : '') . $product->product_name,ENT_QUOTES)));
		}

		$this->allowReview = $ratingModel->allowReview($product->virtuemart_product_id);
		$this->showReview  = $ratingModel->showReview($product->virtuemart_product_id);
		$this->rating_reviews='';
		
		if ($this->showReview)
		{
			$this->review = $ratingModel->getProductReviewForUser($product->virtuemart_product_id);
			$this->showall = vRequest::getBool('showall', false);
			
			if ($this->showall)
			{
				$limit = 50;
			}
			else
			{
				$limit = VmConfig::get( 'vm_num_ratings_show', 3 );
			}

			$this->rating_reviews = $ratingModel->getReviews($product->virtuemart_product_id, 0, $limit);
		}

		if ($this->showRating)
		{
			$this->vote = $ratingModel->getVoteByProduct($product->virtuemart_product_id);
		}

		$this->allowRating = $ratingModel->allowRating($product->virtuemart_product_id);

		$superVendor = vmAccess::isSuperVendor();

		if ($superVendor == 1 || $superVendor==$product->virtuemart_vendor_id || $superVendor)
		{
			$this->edit_link = JURI::root() . 'index.php?option=com_virtuemart&tmpl=component&manage=1&view=product&task=edit&virtuemart_product_id=' . $product->virtuemart_product_id;
			//$this->edit_link = $this->linkIcon($edit_link, 'COM_VIRTUEMART_PRODUCT_FORM_EDIT_PRODUCT', 'edit', false, false);
		}
		else
		{
			$this->edit_link = "";
		}

		// Load the user details
		$this->user = JFactory::getUser();

		// More reviews link
		vRequest::setVar('showall', 1);
		
		$uristring = vmURI::getCleanUrl();
		$this->more_reviews = $uristring;

		if ($product->metadesc)
		{
			$document->setDescription(strip_tags(html_entity_decode($product->metadesc,ENT_QUOTES)));
		}
		else
		{
			$document->setDescription(strip_tags(html_entity_decode($product->product_name,ENT_QUOTES)) . " " . $category->category_name . " " . strip_tags(html_entity_decode($product->product_s_desc,ENT_QUOTES)));
		}

		if ($product->metakey)
		{
			$document->setMetaData('keywords', $product->metakey);
		}

		if ($product->metarobot)
		{
			$document->setMetaData('robots', $product->metarobot);
		}

		if ($app->getCfg('MetaTitle') == '1')
		{
			$document->setMetaData('title', $product->product_name);  //Maybe better product_name
		}
		
		if ($app->getCfg('MetaAuthor') == '1')
		{
			$document->setMetaData('author', $product->metaauthor);
		}

		$showBasePrice = (vmAccess::manager() || vmAccess::isSuperVendor());
		$this->showBasePrice = $showBasePrice;

		$product->event = new stdClass();
		$product->event->afterDisplayTitle = '';
		$product->event->beforeDisplayContent = '';
		$product->event->afterDisplayContent = '';
		
		if (VmConfig::get('enable_content_plugin', 0))
		{
			shopFunctionsF::triggerContentPlugin($product, 'productdetails','product_desc');
		}

		$productDisplayShipments = array();
		$productDisplayPayments  = array();

		if (!class_exists('vmPSPlugin'))
		{
			require(JPATH_VM_PLUGINS . DIRECTORY_SEPARATOR . 'vmpsplugin.php');
		}
			
		JPluginHelper::importPlugin('vmshipment');
		JPluginHelper::importPlugin('vmpayment');
		
		if (version_compare(JVERSION, '4.0.0', 'ge'))
		{
			$app->triggerEvent('plgVmOnProductDisplayShipment', array($product, &$productDisplayShipments));
			$app->triggerEvent('plgVmOnProductDisplayPayment', array($product, &$productDisplayPayments));
		}
		else
		{
			JDispatcher::getInstance()->trigger('plgVmOnProductDisplayShipment', array($product, &$productDisplayShipments));
			JDispatcher::getInstance()->trigger('plgVmOnProductDisplayPayment', array($product, &$productDisplayPayments));
		}

		$this->productDisplayPayments  = $productDisplayPayments;
		$this->productDisplayShipments = $productDisplayShipments; 

		if (empty($category->category_template))
		{
			$category->category_template = VmConfig::get('categorytemplate');
		}

		shopFunctionsF::setVmTemplate($this, $category->category_template, 0, $category->category_product_layout, $product->layout);

		shopFunctionsF::addProductToRecent($virtuemart_product_id);

		if (vRequest::getCmd( 'layout', 'default' )=='notify') $this->setLayout('notify'); //Added by Seyi Awofadeju to catch notify layout
		VmConfig::loadJLang('com_virtuemart');

		vmJsApi::chosenDropDowns();

		if (VmConfig::get ('jdynupdate', true))
		{
			vmJsApi::jDynUpdate();
		}

		if ($this->show_prices)
		{
			if (!class_exists('calculationHelper'))
			{
				require(VMPATH_ADMIN . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'calculationh.php');
			}
		}
		
		$this->document->setMetaData('robots', 'NOINDEX, NOFOLLOW, NOARCHIVE, NOSNIPPET');
		
		vmJsApi::jPrice();
		
		JHtml::addIncludePath(VMESSENTIALS_SITE . '/helpers/html');

		parent::display($tpl);
	}

	/**
	 * Check if state is set
	 *
	 * @param   mixed  $state  State
	 *
	 * @return bool
	 */
	public function getState($state)
	{
		return isset($this->state->{$state}) ? $this->state->{$state} : false;
	}
}
