<?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('VPAdvancedUserController', JPATH_COMPONENT . '/controller.php');

/**
 * User JSON controller class.
 */
class VPAdvancedUserControllerUser extends VPAdvancedUserController
{
	public function checkUsername()
	{
		// Check for request forgeries.
		$this->_checkToken();

		// If registration is disabled - Redirect to login page.
		if (JComponentHelper::getParams('com_users')->get('allowUserRegistration') == 0)
		{
			return $this->returnFalse();
		}

		$model    = $this->getModel('Registration', 'VPAdvancedUserModel');
		$username = $this->input->post->get('uname', '', 'USERNAME');
		
		if(!$model->checkUsername($username))
		{
			return $this->returnFalse($model->getError(), array('uname' => $username));
		}
		
		$this->returnTrue('', array('uname' => $username));
	}
	
	public function checkEmail()
	{
		// Check for request forgeries.
		$this->_checkToken();

		// If registration is disabled - Redirect to login page.
		if (JComponentHelper::getParams('com_users')->get('allowUserRegistration') == 0)
		{
			return $this->returnFalse();
		}

		$model = $this->getModel('Registration', 'VPAdvancedUserModel');
		$email = $this->input->post->get('email', '', 'STRING');
		
		if(!$model->checkEmail($email))
		{
			return $this->returnFalse($model->getError(), array('email' => $email));
		}
		
		$this->returnTrue('', array('email' => $email));
	}
	
	public function uploadAvatar()
	{
		// Check for request forgeries.
		$this->_checkToken('request');
		
		$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 saveCustomFields()
	{
		$model = $this->getModel('Registration', 'VPAdvancedUserModel');
		$rData = $this->input->post->get('jform', array(), 'array');
		
		$form = $model->getAcceptanceForm();
		
		if(!$form)
		{
			$this->returnFalse($model->getError());
		}
		
		if(isset($rData['privacyconsent']) && isset($rData['privacyconsent']['privacy']))
		{
			$privacyField = $form->getField('privacy', 'privacyconsent');
			
			if(!empty($privacyField) && ($privacyField->getAttribute('required') == 'true' || $privacyField->getAttribute('required') == 'required' || $privacyField->getAttribute('required') == '1'))
			{
				if(empty($rData['privacyconsent']['privacy']))
				{
					JFactory::getLanguage()->load('plg_system_PRIVACYCONSENT');
					
					$this->returnFalse(JText::_('PLG_SYSTEM_PRIVACYCONSENT_FIELD_ERROR'));
				}
			}
		}
		
		$data = $model->validate($form, $rData);

		// Check for validation errors.
		if ($data === false)
		{
			// Get the validation messages.
			$errors = $model->getErrors();
			$errorMessages = array();

			// Push up to three validation messages out to the user.
			for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++)
			{
				if ($errors[$i] instanceof Exception)
				{
					$errorMessages[] = $errors[$i]->getMessage();
				}
				else
				{
					$errorMessages[] = $errors[$i];
				}
			}

			$this->returnFalse(implode('<br/>', $errorMessages));
		}
		
		JFactory::getApplication()->setUserState('com_vpdvanceduser.sociallogin.customdata', $data);
		
		$this->returnTrue('');
	}
	
	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 VPAdvancedUserHelperUtility::jsonResponse($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 VPAdvancedUserHelperUtility::jsonResponse($output);
	}
}
