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

JLoader::register('UsersModelUsers', JPATH_USERS_ADMIN . '/models/users.php');

/**
 * Methods supporting a list of VPAdvancedUser records.
 *
 * @since  1.0
 */
class VPAdvancedUserModelUsers extends UsersModelUsers
{
	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   Elements order
	 * @param   string  $direction  Order direction
	 *
	 * @return void
	 *
	 * @throws Exception
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		// Initialise variables.
		$app = JFactory::getApplication('administrator');

		// List state information.
		parent::populateState('a.name', 'asc');
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return   string A store id.
	 *
	 * @since    1.6
	 */
	protected function getStoreId($id = '')
	{
		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return   JDatabaseQuery
	 *
	 * @since    1.6
	 */
	protected function getListQuery()
	{
		return parent::getListQuery();
	}

	/**
	 * Get an array of data items
	 *
	 * @return mixed Array of data items on success, false on failure.
	 */
	public function getItems()
	{
		$items = parent::getItems();
		
		if(!empty($items))
		{
			foreach($items as &$item)
			{
				$item->linked_accounts = $this->getLinkedAccounts($item->id);
			}
		}

		return $items;
	}
	
	public function getProfilePicture($user_id)
	{
		if(!isset($this->cache['user.profile_picture.' . $user_id]))
		{
			$db    = $this->getDbo();
			$query = $db->getQuery(true);
			$query->select($db->quoteName('data_value'))
			      ->from($db->quoteName('#__vpadvanceduser_data'))
			      ->where($db->quoteName('user_id') . ' = ' . (int) $user_id)
			      ->where($db->quoteName('data_key') . ' = ' . $db->quote('data.profile_picture'));

			$db->setQuery($query);
			$result = $db->loadResult();
			
			$this->cache['user.profile_picture.' . $user_id] = !empty($result) ? $result : false;
		}
		
		return $this->cache['user.profile_picture.' . $user_id];
	}
	
	public function getHasAvatarField()
	{
		if(!isset($this->cache['hasProfilePictureField']))
		{
			$db    = $this->getDbo();
			$query = $db->getQuery(true);
			$query->select($db->quoteName('name'))
			      ->select($db->quoteName('state'))
			      ->from($db->quoteName('#__vpadvanceduser_fields'))
			      ->where($db->quoteName('name') . ' = ' . $db->quote('profile_picture'))
			      ->where($db->quoteName('type') . ' = ' . $db->quote('avatar'));

			$db->setQuery($query);
			$result = $db->loadObject();
			
			$this->cache['hasProfilePictureField'] = !empty($result) ? ($result->state == 1) :  false;
		}
		
		return $this->cache['hasProfilePictureField'];
	}
	
	protected function getLinkedAccounts($user_id)
	{
		if(!isset($this->cache['linkedAccounts']))
		{
			$this->cache['linkedAccounts'] = array();
		}
		
		if(!isset($this->cache['linkedAccounts'][$user_id]))
		{
			$db    = $this->getDbo();
			$query = $db->getQuery(true);
			$query->select($db->quoteName('provider'))
			      ->from($db->quoteName('#__vpadvanceduser_users'))
			      ->where($db->quoteName('user_id') . ' = ' . (int) $user_id);

			$db->setQuery($query);
			$accounts = $db->loadColumn();
			
			if(!empty($accounts))
			{
				// Register frontend helper
				JLoader::register('VPAdvancedUserFrontendHelper', JPATH_ADVANCEDUSER_SITE . '/helpers/vpadvanceduser.php');
				
				$valid_providers = VPAdvancedUserFrontendHelper::getProviders();
				$valid_providers = !is_array($valid_providers) ? array() : $valid_providers;
				
				foreach($accounts as $key => &$provider)
				{
					if(!isset($valid_providers[$provider]))
					{
						unset($accounts[$key]);
					}
					else
					{
						$accounts[$key] = $valid_providers[$provider];
					}
				}
			}
			
			$this->cache['linkedAccounts'][$user_id] = !empty($accounts) ? $accounts :  array();
		}
		
		return $this->cache['linkedAccounts'][$user_id];
	}
}
