<?php
/**
 * @package     VP Advanced User
 * @subpackage  Module - 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;

/**
 * Helper for mod_vpadvanceduser
 *
 * @since     1.0
 */
class ModVPAdvancedUserHelper
{
	private static $old_prefixes = array();
	
	public static function getModel($type = 'Login', $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);
		}
		
		JForm::addFormPath(JPATH_ADVANCEDUSER_SITE . '/models/forms');
		JForm::addFieldPath(JPATH_ADVANCEDUSER_ADMIN . '/models/fields');
		JForm::addFieldPath(JPATH_ADVANCEDUSER_SITE . '/models/fields');
		
		return $model;
	}
	
	public static function get($method, $modelName = 'Login')
	{
		$model  = self::getModel($modelName);
		$method = 'get' . ucfirst($method);

		if(!method_exists($model, $method))
		{
			return false;
		}
		
		return call_user_func(array($model, $method));
	}
	
	public static function prepareForm($formIn, $id_prefix = 'vpaumod_')
	{
		if($formIn instanceof JForm)
		{
			$form = clone($formIn);
			
			$fieldsets = $form->getFieldsets();
			
			foreach($fieldsets as $group => $fieldset)
			{
				$fields = $form->getFieldset($group);
				
				if(count($fields))
				{
					foreach($fields as $field)
					{
						if($field->id && strpos($field->id, $id_prefix) === false)
						{
							if(strpos($field->id, 'jform') === false)
							{
								$new_id = $id_prefix . $field->id;
							}
							elseif(strpos($field->id, 'jform_vpadvanceduserdata_') === 0)
							{
								$new_id = str_replace('jform_vpadvanceduserdata_', $id_prefix, $field->id);
							}
							else
							{
								$new_id = str_replace('jform_', $id_prefix, $field->id);
							}
							
							if(count(self::$old_prefixes))
							{
								foreach(self::$old_prefixes as $old_prefix)
								{
									if($old_prefix != $id_prefix)
									{
										$new_id = str_replace($old_prefix, '', $new_id);
									}
								}
							}

							$form->setFieldAttribute($field->fieldname, 'id', $new_id, $field->group);
						}
						
						if($field->autofocus)
						{
							// Do not auto focus fields in module
							$form->setFieldAttribute($field->fieldname, 'autofocus', false, $field->group);
						}
					}
				}
			}
			
			self::$old_prefixes[] = $id_prefix;
			
			return $form;
		}
		
		return $formIn;
	}
	
	/**
	 * Retrieve the url where the user should be returned after logging in
	 *
	 * @param   \Joomla\Registry\Registry  $params  module parameters
	 * @param   string                     $type    return type
	 *
	 * @return string
	 */
	public static function getReturnUrl($params, $type)
	{
		$app  = JFactory::getApplication();
		$item = $app->getMenu()->getItem($params->get($type . '_redirect'));

		if ($item)
		{
			// Register frontend helper
			JLoader::register('VPAdvancedUserFrontendHelper', JPATH_SITE . '/components/com_vpadvanceduser/helpers/vpadvanceduser.php');
			
			$lang = VPAdvancedUserFrontendHelper::getMenuItemLanguageString($item->id);
			
			$url = 'index.php?Itemid=' . $item->id . $lang;
		}
		else
		{
			// Stay on the same page
			$url = JUri::getInstance()->toString();
		}

		return VPAdvancedUserHelperUtility::encode($url);
	}

	/**
	 * Returns the current users type
	 *
	 * @return string
	 */
	public static function getType()
	{
		$user = JFactory::getUser();

		return (!$user->get('guest')) ? 'logout' : 'login';
	}

	/**
	 * Get list of available two factor methods
	 *
	 * @return array
	 */
	public static function getTwoFactorMethods()
	{
		if(!class_exists('UsersHelper'))
		{
			require JPATH_ADMINISTRATOR . '/components/com_users/helpers/users.php';
		}

		return UsersHelper::getTwoFactorMethods();
	}
}
