<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
?>
<?php $enableglocation = Engine_Api::_()->getApi('settings', 'core')->getSetting('enableglocation', 0); ?>
<?php //if ($this->isAjaxSearch): ?>
<div class="browse_members_head">
  <h3>
    <?php echo $this->translate(array('%s member found.', '%s members found.', $this->totalUsers),$this->locale()->toNumber($this->totalUsers)) ?>
  </h3>
  <div class="view_type">
    <a class="list active view-switcher" data-view="list" href="javascript:void(0);">
      <i><svg viewBox="0 0 24 24" fill="currentColor"><path d="M7,6H23a1,1,0,0,0,0-2H7A1,1,0,0,0,7,6Z"/><path d="M23,11H7a1,1,0,0,0,0,2H23a1,1,0,0,0,0-2Z"/><path d="M23,18H7a1,1,0,0,0,0,2H23a1,1,0,0,0,0-2Z"/><circle cx="2" cy="5" r="2"/><circle cx="2" cy="12" r="2"/><circle cx="2" cy="19" r="2"/></svg></i>
    </a>
    <a class="grid view-switcher" data-view="grid" href="javascript:void(0);"><i>
      <i><svg viewBox="0 0 24 24" fill="currentColor"><path d="M7,0H4A4,4,0,0,0,0,4V7a4,4,0,0,0,4,4H7a4,4,0,0,0,4-4V4A4,4,0,0,0,7,0ZM9,7A2,2,0,0,1,7,9H4A2,2,0,0,1,2,7V4A2,2,0,0,1,4,2H7A2,2,0,0,1,9,4Z"/><path d="M20,0H17a4,4,0,0,0-4,4V7a4,4,0,0,0,4,4h3a4,4,0,0,0,4-4V4A4,4,0,0,0,20,0Zm2,7a2,2,0,0,1-2,2H17a2,2,0,0,1-2-2V4a2,2,0,0,1,2-2h3a2,2,0,0,1,2,2Z"/><path d="M7,13H4a4,4,0,0,0-4,4v3a4,4,0,0,0,4,4H7a4,4,0,0,0,4-4V17A4,4,0,0,0,7,13Zm2,7a2,2,0,0,1-2,2H4a2,2,0,0,1-2-2V17a2,2,0,0,1,2-2H7a2,2,0,0,1,2,2Z"/><path d="M20,13H17a4,4,0,0,0-4,4v3a4,4,0,0,0,4,4h3a4,4,0,0,0,4-4V17A4,4,0,0,0,20,13Zm2,7a2,2,0,0,1-2,2H17a2,2,0,0,1-2-2V17a2,2,0,0,1,2-2h3a2,2,0,0,1,2,2Z"/></svg></i>
    </i></a>
		<?php if($enableglocation == 1) { ?>
			<a class="map view-switcher" data-view="map" href="javascript:void(0);">
				<i>
					<svg width="30" height="30" viewBox="0 0 30 30" fill="none" xmlns="http://www.w3.org/2000/svg">
						<rect width="30" height="30" rx="3.6" fill="none"/>
						<path d="M17.25 10.5V21.75M17.25 10.5L21.75 8.25V19.5L17.25 21.75M17.25 10.5L12.75 8.25M17.25 21.75L12.75 19.5M12.75 19.5L8.25 21.75V10.5L12.75 8.25M12.75 19.5V8.25" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"/>
					</svg>
				</i>
			</a>
		<?php } ?>
  </div>
</div>
<?php //endif; ?>
<?php $viewer = Engine_Api::_()->user()->getViewer();?>

<?php if( engine_count($this->users) ): ?>
  <?php
    $ulClass = '';
    $excludedLevels = array(1, 2, 3);
    $isAdmin = false;

    if( !$this->viewer()->getIdentity() ) {
      $ulClass = 'public_user';
    } else {
      $viewerId = $viewer->getIdentity();
      if( engine_in_array($viewer->level_id, $excludedLevels) ) {
        $isAdmin = true;
      } else {
        $registeredPrivacy = array('everyone', 'registered');
        $friendsIds = $viewer->membership()->getMembersIds();
      }
    }

?>

  <div class="browse_mambers view-container" id="list-view" style="display: block;">
    <div class="browse_members_list">
      <?php foreach( $this->users as $user ): ?>
        <div class="browse_mambers_list_item browse_member_list_view_item">
          <article>
          <?php
            $showPhoto = false;
            $viewPrivacy = $user->view_privacy;

            if( !isset($viewerId) ) {
              if( $viewPrivacy == 'everyone' ) {
                $showPhoto = true;
              }
            } elseif( $isAdmin
              || $viewerId == $user->getIdentity()
              || engine_in_array($viewPrivacy, $registeredPrivacy)
              || ($viewPrivacy == 'member' && engine_in_array($user->getIdentity(), $friendsIds))) {
              $showPhoto = true;
            } elseif($viewPrivacy == 'network' ) {
              $netMembershipTable = Engine_Api::_()->getDbtable('membership', 'network');
              $viewerNetwork = $netMembershipTable->getMembershipsOfIds($viewer);
              $userNetwork = $netMembershipTable->getMembershipsOfIds($user);

              if( engine_in_array($user->getIdentity(), $friendsIds)
                || !empty(array_intersect($userNetwork, $viewerNetwork)) ) {
                $showPhoto = true;
              }
            }

            if( $showPhoto ){
              $profileImg = $this->itemBackgroundPhoto($user, 'thumb.profile');
            } else {
              $profileImg = '<span class="bg_item_photo bg_thumb_profile bg_item_photo_user bg_item_nophoto bg_item_nophoto_private"></span>';
            }
          ?>
            <div class="browse_mambers_list_item_thumb">
              <?php echo $this->htmlLink($user->getHref(), $profileImg) ?>
            </div>
            <div class='browse_mambers_list_item_info'>
              <div class="browse_mambers_list_item_name"><?php echo $this->htmlLink($user->getHref(), $user->getTitle(), array('class' => 'font_color')) ?></div>
              <?php if(0 && $user->status != "" ): ?>
                <div class="font_small">
                  <?php echo $user->status; ?>
                </div>
                <div class="font_small font_color_light">
                  <?php echo $this->timestamp($user->status_date) ?>
                </div>
              <?php endif; ?>
              <?php if( isset($viewerId) && $viewerId != $user->getIdentity() ): ?>
                <div class='browse_mambers_list_item_links'>
                  <div class="_friend"><?php echo $this->userFriendship($user, $this->viewer(), 'text') ?></div>
                  <?php if(Engine_Api::_()->getApi('settings', 'core')->getSetting('core.followenable',1)  && !Engine_Api::_()->user()->getViewer()->isSelf($user)) { ?>
                    <div class="_follow"><?php echo $this->partial('_followmembers.tpl', 'user', array('subject' => $user, 'iconType' => 'text')); ?> </div>
                  <?php } ?>
                  <!-- <?php if(Engine_Api::_()->authorization()->getPermission($user, 'user', 'canblock') && Engine_Api::_()->authorization()->getPermission($viewer, 'user', 'block') && !engine_in_array($user->getIdentity(), $this->blockedUserIds) ) :?>
                    <div class="_block">
                      <?php echo '<a href ="'. $this->url(array(
                      'controller' => 'block',
                      'action' => 'add',
                      'user_id' => $user->getIdentity()
                      ),'user_extended',true)
                      . '" class = "btn btn-alt smoothbox" data-bs-toggle="tooltip" title="'. $this->translate("Block Member") . '"><i class="icon_block"></i></a>'; ?>
                    </div>
                  <?php endif; ?> -->
                </div>
              <?php endif; ?>
            </div>
        </article>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <div class="browse_mambers view-container" id="grid-view" style="display: none;">
    <div class="browse_members_grid">
      <?php foreach( $this->users as $user ): ?>
        <div class="browse_mambers_grid_item">
          <article>
          <?php
            $showPhoto = false;
            $viewPrivacy = $user->view_privacy;

            if( !isset($viewerId) ) {
              if( $viewPrivacy == 'everyone' ) {
                $showPhoto = true;
              }
            } elseif( $isAdmin
              || $viewerId == $user->getIdentity()
              || engine_in_array($viewPrivacy, $registeredPrivacy)
              || ($viewPrivacy == 'member' && engine_in_array($user->getIdentity(), $friendsIds))) {
              $showPhoto = true;
            } elseif($viewPrivacy == 'network' ) {
              $netMembershipTable = Engine_Api::_()->getDbtable('membership', 'network');
              $viewerNetwork = $netMembershipTable->getMembershipsOfIds($viewer);
              $userNetwork = $netMembershipTable->getMembershipsOfIds($user);

              if( engine_in_array($user->getIdentity(), $friendsIds)
                || !empty(array_intersect($userNetwork, $viewerNetwork)) ) {
                $showPhoto = true;
              }
            }

            if( $showPhoto ){
              $profileImg = $this->itemBackgroundPhoto($user, 'thumb.profile');
            } else {
              $profileImg = '<span class="bg_item_photo bg_thumb_profile bg_item_photo_user bg_item_nophoto bg_item_nophoto_private"></span>';
            }
          ?>
            <div class="browse_mambers_grid_item_thumb">
              <?php echo $this->htmlLink($user->getHref(), $profileImg) ?>
            </div>
            <div class='browse_mambers_grid_item_info'>
              <div class="browse_mambers_grid_item_name"><?php echo $this->htmlLink($user->getHref(), $user->getTitle(), array('class' => 'font_color')) ?></div>
              <?php if(0 && $user->status != "" ): ?>
                <div class="font_small">
                  <?php echo $user->status; ?>
                </div>
                <div class="font_small font_color_light">
                  <?php echo $this->timestamp($user->status_date) ?>
                </div>
              <?php endif; ?>
              <?php if( isset($viewerId) && $viewerId != $user->getIdentity() ): ?>
                <div class='browse_mambers_grid_item_links'>
                  <div class="_friend"><?php echo $this->userFriendship($user, $this->viewer(), 'text') ?></div>
                  <?php if(Engine_Api::_()->getApi('settings', 'core')->getSetting('core.followenable',1)  && !Engine_Api::_()->user()->getViewer()->isSelf($user)) { ?>
                    <div class="_follow"><?php echo $this->partial('_followmembers.tpl', 'user', array('subject' => $user, 'iconType' => 'text')); ?> </div>
                  <?php } ?>
                  <!-- <?php if(Engine_Api::_()->authorization()->getPermission($user, 'user', 'canblock') && Engine_Api::_()->authorization()->getPermission($viewer, 'user', 'block') && !engine_in_array($user->getIdentity(), $this->blockedUserIds) ) :?>
                    <div class="_block">
                      <?php echo '<a href ="'. $this->url(array(
                      'controller' => 'block',
                      'action' => 'add',
                      'user_id' => $user->getIdentity()
                      ),'user_extended',true)
                      . '" class = "btn btn-alt smoothbox" data-bs-toggle="tooltip" title="'. $this->translate("Block Member") . '"><i class="icon_block"></i></a>'; ?>
                    </div>
                  <?php endif; ?> -->
                </div>
              <?php endif; ?>
            </div>
        </article>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
	<?php if($enableglocation == 1) { ?>
		<!-- Map View Container -->
		<div class="view-container browse_map_view" id="map-view" style="display: none;">
			<div id="members-map" class="map user_large_map" style="height: 600px; width: 100%; border-radius: 8px; overflow: hidden;"></div>
		</div>
	<?php } ?>
<?php endif ?>

<?php if( $this->users ):
    $pagination = $this->paginationControl($this->users, null, null, array(
      'pageAsQuery' => true,
      'query' => $this->formValues,
    ));
  ?>
  <?php if( trim($pagination) ): ?>
    <div class='browsemembers_viewmore' id="browsemembers_viewmore">
      <?php echo $pagination ?>
    </div>
  <?php endif ?>
<?php endif; ?>

<?php 
  $locationArray = array();
  $counter = 0;
  foreach( $this->users as $user ):
    $lat = null;
    $lng = null;
    
    if( isset($user->lat) && isset($user->lng) && $user->lat && $user->lng ) {
      $lat = $user->lat;
      $lng = $user->lng;
    }
    if( $lat && $lng && is_numeric($lat) && is_numeric($lng) ):
      $locationArray[$counter]['id'] = $user->getIdentity();
      $locationArray[$counter]['title'] = '<a href="'.$user->getHref().'">'.$user->getTitle().'</a>';
      $locationArray[$counter]['name'] = $user->getTitle();
      $locationArray[$counter]['href'] = $user->getHref();
      $locationArray[$counter]['image_url'] = $user->getPhotoUrl('thumb.profile');
      $locationArray[$counter]['lat'] = $lat;
      $locationArray[$counter]['lng'] = $lng;
      $counter++;
    endif;
  endforeach;
?>
<!-- Map Data -->
<?php if( $enableglocation == 1 && count($locationArray) > 0 ): ?>
  <div id="map-data" style="display:none;"><?php echo json_encode($locationArray, JSON_HEX_QUOT | JSON_HEX_TAG); ?></div>
<?php endif; ?>

<script type="text/javascript">
  page = '<?php echo sprintf('%d', $this->page) ?>';
  totalUsers = '<?php echo sprintf('%d', $this->totalUsers) ?>';
  userCount = '<?php echo sprintf('%d', $this->userCount) ?>';

  // View Switcher Functionality
  (function() {
    var currentView = 'list';
    var map = null;
    var oms = null;
    var markers = [];
    var countMarker = 0;
    var useRichMarker = false;
    var mapData = [];

		<?php if($enableglocation == 1) { ?>
			function loadMapData() {
				var mapDataElement = document.getElementById('map-data');
				if (mapDataElement) {
					try {
						mapData = JSON.parse(mapDataElement.innerHTML);
					} catch(e) {
						//console.error('Error parsing map data:', e);
						mapData = [];
					}
				}
			}
		<?php } ?>

    function initViewSwitcher() {
			<?php if($enableglocation == 1) { ?>
	      loadMapData();
			<?php } ?>
      
      var viewSwitchers = document.querySelectorAll('.view-switcher');
      for (var i = 0; i < viewSwitchers.length; i++) {
        viewSwitchers[i].addEventListener('click', function(e) {
          e.preventDefault();
          e.stopPropagation();
          var viewType = this.getAttribute('data-view');
          switchView(viewType);
          return false;
        });
      }
    }

    function switchView(viewType) {
      currentView = viewType;

	    var containers = document.querySelectorAll('.view-container');
      for (var i = 0; i < containers.length; i++) {
        containers[i].style.display = 'none';
      }

      var selectedContainer = document.getElementById(viewType + '-view');
      if (selectedContainer) {
        selectedContainer.style.display = 'block';
      }

      var switchers = document.querySelectorAll('.view-switcher');
      for (var j = 0; j < switchers.length; j++) {
        switchers[j].classList.remove('active');
        if (switchers[j].getAttribute('data-view') === viewType) {
          switchers[j].classList.add('active');
        }
      }

			<?php if($enableglocation == 1) { ?>
				if (viewType === 'map') {
					setTimeout(function() {
						initializeMap();
					}, 100);
				}
			<?php } ?>
    }

		<?php if($enableglocation == 1) { ?>
			function initializeMap() {
				if (map !== null) {
					google.maps.event.trigger(map, "resize");
					return;
				}
				if (typeof google === 'undefined' || typeof google.maps === 'undefined') {
					console.warn('Google Maps is not loaded.');
					return;
				}
				loadRichMarker();
			}

			function loadRichMarker() {
				useRichMarker = (typeof RichMarker !== 'undefined');
				if (!useRichMarker) {
					console.log('RichMarker not available; using native Google Maps markers.');
				}
				loadOMS();
			}

			function loadOMS() {
				if (typeof OverlappingMarkerSpiderfier === 'undefined') {
					console.warn('OverlappingMarkerSpiderfier is not loaded; overlapping marker spiderfying will be disabled.');
					oms = null;
					createMap();
				} else {
					createMap();
				}
			}

			function createMap() {
				var mapContainer = document.getElementById('members-map');
				if (!mapContainer) return;

				//Initialize map centered on world
				map = new google.maps.Map(mapContainer, {
					zoom: 2,
					scrollwheel: true,
					center: new google.maps.LatLng(20, 0),
				});

				if (typeof OverlappingMarkerSpiderfier !== 'undefined') {
					oms = new OverlappingMarkerSpiderfier(map, {nearbyDistance:40, circleSpiralSwitchover:0});
				} else {
					oms = null;
				}

				//Add members to map
				addMembersToMap();
			}

			function createMarkerClickListener(marker, infoWindow) {
				marker.addListener('click', function() {
					//Close all other info windows
					for (var m = 0; m < markers.length; m++) {
						if (markers[m].infoWindow) {
							markers[m].infoWindow.close();
						}
					}
					infoWindow.open(map, marker);
				});
			}

			function addMembersToMap() {
				if (!map) return;

				if (!mapData || mapData.length === 0) {
					map.setCenter(new google.maps.LatLng(26.9110600, 75.7373560));
					map.setZoom(5);
					return;
				}

				var bounds = new google.maps.LatLngBounds();
				var hasMarkers = false;

				var RichMarkerPosition = {
					TOP_LEFT: 1,
					TOP: 2,
					TOP_RIGHT: 3,
					LEFT: 4,
					MIDDLE: 5,
					RIGHT: 6,
					BOTTOM_LEFT: 7,
					BOTTOM: 8,
					BOTTOM_RIGHT: 9
				};

				// Loop through mapData array (members with location data)
				for (var u = 0; u < mapData.length; u++) {
					var memberData = mapData[u];
					
					if (!memberData.lat || !memberData.lng) {
						continue; // Skip if no coordinates
					}

					var lat = parseFloat(memberData.lat);
					var lng = parseFloat(memberData.lng);
					var name = memberData.name;
					var href = memberData.href;
					var imageUrl = memberData.image_url ? memberData.image_url : '';

					var markerData = null;

					markerData = new google.maps.Marker({
						position: new google.maps.LatLng(lat, lng),
						map: map,
						title: name,
					});

					var infoContent = '<div class="user_map_info_tip">' +
						'<div class="user_map_info_thumb"><img src="' + imageUrl + '" style="" alt="" /></div>' +
            '<div class="user_map_info"><div class="user_map_title text-center"><a href="' + href + '">' + name + '</a></div>' +
						
						'<div class="mt-2"><a href="' + href + '" class="user_map_btn btn btn-primary">View Profile</a></div></div></div>';

					var infoWindow = new google.maps.InfoWindow({
						content: infoContent,
						maxWidth: 300,
					});
					markerData.infoWindow = infoWindow;
					markerData.markerid = countMarker;
					createMarkerClickListener(markerData, infoWindow);

					markers.push(markerData);
					markerData.setMap(map);
					bounds.extend(markerData.getPosition());
					
					if (oms && useRichMarker) {
						oms.addMarker(markerData);
					}
					countMarker++;
					hasMarkers = true;
				}
				if (oms && useRichMarker) {
					oms.addListener('click', function(marker) {
						var id = marker.markerid;
						var previousIndex = scriptJquery('.marker_' + id).parent().parent().css('z-index');
						scriptJquery('.marker_' + id).parent().parent().css('z-index', '9999');
						scriptJquery('.pin').removeClass('active').css('z-index', 10);
						scriptJquery('.marker_' + id).addClass('active').css('z-index', 200);
						scriptJquery('.marker_' + id + ' .large .close').click(function() {
							scriptJquery(this).parent().parent().parent().parent().parent().css('z-index', previousIndex);
							scriptJquery('.pin').removeClass('active');
							return false;
						});
					});
				}

				if (hasMarkers) {
					map.fitBounds(bounds);
				} else {
					map.setCenter(new google.maps.LatLng(26.9110600, 75.7373560));
					map.setZoom(5);
				}
			}
		<?php } ?>

    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', initViewSwitcher);
    } else {
      initViewSwitcher();
    }
  })();
</script>
