<?php
/**
 * @package    JBusinessDirectory
 *
 * @author CMSJunkie http://www.cmsjunkie.com
 * @copyright  Copyright (C) 2007 - 2021 CMSJunkie. All rights reserved.
 * @license   https://www.gnu.org/licenses/agpl-3.0.en.html
 */
defined('_JEXEC') or die('Restricted access');

class JBusinessDirectoryControllerBusinessUser extends JControllerLegacy {
	public function __construct() {
		parent::__construct();
		$this->appSettings = JBusinessUtil::getApplicationSettings();
	}

	public function checkUser() {
		$user = JBusinessUtil::getUser();
		$filterParam = "";
		$filter_package     = JFactory::getApplication()->input->getInt("filter_package");
		$packageType        = JFactory::getApplication()->input->getInt("packageType",0);
		$claimListingId     = JFactory::getApplication()->input->getInt("claim_listing_id");
		$serviceType        = JFactory::getApplication()->input->getInt("serviceType");
		$orderId        = JFactory::getApplication()->input->getInt("orderId");

		if (!empty($filter_package)) {			
			$filterParam .="&filter_package=".$filter_package;
		}

		if (!empty($claimListingId)) {
			$filterParam .="&claim_listing_id=".$claimListingId;
		}

		if (!empty($serviceType)) {
			$filterParam .="&serviceType=".$serviceType;
		}

		if ($user->id == 0 && ($this->appSettings->allow_user_creation==0 || $packageType == PACKAGE_TYPE_USER || !empty($serviceType) || !empty($claimListingId))) {
			$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=businessuser'.$filterParam, false));
		}elseif(!empty($orderId)){
			$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&task=billingdetails.checkBillingDetails&orderId='.$orderId, false));
		} else {
			if (!empty($claimListingId)) {
				$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=claimlisting'.$filterParam, false));
			}else if(!empty($filter_package) && empty($claimListingId)){
				if($packageType == PACKAGE_TYPE_USER) {
					$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&task=billingdetails.checkBillingDetails'.$filterParam, false));
				} else {
					$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=managecompany&showSteps=true&layout=edit'.$filterParam, false));
				}
			} elseif (!empty($serviceType)) {
				$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view='.$serviceType.'&layout=edit', false));
			} 
		}

		return;
	}
	
	public function loginUser() {
		$this->checkToken('post');

		$app    = JFactory::getApplication();
		$input  = $app->input;
		$method = $input->getMethod();

		$filterParam = "";
		$filter_package = $input->get("filter_package");
		$packageType = $input->get("packageType");
		$claimListingId = $input->get("claim_listing_id");
		$serviceType = $input->get("serviceType");
		$orderId = $app->getUserState("user.order_id");
		$companyId = $app->getUserState("user.company_id");



		if (!empty($filter_package)) {
			$filterParam .="&filter_package=".$filter_package;
		}

		if (!empty($claimListingId)) {
			$filterParam .="&claim_listing_id=".$claimListingId;
		}

		if (!empty($serviceType)) {
			$filterParam .="&serviceType=".$serviceType;
		}

		if (!empty($orderId)) {
			$filterParam .="&orderId=".$orderId;
		}
		

		// Populate the data array:
		$credentials = array();
		$credentials['username']  = $input->$method->get('username', '', 'USERNAME');
		$credentials['password']  = $input->$method->get('password', '', 'RAW');
		$credentials['secretkey'] = $input->$method->get('secretkey', '', 'RAW');
		
		// Perform the log in.
		if (true !== UserService::loginUserWithCredentials($credentials)) {
			// Login failed !
			$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&showOnlyLogin=1&view=businessuser'.$filterParam, false));
			return;
		}
		
		if (!empty($claimListingId)) {
			$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=claimlisting'.$filterParam, false));
		}else if(!empty($filter_package) && empty($claimListingId)){
			if($packageType == PACKAGE_TYPE_USER) {
				$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&task=billingdetails.checkBillingDetails'.$filterParam, false));
			} else {
				$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=managecompany&showSteps=true&layout=edit'.$filterParam, false));
			}		
		} elseif (!empty($serviceType)) {
			$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view='.$serviceType.'&layout=edit', false));
		} elseif (!empty($companyId)) {
			$user = JBusinessUtil::getUser();
			
			if(!empty($companyId )){
				if(JBusinessUtil::updateCompanyUser($companyId, $user->id)){
					$app->setUserState('user.order_id',null);
					$app->setUserState('user.company_id',null);
				}
				if (!empty($orderId)) {
					$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=billingdetails&layout=edit&'.$filterParam, false));
				} else{
					$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=listingconfirmation&listing_id='.$companyId));
				}
			}else{
				$this->setMessage("Could not update listing user", 'warning');
				$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=managecompanies'.$filterParam, false));
			}
		}
	}

	public function addUser() {
		// Check for request forgeries.
		//$this->checkToken();
		
		$app    = JFactory::getApplication();
		$input  = $app->input;
		$method = $input->getMethod();
		
		$filterParam = "";
		$filter_package = $input->get("filter_package");
		$packageType = $input->get("packageType");
		$claimListingId = $input->get("claim_listing_id");
		$serviceType        = $input->get("serviceType");
		$orderId = $app->getUserState("user.order_id");
		$companyId = $app->getUserState("user.company_id");

		if (!empty($filter_package)) {			
			$filterParam .="&filter_package=".$filter_package;
		}
		
		if (!empty($claimListingId)) {
			$filterParam .="&claim_listing_id=".$claimListingId;
		}

		if (!empty($serviceType)) {
			$filterParam .="&serviceType=".$serviceType;
		}

		if (!empty($orderId)) {
			$filterParam .="&orderId=".$orderId;
		}
		
		$appSettings = JBusinessUtil::getApplicationSettings();
		$data = JFactory::getApplication()->input->post->getArray();
		if ($appSettings->captcha) {
			$captchaAnswer = !empty($data['recaptcha_response_field'])?$data['recaptcha_response_field']:$data['g-recaptcha-response'];
			try {
				$namespace="jbusinessdirectory.contact";
				$captcha = JCaptcha::getInstance("recaptcha", array('namespace' => $namespace));
				if (!$captcha->checkAnswer($captchaAnswer)) {
					$error = $captcha->getError();
					$this->setMessage("Captcha error!", 'warning');
					$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=businessuser'.$filterParam, false));
					return;
				}
			} catch (Exception $e) {
				$error = $captcha->getError();
				$this->setMessage("Captcha error!", 'warning');
				$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=businessuser'.$filterParam, false));
				return;
			}
		}
		
		$app   = JFactory::getApplication();
		
		// Attempt to save the data.
		$return = UserService::addJoomlaUser($data);
		
		// Check for errors. 
		// TODO enable check again - for now it is causing some issues
		if ($return === false) {
			
			// Redirect back to the edit screen.
			$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=businessuser'.$filterParam, false));
			
			return false;
		}
				
		// Flush the data from the session.
		$app->setUserState('com_users.registration.data', null);
		
		// Redirect to the profile screen.
		if ($return === 'adminactivate') {
			$this->setMessage(JText::_('COM_USERS_REGISTRATION_COMPLETE_VERIFY'));
			$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&showOnlyLogin=1&view=businessuser'.$filterParam, false));
		} elseif ($return === 'useractivate') {
			$this->setMessage(JText::_('COM_USERS_REGISTRATION_COMPLETE_ACTIVATE'));
			$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&showOnlyLogin=1&view=businessuser'.$filterParam, false));
		} else if(is_numeric($return)) {
			 
			$userId = $return;

			// if the user select the business owner checkbox it will be associated with the business owner usergroup
			$isBusinessOwner = $app->input->get("business_owner");
			if($isBusinessOwner){
				if (!empty($userId)) {
					JUserHelper::addUserToGroup($userId, $this->appSettings->business_usergroup);
				}
			}else{
				//Add default usergroup to the user
				if (!empty($userId)) {
					JUserHelper::addUserToGroup($userId, $this->appSettings->usergroup);
				}
			}

			//check if the profile fields are set for the user - redirect to profile if not
			if(!$isBusinessOwner){

				$userPlugin = JPluginHelper::getPlugin('user', 'jbdprofile');
				if (!empty($userPlugin)) {
					$fields = array(
						'listing-categories',
						'offer-categories',
						'event-categories',
						'conference-categories',
					);
					$params = new JRegistry($userPlugin->params);
					foreach($fields as $field){
						// If fields is required - redirect to profile screen
						if($params->get($field) == 2){
							$this->setRedirect(JRoute::_('index.php?option=com_users&view=profile&layout=edit', false));
							return false;
						}
					}

				}
			}
			
			if (!empty($claimListingId)) {
				$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=claimlisting'.$filterParam, false));
			}else if(!empty($filter_package) && empty($claimListingId)){
				if($packageType == PACKAGE_TYPE_USER) {
					$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&task=billingdetails.checkBillingDetails'.$filterParam, false));
				} else {
					$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=managecompany&showSteps=true&layout=edit'.$filterParam, false));
				}		
			} elseif (!empty($serviceType)) {
				$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view='.$serviceType.'&layout=edit', false));
			} elseif (!empty($companyId)) {
				$user = JBusinessUtil::getUser();
				
				if(!empty($companyId )){
					if(JBusinessUtil::updateCompanyUser($companyId, $user->id)){
						$app->setUserState('user.order_id',null);
						$app->setUserState('user.company_id',null);
					}
					if (!empty($orderId)) {
						$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=billingdetails&layout=edit&'.$filterParam, false));
					} else{
						$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=listingconfirmation&listing_id='.$companyId));
					}
				}else{
					$this->setMessage("Could not update listing user", 'warning');
					$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=managecompanies'.$filterParam, false));
				}
			}
		}
		
		return true;
	}



	/**
	 * Verify the email address
	 *
	 * @return void
	 */
	public function verifyEmail(){

		$model = $this->getModel("businessuser");	
		
		if($model->verifyEmail()){
			$this->setMessage(JText::_('LNG_EMAIL_VERIFIED_SUCCESFULLY'));
		}else{
			$this->setMessage(JText::_('LNG_EMAIL_ACVITATION_CODE_INVALID'));
		}

		$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=useroptions', false));

		return true;
	}

	/**
	 * Resend the verification email
	 *
	 * @return void
	 */
	public function resendVerficationEmail(){
		$model = $this->getModel("businessuser");
		
		if($model->resendVerificationEmail()){ 
			$this->setMessage(JText::_('LNG_EMAIL_VERIFICATION_SENT'));
		}else{
			$this->setMessage(JText::_('LNG_EMAIL_VERIFICATION_NOT_SENT'));
		}

		$this->setRedirect(JRoute::_('index.php?option=com_jbusinessdirectory&view=useroptions', false));

		return true;
	}

	public function checkUserByUsernameAjax(){
		$input  = JFactory::getApplication()->input;
		$username = $input->getString('username');

		$model = $this->getModel("businessuser");
		$result = $model->getUserByUsername($username);
		$response = new stdClass;
		$response->message = '';
		if($result>0){
			$response->status = $result;
			$response->message = JText::_('LNG_USERNAME_ALREADY_EXIST');
		}

		// Send as JSON
		header("Content-Type: application/json", true);
		echo json_encode($response);
		exit;
	}
	
	public function checkUserByEmailAjax(){
		$input  = JFactory::getApplication()->input;
		$email = $input->getString('email');
		
		$model = $this->getModel("businessuser");
		$result = $model->getUserByEmail($email);
		$response = new stdClass;
		$response->message = '';
		if($result>0){
			$response->status = $result;
			$response->message = JText::_('LNG_EMAIL_ALREADY_EXIST');
		}

		// Send as JSON
		header("Content-Type: application/json", true);
		echo json_encode($response);
		exit;
	}
}
