<?php
/**
 * @package     VP Advanced User
 * @subpackage  Content Plugin - VP Advanced User
 * @author      Abhishek Das <info@virtueplanet.com>
 * @copyright   Copyright (C) 2012-2019 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;

// VP Advanced User Component not found
if(!(include_once(JPATH_SITE . '/components/com_vpadvanceduser/define.php')) || !defined('JPATH_ADVANCEDUSER_ADMIN'))
{
	return;
}

/**
* VP Advanced User Plugin
* 
* @package   VP Advanced User
* @since     1.0
*/
class plgContentVPAdvancedUser extends JPlugin
{
	protected $app;
	
	protected $_params;
	
	protected $_data;
	
	/**
	 * Constructor.
	 *
	 * @param   object  &$subject  The object to observe
	 * @param   array   $config    An optional associative array of configuration settings.
	 *
	 * @since   1.0.0
	 */
	public function __construct(&$subject, $config) 
	{
		parent::__construct ($subject, $config);
		
		JFactory::getLanguage()->load('com_vpadvanceduser.sys');
		JFactory::getLanguage()->load('com_vpadvanceduser');
		JFactory::getLanguage()->load('com_users');
		
		$this->_params = JComponentHelper::getParams('com_vpadvanceduser');
	}

	public function onContentBeforeDisplay($context, &$article, &$params)
	{
		if($context != 'com_content.article')
		{
			return false;
		}
		
		$temp = clone $params;
		$temp->merge($article->params);
		$temp->def('author_profile', $this->_params->get('author_profile'));
		$this->_params->set('author_profile', $temp->get('author_profile'));
		
		if($this->_params->get('author_profile') == 'above')
		{
			return $this->getAuthorProfile($article, $temp);
		}
	}
	
	public function onContentAfterDisplay($context, &$article, &$params)
	{
		if($context != 'com_content.article')
		{
			return false;
		}
		
		$temp = clone $params;
		$temp->merge($article->params);
		$temp->def('author_profile', $this->_params->get('author_profile'));
		$this->_params->set('author_profile', $temp->get('author_profile'));
		
		if($this->_params->get('author_profile') == 'below')
		{
			return $this->getAuthorProfile($article, $temp);
		}
	}
	
	/**
	 * On content form preparation.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	function onContentPrepareForm($form, $data)
	{
		if(!($form instanceof JForm))
		{
			return;
		}
		
		JForm::addFormPath(__DIR__ . '/forms');

		$context = $form->getName();
		$mData   = (object) $data;
		$request = isset($mData->request) ? (array) $mData->request : array();
		
		if($context == 'com_content.article')
		{
			$form->loadFile('article', false);
		}
		elseif($context == 'com_menus.item') 
		{
			$option = isset($request['option']) ? $request['option'] : '';
			$view   = isset($request['view']) ? $request['view'] : '';

			if($option == 'com_content' && $view == 'category')
			{
				$form->loadFile('category', false);
			}
			elseif($option == 'com_content' && $view == 'article')
			{
				$form->loadFile('articlemenu', false);
			}
		}
		elseif($context == 'com_config.component')
		{
			$input     = $this->app->input;
			$component = $input->getCmd('component');
			
			if(strtolower($component) == 'com_vpadvanceduser')
			{
				if($this->hasExtension('com_virtuemart'))
				{
					$form->loadFile('config_virtuemart', false);
				}
				
				if($this->hasExtension('pkg_vp_advanced_user', 'package') && JPluginHelper::isEnabled('system', 'vpadvanceduser'))
				{
					$form->loadFile('config', false);
				}
			}
		}
	}
	
	private function getAuthorProfile($article, $params)
	{
		$user_id = isset($article->created_by) ? (int) $article->created_by : 0;
		
		if(empty($user_id))
		{
			return false;
		}
		
		if($this->app->input->getInt('tos'))
		{
			$article->pagination = false;
			return false;
		}
		
		if(!is_array($this->_data))
		{
			$this->_data = array();
		}
		
		if(!isset($this->_data[$user_id]))
		{
			// Get profile model
			$profileModel = $this->getModel();
			
			// Reset data cache in the model
			$profileModel->set('data', null);
			
			// Set the user id 
			$profileModel->setState('user.id', $user_id);
			
			// Try to get profile data
			$profile = $profileModel->getData();
			
			if($profile === false)
			{
				throw new Exception($profileModel->getError(), 500);
				return false;
			}
			
			// Save in internal cache
			$this->_data[$user_id] = $profile;
		}

		// Prepare display data
		$displayData = array(
		    'article' => $article,
		    'author' => $this->_data[$user_id],
		    'params' => $this->_params,
		    'link_author' => (bool) $params->get('link_author'),
		    'position' => $this->_params->get('author_profile')
		);
		
		// Render layout
		$html = JLayoutHelper::render('article_author', $displayData, null, array('client' => 'site', 'component' => 'com_vpadvanceduser'));
		
		return $html;
	}
	
	/**
	* Method to get the instance of any model
	* 
	* @param  string  $type     Type of the model
	* @param  string  $prefix   Model prefix
	* @param  array   $config   Any configuration information need to passed to model instance
	* 
	* @return object  Model class object. An exception thrown in case the model is not found.
	*/
	private function getModel($type = 'Profile', $prefix = 'VPAdvancedUserModel', $config = array('ignore_request' => true))
	{
		// Add models path
		JModelLegacy::addIncludePath(JPATH_ADVANCEDUSER_SITE . '/models', 'VPAdvancedUserModel');
		
		// Try to get an instace of the model
		$model = JModelLegacy::getInstance($type, $prefix, $config);
		
		if(!is_object($model))
		{
			// Throw exception if model not found
			throw new Exception(JText::sprintf('COM_VPADVANCEDUSER_MSG_ERROR_CLASS_NOT_FOUND', 'VPAdvancedUserModel' . ucfirst($type)), 500);
		}
		
		return $model;
	}
	
	/**
	* Method to check if an extension installed and enabled
	* 
	* @param  string  $element  Name of the extension
	* @param  string  $type     Type of the extension like component, module, plugins etc
	* 
	* @return boolean
	*/
	private function hasExtension($element, $type = 'component')
	{
		if(!class_exists('VPAdvancedUserHelper'))
		{
			require(JPATH_ADVANCEDUSER_ADMIN . '/helpers/vpadvanceduser.php');
		}
		
		return VPAdvancedUserHelper::hasExtension($element, $type);
	}
}