<?php
/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.utilities.date');

class plgUserDjcatalog2 extends JPlugin
{
	public static $component_language_loaded = false;
	
	public function __construct(& $subject, $config)
	{
		parent::__construct($subject, $config);
		$this->loadLanguage();
		
		jimport('joomla.filesystem.folder');
		jimport('joomla.filesystem.file');
		
		require_once(JPATH_ROOT.'/components/com_djcatalog2/defines.djcatalog2.php');
		require_once(JPATH_ROOT.'/components/com_djcatalog2/helpers/route.php');
		require_once(JPATH_ROOT.'/components/com_djcatalog2/helpers/djcatalog2.php');
		
		require_once(JPATH_ROOT.'/components/com_djcatalog2/helpers/user.php');
		
		Djcatalog2Helper::loadComponentLanguage();
		
	}
	
	function onContentPrepareData($context, $data)
	{
		if (!in_array($context, array('com_users.profile', 'com_users.user', 'com_users.registration', 'com_admin.profile')))
		{
			return true;
		}
		
		$app = JFactory::getApplication();
		
		if (is_object($data))
		{
			$userId = isset($data->id) ? $data->id : 0;
			
			if (!isset($data->djcatalog2profile) && $userId > 0)
			{
				$option = $app->input->getCmd('option');
				$view = $app->input->getCmd('view');
				$layout = $app->input->getCmd('layout');
				$task = $app->input->getCmd('task');
				
				$translate = false;
				$area = '*';
				
				if ($option == 'com_djcatalog2') {
					if ($task == '') {
						if ($view == 'checkout') {
							$area = 'checkout';
						} else if ($view == 'query') {
							$area = 'query';
						}
					} else {
						if ($task == 'cart.confirm') {
							$area = 'checkout';
						} else if ($task == 'cart.query_confirm') {
							$area = 'query';
						}
					}
				} else {
					if ($context == 'com_users.profile' || $context == 'com_users.user' || 'com_admin.profile') {
						$area = 'profile';
					} else {
						$area = 'register';
					}
					if ($layout != 'edit') {
						$translate = true;
					}
				}
				//$area = ($context == 'com_users.profile' || $context == 'com_users.user' || 'com_admin.profile') ? 'profile' : 'register';
				$userData = (array)Djcatalog2HelperUser::getUserData($userId, $area, $translate);
				
				foreach($userData as $area => $userFields) {
					$data->$area = $userFields;
				}
			}
		}
		
		if (!Joomla\CMS\HTML\HTMLHelper::isRegistered('users.country_id'))
		{
			Joomla\CMS\HTML\HTMLHelper::register('users.country_id', array(__CLASS__, 'country'));
		}
		if (!Joomla\CMS\HTML\HTMLHelper::isRegistered('users.state_id'))
		{
			Joomla\CMS\HTML\HTMLHelper::register('users.state_id', array(__CLASS__, 'country_state'));
		}
		if (!Joomla\CMS\HTML\HTMLHelper::isRegistered('users.customer_group_id'))
		{
			Joomla\CMS\HTML\HTMLHelper::register('users.customer_group_id', array(__CLASS__, 'customer_group_id'));
		}
		if (!Joomla\CMS\HTML\HTMLHelper::isRegistered('users.client_type'))
		{
			Joomla\CMS\HTML\HTMLHelper::register('users.client_type', array(__CLASS__, 'client_type'));
		}
		
		if (!Joomla\CMS\HTML\HTMLHelper::isRegistered('users.www'))
		{
			Joomla\CMS\HTML\HTMLHelper::register('users.www', array(__CLASS__, 'www'));
		}
		
		if (!Joomla\CMS\HTML\HTMLHelper::isRegistered('users.user_id'))
		{
			Joomla\CMS\HTML\HTMLHelper::register('users.user_id', array(__CLASS__, 'user_id'));
		}
		if (!Joomla\CMS\HTML\HTMLHelper::isRegistered('users.gdpr_agreement'))
		{
			Joomla\CMS\HTML\HTMLHelper::register('users.gdpr_agreement', array(__CLASS__, 'yes_no_val'));
			Joomla\CMS\HTML\HTMLHelper::register('users.gdpr_policy', array(__CLASS__, 'yes_no_val'));
		}
		if (!Joomla\CMS\HTML\HTMLHelper::isRegistered('users.tos'))
		{
			Joomla\CMS\HTML\HTMLHelper::register('users.tos', array(__CLASS__, 'yes_no_val'));
		}
		
		return true;
	}
	
	function onContentPrepareForm($form, $data)
	{
		$app = JFactory::getApplication();
		
		if (!($form instanceof JForm))
		{
			$this->_subject->setError('JERROR_NOT_A_FORM');
			return false;
		}
		
	
		
		// Check we are manipulating a valid form.
		$name = $form->getName();
		if (!in_array($name, array('com_admin.profile', 'com_users.user', 'com_users.profile', 'com_users.registration')))
		{
			return true;
		}

		if ($app->input->getCmd('option') == 'com_djclassifieds') {
			return true;
		}
		
		if (JFactory::getUser()->get('requireReset', 0)) {
			return true;
		}
		
		$params = $this->params;
		
		$xml =Djcatalog2HelperUser::getUserFormXML($form->getName(), $data);
		$form->load($xml, true);
		
		$app = JFactory::getApplication();
		
		if ($app->isClient('site')) {
			$visibleGroups = $this->params->get('customer_groups_visible', array());
			$nonApprovalGroups = $this->params->get('customer_groups_no_approval', array());
			
			/*
			if ($name == 'com_users.profile') {
				if ($params->get('customer_group_approval', 1)) {
					if (!empty($nonApprovalGroups)) {
						$form->setFieldAttribute('customer_group_id', 'visible-groups', implode(',', $nonApprovalGroups), 'djcatalog2profile');
					} else {
						$form->removeField('customer_group_id', 'djcatalog2profile');
					}
				} else {
					$form->setFieldAttribute('customer_group_id', 'visible-groups', implode(',', $visibleGroups), 'djcatalog2profile');
				}
			} else {
				if (!empty($visibleGroups)) {
					$form->setFieldAttribute('customer_group_id', 'visible-groups', implode(',', $visibleGroups), 'djcatalog2profile');
				}
			}
			*/
			
			if ($name == 'com_users.profile' || $name == 'com_users.registration') {
				if (!empty($visibleGroups)) {
					$form->setFieldAttribute('customer_group_id', 'visible-groups', implode(',', $visibleGroups), 'djcatalog2profile');
				} else {
					$form->removeField('customer_group_id', 'djcatalog2profile');
				}
			}
			
		} else {
			$fieldsMap = ['basicprofile' => 'djcatalog2profile', 'additional' => 'djcatalog2statements'];
			foreach($fieldsMap as $fieldset => $group) {
				$catalog_fields = $form->getFieldset($fieldset);
				foreach ($catalog_fields as $field) {
					$form->setFieldAttribute($field->fieldname, 'required', null, $group);
					$class = $form->getFieldAttribute($field->fieldname, 'class', '', $group);
					$class = str_replace('required', '', $class);
					$form->setFieldAttribute($field->fieldname, 'class', $class, $group);
				}
			}
		}
		
		$user = JFactory::getUser();
		$salesman = $user->authorise('djcatalog2.salesman', 'com_djcatalog2');
		
		$djc2_params = JComponentHelper::getParams('com_djcatalog2');
		
		if (!$salesman || $name != 'com_users.profile' || $app->input->getCmd('layout', false) || !$djc2_params->get('cart_enable_salesman')) {
			$form->removeField('user_id', 'djcatalog2profile');
		}
		
		return true;
	}
	
	function onUserBeforeDataValidation($form, &$data) {
		if (!in_array($form->getName(), array('com_users.profile', 'com_users.user', 'com_users.registration', 'com_admin.profile')))
		{
			return true;
		}
		
		$app = JFactory::getApplication();
		if ($app->input->getCmd('option') == 'com_djclassifieds') {
			return true;
		}
		
		Djcatalog2HelperUser::prepareFormValidation($form, $data);
		
		return true;
	}
	
	function onUserBeforeSave($oldData, $isNew, $data)
	{
	}
	
	function onUserAfterSave($data, $isNew, $result, $error)
	{
		
		if (!isset($data['djcatalog2profile']) || !isset($data['djcatalog2statements'])) {
			return true;
		}
		
		$userId	= Joomla\Utilities\ArrayHelper::getValue($data, 'id', 0, 'int');
		$user = JFactory::getUser($userId);
		$date = JFactory::getDate();
		$params = JComponentHelper::getParams('com_djcatalog2');
		$app = JFactory::getApplication();
		$db = JFactory::getDbo();
		//$files = $app->input->files->get('jform', array());
		
		
		/*$image_whitelist = explode(',', $image_types);
		 foreach($image_whitelist as $key => $extension) {
		 $image_whitelist[$key] = strtolower(trim($extension));
		 }*/
		$registeredToGroup = false;
		
		if ($userId && $result) {
			
			if ($isNew && $app->isClient('site')) {
				
				$visibleGroups = $this->params->get('customer_groups_visible', array());
				$nonApprovalGroups = $this->params->get('customer_groups_no_approval', array());
				
				// UNSET Customer Group if it requires approval and is not default
				if (isset($data['djcatalog2profile']['customer_group_id']) && $data['djcatalog2profile']['customer_group_id'] > 0 && $this->params->get('customer_group_approval', 1) == 1) {
					if ((count($visibleGroups) > 0 && in_array($data['djcatalog2profile']['customer_group_id'], $visibleGroups)) || count($visibleGroups) < 1) {
						$query = $db->getQuery(true);
						$query->select('*')->from('#__djc2_customer_groups')->where('id='.(int)$data['djcatalog2profile']['customer_group_id']);
						$db->setQuery($query);
						$group = $db->loadObject();
						
						if (empty($group)) {
							$data['djcatalog2profile']['customer_group_id'] = 0;
						}
						else if ((count($nonApprovalGroups) && !in_array($data['djcatalog2profile']['customer_group_id'], $nonApprovalGroups))
							|| (count($nonApprovalGroups) < 1 && !$group->is_default)) {
								
								$registeredToGroup = $data['djcatalog2profile']['customer_group_id'];
								$data['djcatalog2profile']['customer_group_id'] = 0;
							}
					}
				}
			} else if (!$app->isClient('administrator')) {
				if (isset($data['djcatalog2profile']) && isset($data['djcatalog2profile']['customer_group_id'])) {
					unset($data['djcatalog2profile']['customer_group_id']);
				}
			}
			
			$saved = Djcatalog2HelperUser::saveUserProfile($userId, $data, ($isNew ? 'register' : 'profile'));

			if ($saved && $registeredToGroup) {
				$this->notifyGroupSelection($registeredToGroup, $user);
			}
			
			return $saved;
			
			
			if (isset($data['djcatalog2profile']) && (count($data['djcatalog2profile'])))
			{
				try
				{
					
					$row = new stdClass();
					$data['djcatalog2profile']['user_id'] = $userId;
					foreach($data['djcatalog2profile'] as $column => $value) {
						$row->$column = $value;
					}
					
					$gdpr_policy = 0;
					if (isset($data['djcatalog2statements']) && !empty($data['djcatalog2statements']['gdpr_policy'])) {
						$gdpr_policy = 1;
					}
					
					$gdpr_agreement = 0;
					if (isset($data['djcatalog2statements']) && !empty($data['djcatalog2statements']['gdpr_agreement'])) {
						$gdpr_agreement = 1;
					}
					
					$tos_agreement = 0;
					if (isset($data['djcatalog2statements']) && !empty($data['djcatalog2statements']['tos'])) {
						$tos_agreement = 1;
					}
					
					$isempty = true;
					foreach ($row as $value) {
						if (!empty($value)) {
							$isempty = false;
							break;
						}
					}
					if ($isempty && $app->isClient('administrator')) {
						$this->onUserAfterDelete($user->getProperties(1), true, '');
					} else {
						$db->setQuery('SELECT * FROM #__djc2_users WHERE user_id = '.$userId);
						if ($djuser = $db->loadObject()) {
							$row->id = $djuser->id;
							if ($app->isClient('site')) {
								$row->customer_group_id = $djuser->customer_group_id;
								$row->client_type = $djuser->client_type;
								
								$row->gdpr_agreement = $djuser->gdpr_agreement ? $djuser->gdpr_agreement : $gdpr_agreement;
								$row->gdpr_policy = $djuser->gdpr_policy ? $djuser->gdpr_policy : $gdpr_policy;
								$row->tos = $djuser->tos ? $djuser->tos : $tos_agreement;
							} else {
								$row->gdpr_policy = $gdpr_policy;
								$row->gdpr_agreement = $gdpr_agreement;
								$row->tos = $tos_agreement;
							}
						} else {
							/*
							 * NOT USED ANY MORE
							 $db->setQuery('SELECT id FROM #__djc2_customer_groups WHERE is_default=1');
							 $group_id = $db->loadResult();
							 $row->customer_group_id = $group_id ? $group_id : 0;
							 */
							
							if ($isNew && $app->isClient('site')) {
								
								$visibleGroups = $this->params->get('customer_groups_visible', array());
								$nonApprovalGroups = $this->params->get('customer_groups_no_approval', array());
								
								// UNSET Customer Group if it requires approval and is not default
								if (isset($row->customer_group_id) && $row->customer_group_id > 0 && $this->params->get('customer_group_approval', 1) == 1) {
									if ((count($visibleGroups) > 0 && in_array($row->customer_group_id, $visibleGroups)) || count($visibleGroups) < 1) {
										$query = $db->getQuery(true);
										$query->select('*')->from('#__djc2_customer_groups')->where('id='.(int)$row->customer_group_id);
										$db->setQuery($query);
										$group = $db->loadObject();
										
										if (empty($group)) {
											$row->customer_group_id = 0;
										}
										else if ((count($nonApprovalGroups) && !in_array($row->customer_group_id, $nonApprovalGroups))
											|| (count($nonApprovalGroups) < 1 && !$group->is_default)) {
												
												$registeredToGroup = $row->customer_group_id;
												$row->customer_group_id = 0;
											}
									}
								}
							}
							
							$client_type = $params->get('default_client_type', 'R');
							$row->client_type = ($client_type == 'R' || $client_type == 'W') ? $client_type : 'R';
							
							$row->gdpr_policy = $gdpr_policy;
							$row->gdpr_agreement = $gdpr_agreement;
							$row->tos = $tos_agreement;
						}
						
						$row->modified = $date->toSql();
						
						if ($row->id > 0) {
							if (!$db->updateObject('#__djc2_users', $row, 'id', true))
							{
								throw new Exception($db->getErrorMsg());
							}
						} else {
							if (!$db->insertObject('#__djc2_users', $row))
							{
								throw new Exception($db->getErrorMsg());
							}
						}
						
						
						if (($user->name == '---' || empty($user->name)) && !empty($row->firstname) && !empty($row->firstname)) {
							$new_name = $row->firstname.' '.$row->lastname;
							$user->set('name', $new_name);
							$db->setQuery('update #__users set name='.$db->quote($new_name).' where id='.(int)$userId);
							$db->execute();
						}
						$company_name = $row->company;
					}
				}
				catch (JException $e)
				{
					$this->_subject->setError($e->getMessage());
					return false;
				}
			}
		}
		
		$cart_registration = $app->getUserState('com_djcatalog2.cart_registration');
		$users_params = JComponentHelper::getParams('com_users');
		if ($app->isClient('site') && $isNew && $result && $cart_registration && $users_params->get('useractivation') == 0) {
			$credentials = array();
			$credentials['username'] = $data['username'];
			$credentials['password'] = $data['password1'];
			
			$options = array();
			$options['remember'] = true;
			
			$language 	= JFactory::getLanguage();
			$base_dir 	= JPATH_SITE . '/language';
			if(!$language->load('com_users', $base_dir, $language->getTag(), true))
			{
				$language->load('com_users', $base_dir, 'en-GB', true);
			}
			
			$sendpassword = $users_params->get('sendpassword', 1);
			
			$config = JFactory::getConfig();
			
			$user_data = $data;
			$user_data['fromname'] = $config->get('fromname');
			$user_data['mailfrom'] = $config->get('mailfrom');
			$user_data['sitename'] = $config->get('sitename');
			$user_data['siteurl'] = JUri::root();
			
			$emailSubject = JText::sprintf(
				'COM_USERS_EMAIL_ACCOUNT_DETAILS',
				$user_data['name'],
				$user_data['sitename']
				);
			
			$emailBody = '';
			if ($sendpassword)
			{
				$emailBody = JText::sprintf(
					'COM_USERS_EMAIL_REGISTERED_BODY',
					$user_data['name'],
					$user_data['sitename'],
					$user_data['siteurl'],
					$user_data['username'],
					$user_data['password_clear']
					);
			}
			else
			{
				$emailBody = JText::sprintf(
					'COM_USERS_EMAIL_REGISTERED_BODY_NOPW',
					$user_data['name'],
					$user_data['sitename'],
					$user_data['siteurl']
					);
			}
			
			JFactory::getMailer()->sendMail($user_data['mailfrom'], $user_data['fromname'], $user_data['email'], $emailSubject, $emailBody);
			
			$app->login($credentials, $options);
			
			$app->getUserState('com_djcatalog2.cart_registration', null);
			$app->setUserState('users.login.form.data', array());
			$app->redirect(JRoute::_(DJCatalog2HelperRoute::getCheckoutRoute(), false));
		}
		
		return true;
	}
	
	function onUserAfterDelete($user, $success, $msg)
	{
		if (!$success)
		{
			return false;
		}
		
		$userId	= Joomla\Utilities\ArrayHelper::getValue($user, 'id', 0, 'int');
		$db = JFactory::getDbo();
		if ($userId)
		{
			$db->setQuery('select id from #__djc2_users WHERE user_id='.$userId);
			$catalogUserId = $db->loadResult();
			
			$db->setQuery('SELECT id FROM #__djc2_vendors WHERE user_id='. $userId);
			$vendorId = $db->loadResult();
			
			if ($catalogUserId) {
				try
				{
					$db->setQuery('DELETE FROM #__djc2_users WHERE id = '.$catalogUserId);
					$db->execute();
					
					$db->setQuery('DELETE FROM #__djc2_users_extra_fields_values_int WHERE item_id = '.$catalogUserId);
					$db->execute();
					
					$db->setQuery('DELETE FROM #__djc2_users_extra_fields_values_text WHERE item_id = '.$catalogUserId);
					$db->execute();
					
					$db->setQuery('DELETE FROM #__djc2_users_extra_fields_values_date WHERE item_id = '.$catalogUserId);
					$db->execute();
					
					$db->setQuery('DELETE FROM #__djc2_vendors_customers WHERE customer_id= '.$userId);
					$db->execute();
					
					$db->setQuery('DELETE FROM #__djc2_vendors WHERE user_id= '.$userId);
					$db->execute();
					
					if($vendorId) {
						$db->setQuery('DELETE FROM #__djc2_vendors_customers WHERE vendor_id= '. $vendorId);
						$db->execute();
					}
					
				}
				catch (JException $e)
				{
					$this->_subject->setError($e->getMessage());
					return false;
				}
			}
		}
		
		return true;
	}
	/*
	 private function _notifyAfterSave($item, $user)
	 {
	 $app		= JFactory::getApplication();
	 $params 	= JComponentHelper::getParams('com_djcatalog2');
	 
	 $mailfrom	= $app->getCfg('mailfrom');
	 $fromname	= $app->getCfg('fromname');
	 $sitename	= $app->getCfg('sitename');
	 $copytext 	= JText::sprintf('COM_DJCATALOG2_COPYTEXT_OF', $item->name, $sitename);
	 
	 $contact_list = $params->get('fed_notify_list', false);
	 $recipient_list = array();
	 if ($contact_list !== false) {
	 $recipient_list = explode(PHP_EOL, $params->get('fed_notify_list', ''));
	 }
	 
	 $list_is_empty = true;
	 foreach ($recipient_list as $r) {
	 if (strpos($r, '@') !== false) {
	 $list_is_empty = false;
	 break;
	 }
	 }
	 
	 if ($list_is_empty) {
	 $recipient_list[] = $mailfrom;
	 }
	 
	 $recipient_list = array_unique($recipient_list);
	 
	 $name = null;
	 $email = null;
	 $item_name = $item->name;
	 $item_id = $item->id;
	 
	 $subject	= JText::_('COM_DJCATALOG2_NEW_PRODUCT_SUBMITTED_SUBJECT');
	 $body = '';
	 if ($user->guest) {
	 $body = JText::sprintf('COM_DJCATALOG2_PRODUCT_SUBMITTED_BY_GUEST', $item_id, $item_name);
	 } else {
	 $name		= $user->name.' ('.$user->username.')';
	 $email		= $user->email;
	 $body = JText::sprintf('COM_DJCATALOG2_PRODUCT_SUBMITTED', $item_id, $item_name, $name, $email);
	 }
	 
	 $body .= "\n\n".JURI::base().'administrator/index.php?option=com_djcatalog2&view=items&filter_search='.urlencode('id:'.$item_id);
	 
	 $mail = JFactory::getMailer();
	 
	 //$mail->addRecipient($mailfrom);
	 foreach ($recipient_list as $recipient) {
	 $mail->addRecipient(trim($recipient));
	 }
	 if ($user->guest == false) {
	 $mail->addReplyTo(array($email, $name));
	 }
	 $mail->setSender(array($mailfrom, $fromname));
	 $mail->setSubject($sitename.': '.$subject);
	 $mail->setBody($body);
	 $sent = $mail->Send();
	 
	 return $sent;
	 }
	 
	 public static function image($value, $alt = '')
	 {
	 if (empty($value))
	 {
	 return Joomla\CMS\HTML\HTMLHelper::_('users.value', $value);
	 }
	 else
	 {
	 $directory = self::$images_path;
	 $image_path = JURI::root().'/'.$directory.'/'.$value;
	 
	 return '<img src="'.$image_path.'" alt="'.htmlspecialchars($alt).'" />';
	 }
	 }*/
	
	private function notifyGroupSelection($group_id, $user) {
		$app		= JFactory::getApplication();
		$params 	= JComponentHelper::getParams('com_djcatalog2');
		$db = JFactory::getDbo();
		
		$mailfrom	= $app->getCfg('mailfrom');
		$fromname	= $app->getCfg('fromname');
		$sitename	= $app->getCfg('sitename');
		
		$contact_list = $params->get('contact_list', false);
		$recipient_list = array();
		if ($contact_list !== false) {
			$recipient_list = explode(PHP_EOL, $params->get('contact_list', ''));
		}
		
		$list_is_empty = true;
		foreach ($recipient_list as $r) {
			if (strpos($r, '@') !== false) {
				$list_is_empty = false;
				break;
			}
		}
		
		if ($list_is_empty) {
			$recipient_list[] = $mailfrom;
		}
		
		$query = $db->getQuery(true);
		$query->select('name')->from('#__djc2_customer_groups')->where('id='.(int)$group_id);
		$db->setQuery($query);
		$group_name = $db->loadResult();
		if (empty($group_name)) {
			return false;
		}
		
		$subject = JText::_('COM_DJCATALOG2_EMAIL_SUBJECT_CUSTOMER_GROUP_APPLICATION');
		$body = JText::sprintf('COM_DJCATALOG2_EMAIL_BODY_CUSTOMER_GROUP_APPLICATION', $user->name, $user->email, $group_name);
		
		$mail = JFactory::getMailer();
		$mail->addReplyTo($user->email, $user->name);
		$mail->setSubject($sitename.': '.$subject);
		$mail->isHtml(true);
		$mail->setBody('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>' . $body . '</body></html>');
		
		foreach($recipient_list as $recipient) {
			$mail->clearAddresses();
			$mail->addRecipient(trim($recipient));
			$mail->Send();
		}
		
		return true;
	}
	
	public static function country($value)
	{
		if (empty($value) || !(int)$value)
		{
			return Joomla\CMS\HTML\HTMLHelper::_('users.value', $value);
		}
		else
		{
			$db = JFactory::getDbo();
			$db->setQuery('select country_name from #__djc2_countries where id ='.(int)$value);
			$country = $db->loadResult();
			
			return (empty($country)) ? Joomla\CMS\HTML\HTMLHelper::_('users.value', $value) : $country;
		}
	}
	
	public static function country_state($value)
	{
		if (empty($value) || !(int)$value)
		{
			return Joomla\CMS\HTML\HTMLHelper::_('users.value', $value);
		}
		else
		{
			$db = JFactory::getDbo();
			$db->setQuery('select name from #__djc2_countries_states where id ='.(int)$value);
			$state = $db->loadResult();
			
			return (empty($state)) ? Joomla\CMS\HTML\HTMLHelper::_('users.value', $value) : $state;
		}
	}
	
	public static function client_type($value)
	{
		if (empty($value))
		{
			return Joomla\CMS\HTML\HTMLHelper::_('users.value', $value);
		}
		else
		{
			return JText::_('COM_DJCATALOG2_CLIENT_TYPE_' . $value);
		}
	}
	
	public static function customer_group_id($value)
	{
		if (empty($value) || !(int)$value)
		{
			return Joomla\CMS\HTML\HTMLHelper::_('users.value', $value);
		}
		else
		{
			$db = JFactory::getDbo();
			$db->setQuery('select name from #__djc2_customer_groups where id ='.(int)$value);
			$group = $db->loadResult();
			
			return (empty($group)) ? Joomla\CMS\HTML\HTMLHelper::_('users.value', $value) : $group;
		}
	}
	
	public static function www($value)
	{
		if (empty($value))
		{
			return Joomla\CMS\HTML\HTMLHelper::_('users.value', $value);
		}
		else
		{
			$value = htmlspecialchars($value);
			if (substr ($value, 0, 4) == "http")
			{
				return '<a href="'.$value.'" target="_blank">'.$value.'</a>';
			}
			else
			{
				return '<a href="http://'.$value.'" target="_blank">'.$value.'</a>';
			}
		}
	}
	
	public static function user_id($value)
	{
		$user = JFactory::getUser();
		$salesman = $user->authorise('djcatalog2.salesman', 'com_djcatalog2');
		
		if (empty($value) || !$salesman)
		{
			return '';//Joomla\CMS\HTML\HTMLHelper::_('users.value', $value);
		}
		else
		{
			
			$app = JFactory::getApplication();
			$db = JFactory::getDbo();
			
			$query = $db->getQuery(true);
			$query->select('id')->from('#__djc2_vendors')->where('user_id='.(int)$user->id);
			$db->setQuery($query);
			$vendor_id = $db->loadResult();
			
			if (!$vendor_id){
				return '-';
			}
			
			$query = $db->getQuery(true);
			$query->select('u.id, u.name, u.username, u.email');
			$query->from('#__users as u');
			$query->join('INNER', '(select customer_id from #__djc2_vendors_customers where vendor_id = '.(int)$vendor_id.') as vc ON vc.customer_id = u.id');
			$query->order('u.name');
			$db->setQuery($query);
			
			$users = $db->loadObjectList();
			
			$active = $app->getUserState('com_djcatalog2.checkout.user_id', $user->id);
			
			$html = '<select onchange="DJC2CheckoutgetUserData(this.value);">';
			$html .= '<option value="0" ' . (($active == 0) ? 'selected="selected"' : '') . '>'. JText::_('COM_DJCATALOG2_DJCUSER_NONE') .'</option>';
			
			if(count($users)) {
				foreach($users as $user) {
					$selected = $active == $user->id ? 'selected="selected"' : '';
					$html .= '<option value="'.$user->id.'" '.$selected.'>'.$user->name.', '.$user->username.', '.$user->email.'</option>';
				}
			} else {
				$user = JFactory::getUser();
				$html .= '<option value="'.$user->id.'" ' . (($active == $user->id) ? 'selected="selected"' : '') . '>'.$user->name.', '.$user->username.', '.$user->email.'</option>';
			}
			
			$html .= '</select>
					<script type="text/javascript">
					function DJC2CheckoutgetUserData (user_id) {
						window.location.href = "'.JUri::base(false).'index.php?option=com_djcatalog2&task=cart.selectUser&user_id=" + user_id;
					}
					</script>';
			
			return $html;
		}
	}
	
	public static function yes_no_val($value)
	{
		return $value ? JText::_('JYES') : JText::_('JNO');
	}
	
	
	public function onBeforeRender() {
	}
	
	/*public function onAfterInitialise() {
	 $app = JFactory::getApplication();
	 $user = JFactory::getUser();
	 $users_params = JComponentHelper::getParams('com_users');
	 $activation = $users_params->get('useractivation');
	 $cart_registration = $app->getUserState('com_djcatalog2.cart_registration');
	 
	 $input = $app->input;
	 
	 if ($app->isClient('site') && $user->guest && $activation > 0 && $cart_registration) {
	 if ($input->get('option') == 'com_users' && $input->get('view') == 'registration' && $input->get('layout') == 'complete') {
	 $app->getUserState('com_djcatalog2.cart_registration', null);
	 
	 $msg = ($activation == 1) ? JText::_('COM_USERS_REGISTRATION_COMPLETE_ACTIVATE') : JText::_('COM_USERS_REGISTRATION_COMPLETE_VERIFY');
	 $app->enqueueMessage($msg);
	 $app->redirect(JRoute::_(DJCatalog2HelperRoute::getCartRoute().'&layout=login', false));
	 }
	 }
	 }*/
}
