<?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;

use Joomla\Registry\Registry;

JLoader::register('UsersModelUser', JPATH_USERS_ADMIN . '/models/user.php');

/**
 * VPAdvancedUser model.
 *
 * @since  1.0
 */
class VPAdvancedUserModelUser extends UsersModelUser
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @since   3.2
	 */
	public function __construct($config = array())
	{
		parent::__construct($config);
		
		JModelLegacy::addIncludePath(JPATH_USERS_ADMIN . '/models', 'UsersModel');
		JModelLegacy::addTablePath(JPATH_USERS_ADMIN . '/tables');
	}

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param   string  $type    The table type to instantiate
	 * @param   string  $prefix  A prefix for the table class name. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable  A database object
	 *
	 * @since   1.6
	 */
	public function getTable($type = 'User', $prefix = 'JTable', $config = array())
	{
		$table = JTable::getInstance($type, $prefix, $config);

		return $table;
	}

	/**
	 * Method to get a single record.
	 *
	 * @param   integer  $pk  The id of the primary key.
	 *
	 * @return  mixed    Object on success, false on failure.
	 *
	 * @since    1.6
	 */
	public function getItem($pk = null)
	{
		$result = parent::getItem($pk);

		$result->tags = new JHelperTags;
		$result->tags->getTagIds($result->id, 'com_users.user');

		// Get the dispatcher and load the content plugins.
		$dispatcher = JEventDispatcher::getInstance();
		JPluginHelper::importPlugin('content');

		// Load the user plugins for backward compatibility (v3.3.3 and earlier).
		JPluginHelper::importPlugin('user');

		// Trigger the data preparation event.
		$dispatcher->trigger('onContentPrepareData', array('com_users.user', $result));

		return $result;
	}
	
	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      An optional array of data for the form to interogate.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  mixed  A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		JForm::addFormPath(JPATH_USERS_ADMIN . '/models/forms');
		JForm::addFieldPath(JPATH_USERS_ADMIN . '/models/fields');
		
		$plugin = JPluginHelper::getPlugin('user', 'joomla');
		$pluginParams = new Registry($plugin->params);

		// Get the form.
		$form = $this->loadForm('com_users.user', 'user', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		// Passwords fields are required when mail to user is set to No in joomla user plugin
		$userId = $form->getValue('id');

		if ($userId === 0 && $pluginParams->get('mail_to_user') === "0")
		{
			$form->setFieldAttribute('password', 'required', 'true');
			$form->setFieldAttribute('password2', 'required', 'true');
		}

		// If the user needs to change their password, mark the password fields as required
		if (JFactory::getUser()->requireReset)
		{
			$form->setFieldAttribute('password', 'required', 'true');
			$form->setFieldAttribute('password2', 'required', 'true');
		}

		// When multilanguage is set, a user's default site language should also be a Content Language
		if (JLanguageMultilang::isEnabled())
		{
			$form->setFieldAttribute('language', 'type', 'frontend_language', 'params');
		}

		// The user should not be able to set the requireReset value on their own account
		if ((int) $userId === (int) JFactory::getUser()->id)
		{
			$form->removeField('requireReset');
		}

		return $form;
	}
	
	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_vpadvanceduser.edit.user.data', array());

		if (empty($data))
		{
			$data = $this->getItem();
		}

		JPluginHelper::importPlugin('user');

		$this->preprocessData('com_users.profile', $data);

		return $data;
	}
	
	/**
	 * Override JModelAdmin::preprocessForm to ensure the correct plugin group is loaded.
	 *
	 * @param   JForm   $form   A JForm object.
	 * @param   mixed   $data   The data expected for the form.
	 * @param   string  $group  The name of the plugin group to import (defaults to "content").
	 *
	 * @return  void
	 *
	 * @since   1.6
	 * @throws  Exception if there is an error in the form event.
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'user')
	{
		parent::preprocessForm($form, $data, $group);
	}
	
	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.6
	 */
	public function save($data)
	{
		$user_id  = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('user.id');
		$isNew    = ($user_id > 0) ? false : true;
		$sendMail = false;

		// Try to save the user
		$result = parent::save($data);
		
		if($isNew && $result === true)
		{
			$user_id = (int) $this->getState('user.id');
			
			if($user_id > 0)
			{
				// If Joomla user plugin is enabled
				if(JPluginHelper::isEnabled('user', 'joomla'))
				{
					// Get core Joomla user plugin
					$joomla_plugin = JPluginHelper::getPlugin('user', 'joomla');
					
					$registry = new Registry;
					$registry->loadString($joomla_plugin->params);
					$joomla_plugin->params = $registry;
					
					// We will shoot the mail only if mailing option is disabled in core Joomla user plugin
					// to avoid duplicate emails.
					if(!$joomla_plugin->params->get('mail_to_user'))
					{
						$sendMail = true;
					}
				}
				else
				{
					$sendMail = true;
				}
			}
		}
		
		if($sendMail)
		{
			// Get the user object
			$user = JUser::getInstance($user_id);
			
			// Retrive clear password
			$user->password_clear = JArrayHelper::getValue($data, 'password', '', 'string');

			// Get mailer helper instance
			$mailer = VPAdvancedUserHelperMailer::getInstance();
			
			// Try to send registration mail
			if(!$mailer->sendRegistrationMail($user, 0, true))
			{
				// Show the error as a warning.
				// We can not return false as the user is already saved.
				JFactory::getApplication()->enqueueMessage($mailer->getError(), 'warning');
			}
		}
		
		return $result;
	}

	/**
	 * Method to resend activation emails.
	 *
	 * @param   array  &$pks  The ids of the users to whom emails to be sent.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.6
	 */
	public function resend(&$pks)
	{
		if(!JFactory::getUser()->authorise('core.edit.state', 'com_users'))
		{
			JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));
		}

		// Get mailer helper instance
		$mailer = VPAdvancedUserHelperMailer::getInstance();
		$pks    = (array) $pks;

		// Access checks.
		foreach ($pks as $i => $pk)
		{
			// Get the user object
			$user = JUser::getInstance($pk);
			
			if($user->id > 0)
			{
				if (!$user->block || empty($user->activation))
				{
					// Ignore activated accounts.
					unset($pks[$i]);
					continue;
				}

				// Try to resend registration mail
				if(!$mailer->sendRegistrationMail($user, null, false))
				{
					$this->setError($mailer->getError());
					return false;
				}
			}
			else
			{
				unset($pks[$i]);
			}
		}

		return true;
	}

}
