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

/**
 * User json controller class.
 *
 * @since  1.0
 */
class VPAdvancedUserControllerUser extends JControllerForm
{
	public function uploadAvatar()
	{
		// Check for request forgeries.
		JSession::checkToken('request') or $this->returnFalse(JText::_('JINVALID_TOKEN'));
		
		$formData        = $this->input->post->get('jform', array(), 'ARRAY');
		$user_id         = (int) (isset($formData['id']) ? $formData['id'] : 0);
		$data            = isset($formData['vpadvanceduserdata']) ? $formData['vpadvanceduserdata'] : array();
		$files           = $this->input->files->get('vpaufiles', '', 'ARRAY');
		$profile_picture = isset($files['profile_picture']) ? $files['profile_picture'] : '';
		
		if(empty($user_id))
		{
			$this->returnFalse(JText::_('COM_VPADVANCEDUSER_ERROR_USER_NOT_REGISTERED'));
		}
		
		if(!isset($data['profile_picture']))
		{
			$this->returnFalse(JText::_('COM_VPADVANCEDUSER_ERROR_INVALID_REQUEST'));
		}
		
		if(empty($profile_picture) || empty($profile_picture['name']))
		{
			$this->returnFalse(JText::_('COM_VPADVANCEDUSER_ERROR_NO_FILES_TO_UPLOAD'));
		}
		
		// Get the instance of Avatar helper
		$avatarHelper = VPAdvancedUserHelperAvatar::getInstance(array('user_id' => $user_id));
		
		// Set the present file
		$avatarHelper->setPresentFile($data['profile_picture']);
		
		// Validate file
		if(!$avatarHelper->validate($profile_picture))
		{
			$this->returnFalse($avatarHelper->getError());
		}
		
		// Try to upload the file
		$result = $avatarHelper->upload();
		
		if(!$result)
		{
			$this->returnFalse($avatarHelper->getError());
		}
		
		// Get the full url of the image uploaded
		$url = $avatarHelper->getUrl($result, true);
		
		$this->returnTrue(JText::_('COM_VPADVANCEDUSER_AVATAR_UPLOADED'), array('profile_picture' => $result, 'url' => $url));
	}
	
	public function getRedirects()
	{
		$model = $this->getModel('Authenticate');
		
		$result = $model->getRedirectUri();
		
		if($result === false)
		{
			$this->returnFalse($model->getError());
		}
		
		$this->returnTrue('List of URIs', array('data' =>$result));
	}
	
	protected function returnTrue($message = '', $details = array())
	{
		$details = (array) $details;
		$output  = array();
		$output['result'] = true;
		$output['message'] = '';
		
		if(!empty($message))
		{
			$output['message'] = $message;
		}
		
		if(count($details))
		{
			$output = array_merge($output, $details);
		}
		
		return $this->response($output);
	}
	
	protected function returnFalse($message = '', $details = array())
	{
		$details = (array) $details;
		$output  = array();
		$output['result'] = false;
		$output['message'] = '';
		
		if(!empty($message))
		{
			$output['message'] = $message;
		}
		
		if(count($details))
		{
			$output = array_merge($output, $details);
		}
		
		return $this->response($output);
	}

	protected function response($output = array()) 
	{
		$app     = JFactory::getApplication();
		$obLevel = ob_get_level();
		
		if($obLevel)
		{
			while($obLevel > 0)
			{
				ob_end_clean();
				$obLevel --;
			}
		}
		elseif(ob_get_contents())
		{
			@ob_clean();
		}
		
		header('Content-type: application/json');
		header('Cache-Control: public,max-age=1,must-revalidate');
		header('Expires: ' . gmdate('D, d M Y H:i:s', ($_SERVER['REQUEST_TIME'] + 1)) . ' GMT');
		header('Last-modified: ' . gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME']) . ' GMT');
			
		if(function_exists('header_remove')) 
		{
			header_remove('Pragma');
		}
		
		$response = new Registry;
		$response->loadArray($output);
		
		echo (string) $response;
		
		flush();
		$app->close();
	}

	/**
	 * Proxy for getModel.
	 *
	 * @param   string  $name    Optional. Model name
	 * @param   string  $prefix  Optional. Class prefix
	 * @param   array   $config  Optional. Configuration array for model
	 *
	 * @return  object The Model
	 *
	 * @since    1.6
	 */
	public function getModel($name = 'user', $prefix = 'VPAdvancedUserModel', $config = array('ignore_request' => true))
	{
		JModelLegacy::addIncludePath(JPATH_ADVANCEDUSER_SITE . '/models');
		
		return parent::getModel($name, $prefix, $config);
	}
}
