<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
class User_IndexController extends Core_Controller_Action_Standard
{
  public function indexAction()
  {

  }

  public function homeAction()
  {
    // check public settings
    $require_check = Engine_Api::_()->getApi('settings', 'core')->getSetting('core.general.portal', 1);
		$user_front = Zend_Registry::isRegistered('user_front') ? Zend_Registry::get('user_front') : null;
    if(!$require_check){
      if( !$this->_helper->requireUser()->isValid() ) return;
    }
    
    if( !Engine_Api::_()->user()->getViewer()->getIdentity() ) {
      return $this->_helper->redirector->gotoRoute(array(), 'default', true);
    }

    // Render
		if(!empty($user_front)) {
    	$this->_helper->content->setNoRender()->setEnabled();
		}
  }

  public function browseAction()
  {
    $require_check = Engine_Api::_()->getApi('settings', 'core')->getSetting('core.general.portal', 1);
    if(!$require_check){
      if( !$this->_helper->requireUser()->isValid() ) return;
    }
    if( !$this->_executeSearch() ) {
      // throw new Exception('error');
    }

    $this->view->isAjaxSearch = $this->_getParam('ajax');

    if ($this->view->isAjaxSearch) {
      $this->renderScript('_browseUsers.tpl');
    }

    if( !$this->view->isAjaxSearch ) {
      // Render
      $this->_helper->content
          ->setEnabled()
          ;
    }
  }

  protected function _executeSearch()
  {
    // Check form
    $form = new User_Form_Search(array(
      'type' => 'user'
    ));

    if (!$form->isValid($this->_getAllParams())) {
      $this->view->error = true;
      $this->view->totalUsers = 0; 
      $this->view->userCount = 0; 
      $this->view->page = 1;
      return false;
    }

    $this->view->form = $form;

    // Get search params
    $page = (int)  $this->_getParam('page', 1);
    $ajax = (bool) $this->_getParam('ajax', false);
    $options = $form->getValues();
    
    // Process options
    $tmp = array();
    $originalOptions = $options;
    foreach ($options as $k => $v) {
      if (null == $v || '' == $v || (is_array($v) && engine_count(array_filter($v)) == 0)) {
        continue;
      } elseif (false !== strpos($k, '_field_')) {
        list($null, $field) = explode('_field_', $k);
        $tmp['field_' . $field] = $v;
      } elseif (false !== strpos($k, '_alias_')) {
        list($null, $alias) = explode('_alias_', $k);
        $tmp[$alias] = $v;
      } else {
        $tmp[$k] = $v;
      }
    }
    $options = $tmp;

    // Get table info
    $table = Engine_Api::_()->getItemTable('user');
    $userTableName = $table->info('name');

    $searchTable = Engine_Api::_()->fields()->getTable('user', 'search');
    $searchTableName = $searchTable->info('name');

    
    //extract($options); // displayname
    $profile_type = @$options['profile_type'];
    $displayname = @$options['displayname'];
    if (!empty($options['extra'])) {
      extract($options['extra']); // is_online, has_photo, submit
    }

    $viewer = Engine_Api::_()->user()->getViewer();
    $viewerId = $viewer->getIdentity();
    $excludedLevels = array(1, 2, 3);
    $allBlockedUsers = array();

    if( $viewerId ) {
      $blockTable = Engine_Api::_()->getDbtable('block', 'user');
      $blockedSelect = $blockTable->select()
        ->from('engine4_user_block', 'blocked_user_id')
        ->where('user_id = ?', $viewerId);
      $blockedUsers = $blockTable->fetchAll($blockedSelect)->toArray();

      foreach( $blockedUsers as $blockedUser ) {
        array_push($allBlockedUsers, $blockedUser['blocked_user_id']);
      }
      $this->view->blockedUserIds = $allBlockedUsers;

      if( !engine_in_array($viewer->level_id, $excludedLevels) ) {
        $blockedBySelect = $blockTable->select()
          ->from('engine4_user_block', 'user_id')
          ->where('blocked_user_id = ?', $viewerId);
        $blockedByUsers = $blockTable->fetchAll($blockedBySelect)->toArray();

        foreach( $blockedByUsers as $blockedByUser ) {
          array_push($allBlockedUsers, $blockedByUser['user_id']);
        }
      } else {

        unset($allBlockedUsers);
      }
    }

    // Contruct query
    $select = $table->select()
      ->setIntegrityCheck(false)
      ->from($userTableName)
      ->joinLeft($searchTableName, "`{$searchTableName}`.`item_id` = `{$userTableName}`.`user_id`", null)
      //->group("{$userTableName}.user_id")
      ->where("{$userTableName}.search = ?", 1)
      ->where("{$userTableName}.enabled = ?", 1);
      
    //Location search
    $primaryId = current($table->info("primary"));
    
    $tableLocationName = Engine_Api::_()->getDbtable('locations', 'core')->info('name');
    $location = $this->_getParam('location', '');
    $lat = $this->_getParam('lat', '');
    $lng = $this->_getParam('lng', '');
    $miles = $this->_getParam('miles', 50);
    
    $enablesigupfields = (array) json_decode(Engine_Api::_()->getApi('settings', 'core')->getSetting('user.signup.enablesigupfields', '["confirmpassword","dob","gender","profiletype","timezone","language","location"]'));
    
    //Location Based search
    if(Engine_Api::_()->getApi('settings', 'core')->getSetting('enableglocation', 0) && isset($enablesigupfields) && engine_in_array('location', $enablesigupfields)) {

      if(Engine_Api::_()->getApi('settings', 'core')->getSetting('enableglocation', 0) == 2 && !empty($location)) {
        $select->where($userTableName . '.location LIKE ?', $location . '%');
      } else if(Engine_Api::_()->getApi('settings', 'core')->getSetting('enableglocation', 0) == 1) {

        if(empty($lat) && empty($lng) && !empty($_COOKIE['location_data'])) {
          $location = $_COOKIE['location_data'];
          $lat = $_COOKIE['location_lat'];
          $lng = $_COOKIE['location_lng'];
          $miles = 50;
        }

        if(!empty($lat) && !empty($lng) && !empty($location) && $lat != 'undefined') {

          //This is the maximum distance (in miles) away from $origLat, $origLon in which to search
          $dist = !empty($miles) ? $miles : 50;

          $searchType = !empty(Engine_Api::_()->getApi('settings', 'core')->getSetting('core.search.type', 1)) ? 3956 : 6371;

          $origLat = $lat;
          $origLon = $lng;

          $asinSort = array('lat', 'lng', 'distance' => new Zend_Db_Expr(($searchType . " * 2 * ASIN(SQRT( POWER(SIN(($origLat - abs(lat))*pi()/180/2),2) + COS($origLat*pi()/180 )*COS(abs(lat)*pi()/180) *POWER(SIN(($origLon-lng)*pi()/180/2),2)))")));
          $select->joinLeft($tableLocationName, $tableLocationName . '.resource_id = ' . $userTableName . '.'.$primaryId .' AND ' . $tableLocationName . '.resource_type = "user" ', $asinSort);
          $select->where($tableLocationName . ".lng between ($origLon-$dist/abs(cos(radians($origLat))*69)) and ($origLon+$dist/abs(cos(radians($origLat))*69)) and " . $tableLocationName . ".lat between ($origLat-($dist/69)) and ($origLat+($dist/69))");
          $select->order('distance');
          $select->having("distance < $dist");
        } else {
					$select->joinLeft($tableLocationName, $tableLocationName . '.resource_id = ' . $userTableName . '.'.$primaryId .' AND ' . $tableLocationName . '.resource_type = "user" ', array('lat', 'lng'));
				}
      }
    }
    
    if( !empty($allBlockedUsers) ) {
      $select->where("user_id NOT IN (?)", $allBlockedUsers);
    }
    $searchDefault = true;

    // Build the photo and is online part of query
    if (isset($has_photo) && !empty($has_photo)) {
      $select->where($userTableName.'.photo_id != ?', "0");
      $searchDefault = false;
    }

    if (isset($is_online) && !empty($is_online)) {
      $select
        ->joinRight("engine4_user_online", "engine4_user_online.user_id = `{$userTableName}`.user_id", null)
        ->group("engine4_user_online.user_id")
        ->where($userTableName.'.user_id != ?', "0");
      $searchDefault = false;
    }

    // Add displayname
    if (!empty($displayname)) {
      $select->where("(`{$userTableName}`.`username` LIKE ? || `{$userTableName}`.`displayname` LIKE ?)", "%{$displayname}%");
      $searchDefault = false;
    }
    
    // Build search part of query
    $searchParts = Engine_Api::_()->fields()->getSearchQuery('user', $options);
    foreach ($searchParts as $k => $v) {
      if (strpos($k, 'FIND_IN_SET') !== false) {
        $select->where("{$k}", $v);
        continue;
      }

      $select->where("`{$searchTableName}`.{$k}", $v);

      if (isset($v) && $v != "") {
        $searchDefault = false;
      }
    }

    $orderby = $this->getParam('orderby');
    $orderbyOptions = array('member_count', 'creation_date');

    if (!empty($orderby) && engine_in_array($orderby, $orderbyOptions)) {
      $select->order($orderby . " DESC");
    } elseif ($searchDefault) {
      $select->order("{$userTableName}.lastlogin_date DESC");
    } else {
      $select->order("{$userTableName}.displayname ASC");
    }

    // Build paginator
    $paginator = Zend_Paginator::factory($select);
    $paginator->setItemCountPerPage(12);
    $paginator->setCurrentPageNumber($page);
    
    $this->view->page = $page;
    $this->view->ajax = $ajax;
    $this->view->users = $paginator;
    $this->view->totalUsers = $paginator->getTotalItemCount();
    $this->view->userCount = $paginator->getCurrentItemCount();
    $this->view->topLevelId = $form->getTopLevelId();
    $this->view->topLevelValue = $form->getTopLevelValue();
    $this->view->formValues = array_filter($originalOptions);

    return true;
  }

  public function getusersAction() {
    
    $extraParamsObj = $this->_getParam('extraParamsObj', null);
    
    $type = $this->_getParam('type', null);
    $data = array();
    $users_table = Engine_Api::_()->getDbtable('users', 'user');
    $select = $users_table->select()
                    ->where('displayname LIKE ? ', $this->_getParam('text') . '%');
    if(!empty($type) && $type == 'phone') {
      $select->where('phone_number <> ?', '');
    }

    if(!empty($type) && $type == 'phonenumber') {
      $select->where('phone_number <> ?', '');
    }
    
    if(engine_count($extraParamsObj) > 0) {
      if(!empty($extraParamsObj['memberlevel'])) {
        $select->where('level_id =?', $extraParamsObj['memberlevel']);
      }
    }
    $select->order('displayname ASC')->limit('40');

    $users = $users_table->fetchAll($select);

    foreach ($users as $user) {
      $user_icon_photo = $this->view->itemPhoto($user, 'thumb.icon');
      if(!empty($type) && $type == 'phonenumber') {
        $data[] = array(
          'id' => $user->user_id,
          'label' => $user->getTitle(false)  . ' - (+'.$user->country_code.'-' . $user->phone_number .')',
          'photo' => $user_icon_photo
        );
      } else {
        $data[] = array(
            'id' => $user->user_id,
            'label' => $user->getTitle(false),
            'photo' => $user_icon_photo
        );
      }
    }
    return $this->_helper->json($data);
  }

  public function resendEmailAction() {
    
    $token = $this->_getParam('token');
    $userId = Engine_Api::_()->user()->getUserIdFromToken($token);

    $userTable = Engine_Api::_()->getDbtable('users', 'user');
    $user = $userTable->fetchRow($userTable->select()->where('user_id = ?', $userId));

    $verify_table = Engine_Api::_()->getDbtable('verify', 'user');

    try {
      // verify email resend
      $select = $verify_table->select();$select->where('user_id = ?', $user->user_id)->limit(1);
      $verifyRow = $verify_table->fetchRow($select);
      if(isset($verifyRow))
        $verifyRow->delete();
      $verify_row = $verify_table->createRow();
      $verify_row->user_id = $user->getIdentity();
      $verify_row->code = md5($user->email
        . $user->creation_date
        . Engine_Api::_()->getApi('settings', 'core')->getSetting('core.secret', 'staticSalt')
        . (string) rand(1000000, 9999999));
      $verify_row->date = $user->creation_date;
      $verify_row->save();

      $mailParams = array(
        'host' => $_SERVER['HTTP_HOST'],
        'email' => $user->email,
        'date' => time(),
        'recipient_title' => $user->getTitle(),
        'recipient_link' => $user->getHref(),
        'recipient_photo' => $user->getPhotoUrl('thumb.icon'),
        'queue' => false,
      );

      $mailParams['object_link'] = Zend_Controller_Front::getInstance()->getRouter()->assemble(array(
        'action' => 'verify',
        'token' => Engine_Api::_()->user()->getVerifyToken($user->getIdentity()),
        'verify' => $verify_row->code
      ), 'user_signup', true);

      Engine_Api::_()->getApi('mail', 'core')->sendSystem(
        $user,
        'core_verification',
        $mailParams
      );
    } catch( Exception $e ) {
      throw $e;
    }

    $base_url = ( _ENGINE_SSL ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . Zend_Registry::get('Zend_View')->baseUrl();
    header("Location: ".$base_url);
  }

	public function addLocationAction() {

		$this->view->is_ajax = $is_ajax = $this->_getParam('is_ajax', 0);

		$user = Engine_Api::_()->user()->getViewer();
    $this->view->viewer_id = $viewer_id = $user->getIdentity();
		
		if(!$is_ajax) {
			$this->view->form = $form = new User_Form_Location();
		}

		$this->view->locationLatLng = $locationLatLng = Engine_Api::_()->getDbtable('locations', 'core')->getLocationData(array('resource_type' => $user->getType(), 'resource_id' =>  $user->getIdentity()));

		if ($locationLatLng && $user->location) {
			$form->populate(array('user_location' => $user->location,
				'user_lat' => $locationLatLng['lat'],
				'user_lng' => $locationLatLng['lng'],
				'user_zip' => $locationLatLng['zip'],
				'user_city' => $locationLatLng['city'],
				'user_state' => $locationLatLng['state'],
				'user_country' => $locationLatLng['country']));
			$form->setTitle('Edit Location');
			$form->submit->setLabel('Update Location');
		}

		if($is_ajax) {
			if ($this->getRequest()->getPost()) {
				$user->location = $_POST['user_location'];
				$user->save();

				if (isset($_POST['user_lat']) && isset($_POST['user_lng']) && $_POST['user_lat'] != '' && $_POST['user_lng'] != '' && !empty($_POST['user_location'])) {
					
					Engine_Db_Table::getDefaultAdapter()->query('INSERT INTO engine4_core_locations (resource_id, lat, lng ,city,state,zip,country, resource_type) VALUES ("' . $user->user_id . '", "' . $_POST['user_lat'] . '","' . $_POST['user_lng'] . '","' . $_POST['user_city'] . '","' . $_POST['user_state'] . '","' . $_POST['user_zip'] . '","' . $_POST['user_country'] . '",  "user")	ON DUPLICATE KEY UPDATE	lat = "' . $_POST['user_lat'] . '" , lng = "' . $_POST['user_lng'] . '",city = "' . $_POST['user_city'] . '", state = "' . $_POST['user_state'] . '", country = "' . $_POST['user_country'] . '", zip = "' . $_POST['user_zip'] . '"');

					echo Zend_Json::encode(array('status' => 1, 'message' => Zend_Registry::get('Zend_Translate')->_('Location has been added successfully.'), 'url' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action' => 'edit-location', 'id' => $user->getIdentity()), 'user_general', true)));
					exit();
				} else {

					Engine_Api::_()->getItemTable('core_location')->delete(array(
						'resource_id = ?' => $user->getIdentity(),
						'resource_type' => 'user'
					));

					echo Zend_Json::encode(array('status' => 1, 'message' => Zend_Registry::get('Zend_Translate')->_('Location has been added successfully.'), 'url' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action' => 'edit-location', 'id' => $user->getIdentity()), 'user_general', true)));
					exit();
				}
			}
		}
	}

	public function editLocationAction() {

		if (!$this->_helper->requireUser()->isValid())
			return;

		$this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();

		if (!Engine_Api::_()->core()->hasSubject()) {
			// Can specifiy custom id
			$id = $this->_getParam('id', null);
			$subject = null;
			if (null === $id) {
				$subject = Engine_Api::_()->user()->getViewer();
				Engine_Api::_()->core()->setSubject($subject);
			} else {
				$subject = Engine_Api::_()->getItem('user', $id);
				Engine_Api::_()->core()->setSubject($subject);
			}
		}

		if ($id) {
			$params = array('id' => $id);
		} else {
			$params = array();
		}

		$this->view->user = $user = Engine_Api::_()->getItem('user', $subject->getIdentity());

		$userLocation = $user->location;
		if (!$userLocation)
			return $this->_forward('notfound', 'error', 'core');

		$this->view->locationLatLng = $locationLatLng = Engine_Api::_()->getDbtable('locations', 'core')->getLocationData(array('resource_type' => $user->getType(), 'resource_id' =>  $user->getIdentity()));
		if (!$locationLatLng) {
			return $this->_forward('notfound', 'error', 'core');
		}

		$this->view->form = $form = new User_Form_Location();
		$form->populate(array(
			'user_edit_location' => $userLocation,
			'user_lat' => $locationLatLng['lat'],
			'user_lng' => $locationLatLng['lng'],
			'user_zip' => $locationLatLng['zip'],
			'user_city' => $locationLatLng['city'],
			'user_state' => $locationLatLng['state'],
			'user_country' => $locationLatLng['country'],
		));

		// Check if post
		if( !$this->getRequest()->isPost() ) {
			$this->view->status = false;
			$this->view->error = Zend_Registry::get('Zend_Translate')->_('Not post');
			return;
		}

		if( !$form->isValid($this->getRequest()->getPost()) ) {
			$this->view->status = false;
			$this->view->error =  Zend_Registry::get('Zend_Translate')->_('Invalid data');
			return;
		}

		if ($this->getRequest()->getPost()) {
			$user->location = $_POST['user_edit_location'];
			$user->save();

			if (isset($_POST['user_lat']) && isset($_POST['user_lng']) && $_POST['user_lat'] != '' && $_POST['user_lng'] != '' && !empty($_POST['user_edit_location'])) {
				Engine_Db_Table::getDefaultAdapter()->query('INSERT INTO engine4_core_locations (resource_id, lat, lng ,city,state,zip,country, resource_type) VALUES ("' . $user->user_id . '", "' . $_POST['user_lat'] . '","' . $_POST['user_lng'] . '","' . $_POST['user_city'] . '","' . $_POST['user_state'] . '","' . $_POST['user_zip'] . '","' . $_POST['user_country'] . '",  "user")	ON DUPLICATE KEY UPDATE	lat = "' . $_POST['user_lat'] . '" , lng = "' . $_POST['user_lng'] . '",city = "' . $_POST['user_city'] . '", state = "' . $_POST['user_state'] . '", country = "' . $_POST['user_country'] . '", zip = "' . $_POST['user_zip'] . '"');
			}
			return $this->_helper->redirector->gotoRoute(array());
		}
	}
}
