<?php
/**
 * @package    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;

/**
 * Class VPAdvancedUserFrontendHelper
 *
 * @since  1.0
 */
class VPAdvancedUserFrontendHelper
{
	protected static $menuLanguages = array();
	
	protected static $providers = null;
	
	
	public static function getUsernameByEmail($email, $onFail = null)
	{
		if(empty($email))
		{
			return $onFail;
		}
		
		// Basic sanitizer for email 
		$email = filter_var($email, FILTER_VALIDATE_EMAIL);
		
		if (!$email || !preg_match('/([\w\-]+\@[\w\-]+\.[\w\-]+)/', $email))
		{
			return $onFail;
		}
		
		// Joomla style email sanitizing
		$email = JStringPunycode::emailToPunycode($email);
		
		if(empty($email))
		{
			return $onFail;
		}
		
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true);
		
		$query->select($db->quoteName('username'))
		      ->from($db->quoteName('#__users'))
		      ->where($db->quoteName('email') . ' = ' . $db->quote($email));

		try
		{
			$db->setQuery($query);
			$username = $db->loadResult();
		}
		catch(RuntimeException $e)
		{
			JError::raiseWarning(500, $e->getMessage());
			return false;
		}
		
		if(!empty($username))
		{
			return $username;
		}
		
		return $onFail;
	}
	
	public static function getMenuItemLanguageString($menu_id)
	{
		$menu_id = (int) $menu_id;
		
		if(!isset(self::$menuLanguages[$menu_id]))
		{
			if (JLanguageMultilang::isEnabled())
			{
				$db = JFactory::getDbo();
				$query = $db->getQuery(true)
					->select('language')
					->from($db->quoteName('#__menu'))
					->where('client_id = 0')
					->where('id =' . $menu_id);

				$db->setQuery($query);

				try
				{
					$language = $db->loadResult();
				}
				catch (RuntimeException $e)
				{
					return;
				}

				if ($language !== '*')
				{
					self::$menuLanguages[$menu_id] = '&lang=' . $language;
				}
				else
				{
					self::$menuLanguages[$menu_id] = '';
				}
			}
			else
			{
				self::$menuLanguages[$menu_id] = '';
			}
		}
		
		return self::$menuLanguages[$menu_id];
	}
	
	public static function getCurrentUrl()
	{
		$url  = JUri::getInstance()->toString();
		$base = JUri::base();
		
		if($base && strpos($url, $base) === 0)
		{
			$url = str_replace($base, '', $url);
			$url = JUri::base(true) . '/' . $url;
		}
		
		if(empty($url))
		{
			$url = JUri::base(true) . '/';
		}
		
		if(strpos($url, '/') === false && strpos($url, 'index.php?') === 0 && strpos($url, 'option=') !== false)
		{
			$url = JRoute::_($url, false);
		}
		
		return $url;
	}
	
	public static function getProviders()
	{
		jimport('joomla.filesystem.folder');
		jimport('joomla.filesystem.file');
		
		if(!is_array(self::$providers))
		{
			$app           = JFactory::getApplication();
			$provider_path = JPATH_ADVANCEDUSER_SITE . '/libraries/Hybrid/Providers';
			
			if(!is_dir($provider_path))
			{
				$app->enqueueMessage('HybridAuth Providers directory not found.', 'warning');
				return false;
			}
			
			$available_providers = JFolder::files($provider_path, '.php');
			
			if(empty($available_providers))
			{
				$app->enqueueMessage('Could not the fetch list of authentication providers.', 'warning');
				return false;
			}
			
			$providers = array();
			
			foreach($available_providers as $value)
			{
				$value = str_replace('.php', '', $value);
				$key   = strtolower($value);
				
				$providers[$key] = $value;
			}
			
			self::$providers = $providers;
		}
		
		return self::$providers; 
	}
	
	public static function handlePrivacyConsentPlugin($start, $formData = null)
	{
		static $option =  null;
		static $task = null;
		static $jformData = null;
		
		if(!JPluginHelper::isEnabled('system', 'privacyconsent'))
		{
			return;
		}
		
		$input = JFactory::getApplication()->input;
		
		if($start)
		{
			$option = $input->getCmd('option');
			$task = $input->getCmd('task');
			$jformData = $input->post->get('jform', array(), 'array');
			
			$input->set('option', 'com_users');
			$input->set('task', 'registration.register');
			$input->get->set('option', 'com_users');
			$input->get->set('task', 'registration.register');

			if(is_array($formData))
			{
				$input->set('jform', $formData);
				$input->post->set('jform', $formData);
				
				//vpdump($input->post->get('jform', array(), 'array'));exit;
			}
		}
		else
		{
			$input->set('option', $option);
			$input->set('task', $task);
			$input->get->set('option', $option);
			$input->get->set('task', $task);
			
			$input->set('jform', $jformData);
			$input->post->set('jform', $jformData);
		}
	}
}
