/**
 * Adds rel='canonical' tag to links.
 *
 * @since 1.0.0
 * @package GeoDirectory_Location_Manager
 *
 * @global object $wp WordPress object.
 */
function geodir_location_rel_canonical()
{
    global $wp;
    if (isset($wp->query_vars['page_id']) && $wp->query_vars['page_id'] == geodir_location_page_id()) {
        $link = geodir_get_location_link();
        if (get_option('geodir_set_as_home') && $link == geodir_get_location_link('base')) {
            $link = get_bloginfo('url');
        } else {
            if (get_option('permalink_structure') != '') {
                $link = trim($link);
                $link = rtrim($link, "/") . "/";
            }
        }
        echo "<link rel='canonical' href='{$link}' />\n";
    }
}
/**
 *
 * @global object $wpdb WordPress Database object.
 *
 * @param $atts
 * @return string
 */
function geodir_sc_location_neighbourhood($atts)
{
    global $wpdb;
    ob_start();
    $location_id = '';
    if ($gd_city = get_query_var('gd_city')) {
        $location_id = $wpdb->get_var($wpdb->prepare("SELECT location_id from " . POST_LOCATION_TABLE . " WHERE city_slug=%s", array($gd_city)));
    }
    $gd_neighbourhoods = geodir_get_neighbourhoods($location_id);
    $location_request = array();
    $location_request[] = get_query_var('gd_country');
    $location_request[] = get_query_var('gd_region');
    $location_request[] = get_query_var('gd_city');
    if ($gd_neighbourhoods) {
        ?>
		<div id="geodir-category-list">
			<div class="geodir-category-list-in clearfix">
				<div class="geodir-cat-list clearfix">
					<?php 
        $hood_count = 0;
        echo '<ul>';
        foreach ($gd_neighbourhoods as $gd_neighbourhood) {
            if ($hood_count % 15 == 0) {
                echo '</ul><ul>';
            }
            $neighbourhood_action = esc_url(add_query_arg(array('gd_neighbourhood' => $gd_neighbourhood->hood_slug), rtrim(geodir_get_location_link('current'), '/') . '/'));
            echo '<li><a href="' . $neighbourhood_action . '">' . ucwords($gd_neighbourhood->hood_name) . '</a></li>';
            $hood_count++;
        }
        echo '</ul>';
        ?>

				</div>
			</div>
		</div>
	<?php 
    }
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}
    /**
     * @param array $args
     * @param array $instance
     */
    public function widget($args, $instance)
    {
        // prints the widget
        extract($args, EXTR_SKIP);
        $title = empty($instance['title']) ? __('Near Me', GEODIRECTORY_TEXTDOMAIN) : apply_filters('widget_title', __($instance['title'], GEODIRECTORY_TEXTDOMAIN));
        //$count = empty( $instance['count'] ) ? '5' : apply_filters( 'widget_count', $instance['count'] );
        //$comments_li = geodir_get_recent_reviews( 30, $count, 100, false );
        ?>
<script type="text/javascript">
gdShareLocationOptions = {
	enableHighAccuracy: true,
	timeout: 5000,
	maximumAge: 0
};
function gdGetLocationNearMe() {
	//jQuery('.snear').removeClass("near-country near-region near-city");// remove any location classes
	//if(box && box.prop('checked') != true){gdClearUserLoc();return;}
	// Try HTML5 geolocation
	if(navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position) {
			lat = position.coords.latitude;
			lon = position.coords.longitude;
			my_location = 1;
			if(typeof gdSetupUserLoc === 'function') {
				gdSetupUserLoc();
			} else {
				gdLocationSetupUserLoc();
			}
			jQuery.ajax({
				// url: url,
				url: "<?php 
        echo admin_url('admin-ajax.php');
        ?>
",
				type: 'POST',
				dataType: 'html',
				data: {
					action: 'gd_location_manager_set_user_location',
					lat: lat,
					lon: lon,
					myloc: 1
				},
				beforeSend: function() {},
				success: function(data, textStatus, xhr) {
					window.location.href = "<?php 
        echo geodir_get_location_link('base') . 'me/';
        ?>
";
				},
				error: function(xhr, textStatus, errorThrown) {
					alert(textStatus);
				}
			});
		}, gdShareLocationError, gdShareLocationOptions);
	} else {
		// Browser doesn't support Geolocation
		alert(geodir_location_all_js_msg.DEFAUTL_ERROR);
	}
}
</script>
		
			<?php 
        echo $before_widget;
        ?>
			<button type="button" onclick=" gdGetLocationNearMe();"><?php 
        echo $title;
        ?>
</button>
			<?php 
        echo $after_widget;
    }
/**
 * Add the location variables in session.
 *
 * @since 1.0.0
 *
 * @param object $wp The WordPress object.
 */
function geodir_set_location_var_in_session_in_core($wp)
{
    //$wp->geodir_query_vars = $wp->query_vars ;
    // this code will determine when a user wants to switch location
    // Query Vars will have page_id parameter
    // check if query var has page_id and that page id is location page
    geodir_set_is_geodir_page($wp);
    if (!get_option('geodir_set_as_home')) {
        if (empty($wp->query_vars) || !array_diff(array_keys($wp->query_vars), array('preview', 'page', 'paged', 'cpage'))) {
            if ('page' == get_option('show_on_front')) {
                $wp->query_vars['page_id'] = get_option('page_on_front');
            }
        }
    }
    if (isset($wp->query_vars['page_id']) && $wp->query_vars['page_id'] == geodir_location_page_id()) {
        $gd_country = '';
        $gd_region = '';
        $gd_city = '';
        if (isset($wp->query_vars['gd_country']) && $wp->query_vars['gd_country'] != '') {
            $gd_country = urldecode($wp->query_vars['gd_country']);
        }
        if (isset($wp->query_vars['gd_region']) && $wp->query_vars['gd_region'] != '') {
            $gd_region = urldecode($wp->query_vars['gd_region']);
        }
        if (isset($wp->query_vars['gd_city']) && $wp->query_vars['gd_city'] != '') {
            $gd_city = urldecode($wp->query_vars['gd_city']);
        }
        if (!($gd_country == '' && $gd_region == '' && $gd_city == '')) {
            $default_location = geodir_get_default_location();
            if (get_option('geodir_add_location_url')) {
                if (get_option('geodir_show_location_url') != 'all') {
                    if ($gd_region == '') {
                        if (isset($_SESSION['gd_region'])) {
                            $gd_region = $_SESSION['gd_region'];
                        } else {
                            $gd_region = $default_location->region_slug;
                        }
                    }
                    if ($gd_city == '') {
                        if (isset($_SESSION['gd_city'])) {
                            $gd_city = $_SESSION['gd_city'];
                        } else {
                            $gd_city = $default_location->city_slug;
                        }
                        $base_location_link = geodir_get_location_link('base');
                        wp_redirect($base_location_link . '/' . $gd_country . '/' . $gd_region . '/' . $gd_city);
                        exit;
                    }
                }
            }
            $args = array('what' => 'city', 'city_val' => $gd_city, 'region_val' => $gd_region, 'country_val' => $gd_country, 'country_column_name' => 'country_slug', 'region_column_name' => 'region_slug', 'city_column_name' => 'city_slug', 'location_link_part' => false, 'compare_operator' => '');
            $location_array = function_exists('geodir_get_location_array') ? geodir_get_location_array($args) : array();
            if (!empty($location_array)) {
                $_SESSION['gd_multi_location'] = 1;
                $_SESSION['gd_country'] = $gd_country;
                $_SESSION['gd_region'] = $gd_region;
                $_SESSION['gd_city'] = $gd_city;
                $wp->query_vars['gd_country'] = $gd_country;
                $wp->query_vars['gd_region'] = $gd_region;
                $wp->query_vars['gd_city'] = $gd_city;
            } else {
                unset($_SESSION['gd_multi_location'], $_SESSION['gd_city'], $_SESSION['gd_region'], $_SESSION['gd_country']);
            }
        } else {
            unset($_SESSION['gd_multi_location'], $_SESSION['gd_city'], $_SESSION['gd_region'], $_SESSION['gd_country']);
        }
    } else {
        if (isset($wp->query_vars['post_type']) && $wp->query_vars['post_type'] != '') {
            if (!is_admin()) {
                $requested_post_type = $wp->query_vars['post_type'];
                // check if this post type is geodirectory post types
                $post_type_array = geodir_get_posttypes();
                if (in_array($requested_post_type, $post_type_array)) {
                    // now u can apply geodirectory related manipulation.
                }
            }
        } else {
            // check if a geodirectory taxonomy is set
            $gd_country = '';
            $gd_region = '';
            $gd_city = '';
            $is_geodir_taxonomy = false;
            $is_geodir_taxonomy_term = false;
            // the last term is real geodirectory taxonomy term or not
            $is_geodir_location_found = false;
            $geodir_taxonomy = '';
            $geodir_post_type = '';
            $geodir_term = '';
            $geodir_set_location_session = true;
            $geodir_taxonomis = geodir_get_taxonomies('', true);
            foreach ($geodir_taxonomis as $taxonomy) {
                if (array_key_exists($taxonomy, $wp->query_vars)) {
                    $is_geodir_taxonomy = true;
                    $geodir_taxonomy = $taxonomy;
                    $geodir_post_type = str_replace('category', '', $taxonomy);
                    $geodir_post_type = str_replace('_tags', '', $geodir_post_type);
                    $geodir_term = $wp->query_vars[$geodir_taxonomy];
                    break;
                }
            }
            // now get an array of all terms seperated by '/'
            $geodir_terms = explode('/', $geodir_term);
            $geodir_last_term = end($geodir_terms);
            if ($is_geodir_taxonomy) {
                $wp->query_vars['post_type'] = $geodir_post_type;
                // now check if last term is a post of geodirectory post types
                $geodir_post = get_posts(array('name' => $geodir_last_term, 'posts_per_page' => 1, 'post_type' => $geodir_post_type));
                if (empty($geodir_post)) {
                    $geodir_post = get_posts(array('name' => $geodir_last_term, 'posts_per_page' => 1, 'post_type' => $geodir_post_type, 'post_status' => 'draft', 'suppress_filters' => false));
                }
                if (!empty($geodir_post)) {
                    if ($geodir_post[0]->post_status != 'publish') {
                        foreach ($wp->query_vars as $key => $vars) {
                            unset($wp->query_vars[$key]);
                        }
                        $wp->query_vars['error'] = '404';
                        // set it as 404 if post exists but its status is not published yet
                    } else {
                        //$wp->query_vars[$geodir_taxonomy] = str_replace( '/'.$geodir_last_term , ''  , $geodir_term);
                        $wp->query_vars[$geodir_post_type] = $geodir_last_term;
                        $wp->query_vars['name'] = $geodir_last_term;
                    }
                    $geodir_term = str_replace('/' . $geodir_last_term, '', $geodir_term, $post_title_replace_count);
                    if (!$post_title_replace_count) {
                        $geodir_term = str_replace($geodir_last_term, '', $geodir_term, $post_title_replace_count);
                    }
                    $geodir_terms = explode('/', $geodir_term);
                    $geodir_last_term = end($geodir_terms);
                    $geodir_set_location_session = false;
                    //return ;
                }
                $geodir_location_terms = '';
                // if last term is not a post then check if last term is a term of the specific texonomy or not
                if (geodir_term_exists($geodir_last_term, $geodir_taxonomy)) {
                    $is_geodir_taxonomy_term = true;
                    $geodir_set_location_session = false;
                }
                // now check if there is location parts in the url or not
                if (get_option('geodir_add_location_url')) {
                    $default_location = geodir_get_default_location();
                    if (get_option('geodir_show_location_url') == 'all') {
                        if (count($geodir_terms) >= 3) {
                            $gd_country = urldecode($geodir_terms[0]);
                            $gd_region = urldecode($geodir_terms[1]);
                            $gd_city = urldecode($geodir_terms[2]);
                        } else {
                            if (count($geodir_terms) >= 2) {
                                $gd_country = urldecode($geodir_terms[0]);
                                $gd_region = urldecode($geodir_terms[1]);
                            } else {
                                if (count($geodir_terms) >= 1) {
                                    $gd_country = urldecode($geodir_terms[0]);
                                }
                            }
                        }
                        if (strtolower($default_location->country_slug) == strtolower($gd_country) && strtolower($default_location->region_slug) == strtolower($gd_region) && strtolower($default_location->city_slug) == strtolower($gd_city)) {
                            $is_geodir_location_found = true;
                        }
                        // if location has not been found for country , region and city then search for country and region only
                        if (!$is_geodir_location_found) {
                            $gd_city = '';
                            if (strtolower($default_location->country_slug) == strtolower($gd_country) && strtolower($default_location->region_slug) == strtolower($gd_region)) {
                                $is_geodir_location_found = true;
                            }
                        }
                        // if location has not been found for country , region  then search for country only
                        if (!$is_geodir_location_found) {
                            $gd_city = '';
                            $gd_region = '';
                            if (strtolower($default_location->country_slug) == strtolower($gd_country)) {
                                $is_geodir_location_found = true;
                            }
                        }
                    } else {
                        $gd_city = $geodir_terms[0];
                        if (strtolower($default_location->city_slug) == strtolower($gd_city)) {
                            $is_geodir_location_found = true;
                            $gd_region = $default_location->region_slug;
                            $gd_country = $default_location->country_slug;
                        }
                    }
                    // if locaton still not found then clear location related session variables
                    if ($is_geodir_location_found && $geodir_set_location_session) {
                        $_SESSION['gd_multi_location'] = 1;
                        $_SESSION['gd_country'] = $gd_country;
                        $_SESSION['gd_region'] = $gd_region;
                        $_SESSION['gd_city'] = $gd_city;
                    }
                    if (get_option('geodir_show_location_url') != 'all') {
                        $gd_country = '';
                        $gd_region = '';
                    }
                    if ($is_geodir_location_found) {
                        $wp->query_vars['gd_country'] = $gd_country;
                        $wp->query_vars['gd_region'] = $gd_region;
                        $wp->query_vars['gd_city'] = $gd_city;
                    } else {
                        $gd_country = '';
                        $gd_region = '';
                        $gd_city = '';
                    }
                }
                $wp->query_vars[$geodir_taxonomy] = $geodir_term;
                // eliminate location related terms from taxonomy term
                if ($gd_country != '') {
                    $wp->query_vars[$geodir_taxonomy] = preg_replace('/' . urlencode($gd_country) . '/', '', $wp->query_vars[$geodir_taxonomy], 1);
                }
                if ($gd_region != '') {
                    $wp->query_vars[$geodir_taxonomy] = preg_replace('/' . urlencode($gd_region) . '/', '', $wp->query_vars[$geodir_taxonomy], 1);
                }
                if ($gd_city != '') {
                    $wp->query_vars[$geodir_taxonomy] = preg_replace('/' . urlencode($gd_city) . '/', '', $wp->query_vars[$geodir_taxonomy], 1);
                }
                $wp->query_vars[$geodir_taxonomy] = str_replace('///', '', $wp->query_vars[$geodir_taxonomy]);
                $wp->query_vars[$geodir_taxonomy] = str_replace('//', '', $wp->query_vars[$geodir_taxonomy]);
                $wp->query_vars[$geodir_taxonomy] = trim($wp->query_vars[$geodir_taxonomy], '/');
                if ($wp->query_vars[$geodir_taxonomy] == '') {
                    unset($wp->query_vars[$geodir_taxonomy]);
                } else {
                    if (!$is_geodir_taxonomy_term) {
                        foreach ($wp->query_vars as $key => $vars) {
                            unset($wp->query_vars[$key]);
                        }
                        $wp->query_vars['error'] = '404';
                    }
                }
            }
        }
    }
    if (isset($_SESSION['gd_multi_location']) && $_SESSION['gd_multi_location'] == 1) {
        $wp->query_vars['gd_country'] = $_SESSION['gd_country'];
        $wp->query_vars['gd_region'] = $_SESSION['gd_region'];
        $wp->query_vars['gd_city'] = $_SESSION['gd_city'];
    }
    // now check if there is location parts in the url or not
    if (get_option('geodir_add_location_url')) {
        if (get_option('geodir_show_location_url') != 'all') {
            if (isset($wp->query_vars['gd_country'])) {
                $wp->query_vars['gd_country'] = '';
            }
            if (isset($wp->query_vars['gd_region'])) {
                $wp->query_vars['gd_region'] = '';
            }
        }
    } else {
        if (isset($wp->query_vars['gd_country'])) {
            $wp->query_vars['gd_country'] = '';
        }
        if (isset($wp->query_vars['gd_region'])) {
            $wp->query_vars['gd_region'] = '';
        }
        if (isset($wp->query_vars['gd_city'])) {
            $wp->query_vars['gd_city'] = '';
        }
    }
}
/**
 * Get location array using arguments.
 *
 * @since 1.0.0
 * @package GeoDirectory_Location_Manager
 *
 * @global object $wpdb WordPress Database object.
 *
 * @param null|array $args {
 *    Attributes of args.
 *
 *    @type string $what What do you want to query. Possible values: city, region, country. Default: 'city'.
 *    @type string $city_val City value.
 *    @type string $region_val Region value.
 *    @type string $country_val Country value.
 *    @type string $country_non_restricted Non restricted countries.
 *    @type string $region_non_restricted Non restricted regions.
 *    @type string $city_non_restricted Non restricted cities.
 *    @type bool $filter_by_non_restricted Filter by non restricted?.
 *    @type string $compare_operator Comparison operator.
 *    @type string $country_column_name Country column name.
 *    @type string $region_column_name Region column name.
 *    @type string $city_column_name City column name.
 *    @type bool $location_link_part Location link part.
 *    @type string $order_by Order by value.
 *    @type string $no_of_records No of records to return.
 *    @type string $spage Current page number.
 *    @type array $format {
 *        Attributes of format.
 *
 *        @type string $type Type. Default: 'list'.
 *        @type string $container_wrapper Container wrapper. Default: 'ul'.
 *        @type string $container_wrapper_attr Container wrapper attr.
 *        @type string $item_wrapper Item wrapper. Default: 'li'.
 *        @type string $item_wrapper_attr Item wrapper attr.
 *
 *    }
 *
 * }
 * @param bool $switcher Todo: describe this part.
 * @return array|mixed|string
 */
function geodir_get_location_array($args = null, $switcher = false)
{
    global $wpdb;
    $defaults = array('what' => 'city', 'city_val' => '', 'region_val' => '', 'country_val' => '', 'country_non_restricted' => '', 'region_non_restricted' => '', 'city_non_restricted' => '', 'filter_by_non_restricted' => true, 'compare_operator' => 'like', 'country_column_name' => 'country', 'region_column_name' => 'region', 'city_column_name' => 'city', 'location_link_part' => true, 'order_by' => 'asc', 'no_of_records' => '', 'spage' => '', 'format' => array('type' => 'list', 'container_wrapper' => 'ul', 'container_wrapper_attr' => '', 'item_wrapper' => 'li', 'item_wrapper_attr' => ''));
    $location_args = wp_parse_args($args, $defaults);
    $search_query = '';
    $location_link_column = '';
    $location_default = geodir_get_default_location();
    if ($location_args['filter_by_non_restricted']) {
        // Non restricted countries
        if ($location_args['country_non_restricted'] == '') {
            if (get_option('geodir_enable_country') == 'default') {
                $country_non_retsricted = isset($location_default->country) ? $location_default->country : '';
                $location_args['country_non_restricted'] = $country_non_retsricted;
            } else {
                if (get_option('geodir_enable_country') == 'selected') {
                    $country_non_retsricted = get_option('geodir_selected_countries');
                    if (!empty($country_non_retsricted) && is_array($country_non_retsricted)) {
                        $country_non_retsricted = implode(',', $country_non_retsricted);
                    }
                    $location_args['country_non_restricted'] = $country_non_retsricted;
                }
            }
            $location_args['country_non_restricted'] = geodir_parse_location_list($location_args['country_non_restricted']);
        }
        //Non restricted Regions
        if ($location_args['region_non_restricted'] == '') {
            if (get_option('geodir_enable_region') == 'default') {
                $regoin_non_restricted = isset($location_default->region) ? $location_default->region : '';
                $location_args['region_non_restricted'] = $regoin_non_restricted;
            } else {
                if (get_option('geodir_enable_region') == 'selected') {
                    $regoin_non_restricted = get_option('geodir_selected_regions');
                    if (!empty($regoin_non_restricted) && is_array($regoin_non_restricted)) {
                        $regoin_non_restricted = implode(',', $regoin_non_restricted);
                    }
                    $location_args['region_non_restricted'] = $regoin_non_restricted;
                }
            }
            $location_args['region_non_restricted'] = geodir_parse_location_list($location_args['region_non_restricted']);
        }
        //Non restricted cities
        if ($location_args['city_non_restricted'] == '') {
            if (get_option('geodir_enable_city') == 'default') {
                $city_non_retsricted = isset($location_default->city) ? $location_default->city : '';
                $location_args['city_non_restricted'] = $city_non_retsricted;
            } else {
                if (get_option('geodir_enable_city') == 'selected') {
                    $city_non_restricted = get_option('geodir_selected_cities');
                    if (!empty($city_non_restricted) && is_array($city_non_restricted)) {
                        $city_non_restricted = implode(',', $city_non_restricted);
                    }
                    $location_args['city_non_restricted'] = $city_non_restricted;
                }
            }
            $location_args['city_non_restricted'] = geodir_parse_location_list($location_args['city_non_restricted']);
        }
    }
    if ($location_args['what'] == '') {
        $location_args['what'] = 'city';
    }
    if ($location_args['location_link_part']) {
        switch ($location_args['what']) {
            case 'country':
                if (get_option('permalink_structure') != '') {
                    $location_link_column = ", CONCAT_WS('/', country_slug) AS location_link ";
                } else {
                    $location_link_column = ", CONCAT_WS('&gd_country=', '', country_slug) AS location_link ";
                }
                break;
            case 'region':
                if (get_option('permalink_structure') != '') {
                    $location_link_column = ", CONCAT_WS('/', country_slug, region_slug) AS location_link ";
                } else {
                    $location_link_column = ", CONCAT_WS('&', CONCAT('&gd_country=', country_slug), CONCAT('gd_region=', region_slug) ) AS location_link ";
                }
                break;
            case 'city':
                if (get_option('permalink_structure') != '') {
                    $location_link_column = ", CONCAT_WS('/', country_slug, region_slug, city_slug) AS location_link ";
                } else {
                    $location_link_column = ", CONCAT_WS('&', CONCAT('&gd_country=', country_slug), CONCAT('gd_region=', region_slug) ,CONCAT('gd_city=' , city_slug)) AS location_link ";
                }
                /*else
                				{
                					if ( get_option('permalink_structure') != '' )
                						$location_link_column = " ,   city_slug as location_link ";
                					else
                						$location_link_column = " , CONCAT_WS('&gd_city=', '',city_slug) as location_link ";
                
                				}*/
                break;
                /*default:
                				if(get_option('geodir_show_location_url')=='all')
                				{
                					if ( get_option('permalink_structure') != '' )
                						$location_link_column = " , CONCAT_WS('/', country_slug, region_slug, city_slug) as location_link ";
                					else
                						$location_link_column = " , CONCAT_WS('&', CONCAT('&gd_country=' ,country_slug) ,CONCAT('gd_region=' , region_slug) ,CONCAT('gd_city=' , city_slug)) as location_link ";
                				}
                				else
                				{
                					if ( get_option('permalink_structure') != '' )
                						$location_link_column = " ,   city_slug as location_link ";
                					else
                						$location_link_column = " , CONCAT_WS('&gd_city=', '',city_slug) as location_link ";
                
                				}
                				break;*/
        }
    }
    switch ($location_args['compare_operator']) {
        case 'like':
            if (isset($location_args['country_val']) && $location_args['country_val'] != '') {
                //$search_query .= " AND lower(".$location_args['country_column_name'].") like  '". mb_strtolower( $location_args['country_val'] )."%' ";
                $countries_search_sql = geodir_countries_search_sql($location_args['country_val']);
                $countries_search_sql = $countries_search_sql != '' ? " OR FIND_IN_SET(country, '" . $countries_search_sql . "')" : '';
                $translated_country_val = sanitize_title(trim(wp_unslash($location_args['country_val'])));
                $search_query .= " AND ( lower(" . $location_args['country_column_name'] . ") like  '%" . mb_strtolower($location_args['country_val']) . "%' OR  lower(country_slug) LIKE '" . $translated_country_val . "%' " . $countries_search_sql . " ) ";
            }
            if (isset($location_args['region_val']) && $location_args['region_val'] != '') {
                $search_query .= " AND lower(" . $location_args['region_column_name'] . ") like  '%" . mb_strtolower($location_args['region_val']) . "%' ";
            }
            if (isset($location_args['city_val']) && $location_args['city_val'] != '') {
                $search_query .= " AND lower(" . $location_args['city_column_name'] . ") like  '%" . mb_strtolower($location_args['city_val']) . "%' ";
            }
            break;
        case 'in':
            if (isset($location_args['country_val']) && $location_args['country_val'] != '') {
                $location_args['country_val'] = geodir_parse_location_list($location_args['country_val']);
                $search_query .= " AND lower(" . $location_args['country_column_name'] . ") in({$location_args['country_val']}) ";
            }
            if (isset($location_args['region_val']) && $location_args['region_val'] != '') {
                $location_args['region_val'] = geodir_parse_location_list($location_args['region_val']);
                $search_query .= " AND lower(" . $location_args['region_column_name'] . ") in({$location_args['region_val']}) ";
            }
            if (isset($location_args['city_val']) && $location_args['city_val'] != '') {
                $location_args['city_val'] = geodir_parse_location_list($location_args['city_val']);
                $search_query .= " AND lower(" . $location_args['city_column_name'] . ") in({$location_args['city_val']}) ";
            }
            break;
        default:
            if (isset($location_args['country_val']) && $location_args['country_val'] != '') {
                //$search_query .= " AND lower(".$location_args['country_column_name'].") =  '". mb_strtolower($location_args['country_val'])."' ";
                $countries_search_sql = geodir_countries_search_sql($location_args['country_val']);
                $countries_search_sql = $countries_search_sql != '' ? " OR FIND_IN_SET(country, '" . $countries_search_sql . "')" : '';
                $translated_country_val = sanitize_title(trim(wp_unslash($location_args['country_val'])));
                $search_query .= " AND ( lower(" . $location_args['country_column_name'] . ") =  '" . mb_strtolower($location_args['country_val']) . "' OR  lower(country_slug) LIKE '" . $translated_country_val . "%' " . $countries_search_sql . " ) ";
            }
            if (isset($location_args['region_val']) && $location_args['region_val'] != '') {
                $search_query .= " AND lower(" . $location_args['region_column_name'] . ") =  '" . mb_strtolower($location_args['region_val']) . "' ";
            }
            if (isset($location_args['city_val']) && $location_args['city_val'] != '') {
                $search_query .= " AND lower(" . $location_args['city_column_name'] . ") =  '" . mb_strtolower($location_args['city_val']) . "' ";
            }
            break;
    }
    // end of switch
    if ($location_args['country_non_restricted'] != '') {
        $search_query .= " AND LOWER(country) IN ({$location_args['country_non_restricted']}) ";
    }
    if ($location_args['region_non_restricted'] != '') {
        if ($location_args['what'] == 'region' || $location_args['what'] == 'city') {
            $search_query .= " AND LOWER(region) IN ({$location_args['region_non_restricted']}) ";
        }
    }
    if ($location_args['city_non_restricted'] != '') {
        if ($location_args['what'] == 'city') {
            $search_query .= " AND LOWER(city) IN ({$location_args['city_non_restricted']}) ";
        }
    }
    //page
    if ($location_args['no_of_records']) {
        $spage = $location_args['no_of_records'] * $location_args['spage'];
    } else {
        $spage = "0";
    }
    // limit
    $limit = $location_args['no_of_records'] != '' ? ' LIMIT ' . $spage . ', ' . (int) $location_args['no_of_records'] . ' ' : '';
    // display all locations with same name also
    $search_field = $location_args['what'];
    if ($switcher) {
        $select = $search_field . $location_link_column;
        $group_by = $search_field;
        $order_by = $search_field;
        if ($search_field == 'city') {
            $select .= ', country, region, city, country_slug, region_slug, city_slug';
            $group_by = 'country, region, city';
            $order_by = 'city, region, country';
        } else {
            if ($search_field == 'region') {
                $select .= ', country, region, country_slug, region_slug';
                $group_by = 'country, region';
                $order_by = 'region, country';
            } else {
                if ($search_field == 'country') {
                    $select .= ', country, country_slug';
                    $group_by = 'country';
                    $order_by = 'country';
                }
            }
        }
        $main_location_query = "SELECT " . $select . " FROM " . POST_LOCATION_TABLE . " WHERE 1=1 " . $search_query . " GROUP BY " . $group_by . " ORDER BY " . $order_by . " " . $location_args['order_by'] . " " . $limit;
    } else {
        $main_location_query = "SELECT {$location_args['what']} {$location_link_column} FROM " . POST_LOCATION_TABLE . " WHERE 1=1 " . $search_query . " GROUP BY {$location_args['what']} ORDER BY {$location_args['what']} {$location_args['order_by']} {$limit}";
    }
    $locations = $wpdb->get_results($main_location_query);
    if ($switcher && !empty($locations)) {
        $new_locations = array();
        foreach ($locations as $location) {
            //print_r($location);
            //echo '###'.$search_field;
            $new_location = $location;
            $label = $location->{$search_field};
            if (($search_field == 'city' || $search_field == 'region') && (int) geodir_location_check_duplicate($search_field, $label) > 1) {
                if ($search_field == 'city') {
                    $label .= ', ' . $location->region;
                } else {
                    if ($search_field == 'region') {
                        $country_iso2 = geodir_location_get_iso2($location->country);
                        $country_iso2 = $country_iso2 != '' ? $country_iso2 : $location->country;
                        $label .= $country_iso2 != '' ? ', ' . $country_iso2 : '';
                    }
                }
            }
            $new_location->title = $location->{$search_field};
            $new_location->{$search_field} = $label;
            $new_location->label = $label;
            $new_locations[] = $new_location;
        }
        $locations = $new_locations;
    }
    $location_as_formated_list = "";
    if (!empty($location_args['format'])) {
        if ($location_args['format']['type'] == 'array') {
            return $locations;
        } elseif ($location_args['format']['type'] == 'jason') {
            return json_encode($locations);
        } else {
            $base_location_link = geodir_get_location_link('base');
            $container_wrapper = '';
            $container_wrapper_attr = '';
            $item_wrapper = '';
            $item_wrapper_attr = '';
            if (isset($location_args['format']['container_wrapper']) && !empty($location_args['format']['container_wrapper'])) {
                $container_wrapper = $location_args['format']['container_wrapper'];
            }
            if (isset($location_args['format']['container_wrapper_attr']) && !empty($location_args['format']['container_wrapper_attr'])) {
                $container_wrapper_attr = $location_args['format']['container_wrapper_attr'];
            }
            if (isset($location_args['format']['item_wrapper']) && !empty($location_args['format']['item_wrapper'])) {
                $item_wrapper = $location_args['format']['item_wrapper'];
            }
            if (isset($location_args['format']['item_wrapper_attr']) && !empty($location_args['format']['item_wrapper_attr'])) {
                $item_wrapper_attr = $location_args['format']['item_wrapper_attr'];
            }
            if (!empty($container_wrapper)) {
                $location_as_formated_list = "<" . $container_wrapper . " " . $container_wrapper_attr . " >";
            }
            if (!empty($locations)) {
                foreach ($locations as $location) {
                    if (!empty($item_wrapper)) {
                        $location_as_formated_list .= "<" . $item_wrapper . " " . $item_wrapper_attr . " >";
                    }
                    if (isset($location->location_link)) {
                        $location_as_formated_list .= "<a href='" . geodir_location_permalink_url($base_location_link . $location->location_link) . "' ><i class='fa fa-caret-right'></i> ";
                    }
                    $location_as_formated_list .= $location->{$location_args}['what'];
                    if (isset($location->location_link)) {
                        $location_as_formated_list .= "</a>";
                    }
                    if (!empty($item_wrapper)) {
                        $location_as_formated_list .= "</" . $item_wrapper . ">";
                    }
                }
            }
            return $location_as_formated_list;
        }
    }
    return $locations;
}
/**
 *
 * @global object $wpdb WordPress Database object.
 *
 * @param null $args
 * @return string
 */
function geodir_location_tab_switcher($args = null)
{
    $switcher = !empty($args) && isset($args['addSearchTermOnNorecord']) ? true : false;
    if (get_option('geodir_enable_country') != 'default' || get_option('geodir_enable_region') != 'default' || get_option('geodir_enable_city') != 'default') {
        $defaults = array('echo' => true, 'addSearchTermOnNorecord' => 0, 'autoredirect' => false);
        $args = wp_parse_args($args, $defaults);
        global $wpdb;
        // Options
        $echo = $args['echo'];
        $addSearchTermOnNorecord = $args['addSearchTermOnNorecord'];
        $autoredirect = $args['autoredirect'];
        $output = '';
        $selected = '';
        $location_list = '';
        $country_div = '';
        $region_div = '';
        $city_div = '';
        $onchange = '';
        $what_is_current_location = geodir_what_is_current_location();
        $what_is_current_location_div = $what_is_current_location . '_div';
        if ($what_is_current_location != '') {
            ${$what_is_current_location_div} = 'gd-tab-active';
        } else {
            $what_is_current_location = apply_filters('geodir_location_switcher_default_tab', 'city');
            $what_is_current_location_div = $what_is_current_location . '_div';
            ${$what_is_current_location_div} = 'gd-tab-active';
        }
        $location_value = '';
        if ($autoredirect === '0') {
        } else {
            $location_value = geodir_get_location_link('base');
            $onchange = ' onchange="window.location.href=this.value" ';
            $autoredirect = '1';
        }
        $base_location = geodir_get_location_link('base');
        $current_location_array = array();
        $selected = '';
        $country_val = '';
        $region_val = '';
        $city_val = '';
        $country_val = geodir_get_current_location(array('what' => 'country', 'echo' => false));
        $region_val = geodir_get_current_location(array('what' => 'region', 'echo' => false));
        $city_val = geodir_get_current_location(array('what' => 'city', 'echo' => false));
        $item_set_selected = false;
        $output .= '<div class="geodir_location_tab_container" >';
        $output .= '<dl class="geodir_location_tabs_head">';
        if (get_option('geodir_enable_country') != 'default') {
            $output .= '<dd data-location="country" class="geodir_location_tabs ' . $country_div . '" ><a href="javascript:void(0)">' . __('Country', GEODIRLOCATION_TEXTDOMAIN) . '</a></dd>';
        }
        if (get_option('geodir_enable_region') != 'default') {
            $output .= '<dd data-location="region" class="geodir_location_tabs ' . $region_div . '" ><a href="javascript:void(0)">' . __('Region', GEODIRLOCATION_TEXTDOMAIN) . '</a></dd>';
        }
        if (get_option('geodir_enable_city') != 'default') {
            $output .= '<dd data-location="city" class="geodir_location_tabs ' . $city_div . ' " ><a href="javascript:void(0)">' . __('City', GEODIRLOCATION_TEXTDOMAIN) . '</a></dd>';
        }
        $output .= '</dl>';
        $output .= '<input type="hidden" class="selected_location" value="city" /><div style="clear:both;"></div>';
        $output .= '<div class="geodir_location_sugestion">';
        $output .= '<select class="geodir_location_switcher_chosen" name="gd_location" data-placeholder="' . __('Please wait..&hellip;', GEODIRLOCATION_TEXTDOMAIN) . '" data-addSearchTermOnNorecord="' . $addSearchTermOnNorecord . '" data-autoredirect="' . $autoredirect . '" ' . $onchange . ' data-showeverywhere="1" >';
        $location_switcher_list_mode = get_option('geodir_location_switcher_list_mode');
        if (empty($location_switcher_list_mode)) {
            $location_switcher_list_mode = 'drill';
        }
        if ($location_switcher_list_mode == 'drill') {
            $args = array('what' => $what_is_current_location, 'country_val' => strtolower($what_is_current_location) == 'region' || strtolower($what_is_current_location) == 'city' ? $country_val : '', 'region_val' => strtolower($what_is_current_location) == 'city' ? $region_val : '', 'echo' => false, 'no_of_records' => '5', 'format' => array('type' => 'array'));
        } else {
            $args = array('what' => $what_is_current_location, 'echo' => false, 'no_of_records' => '5', 'format' => array('type' => 'array'));
        }
        if ($what_is_current_location == 'country' && $country_val != '') {
            $args_current_location = array('what' => $what_is_current_location, 'country_val' => $country_val, 'compare_operator' => '=', 'no_of_records' => '1', 'echo' => false, 'format' => array('type' => 'array'));
            $current_location_array = geodir_get_location_array($args_current_location, $switcher);
        }
        if ($what_is_current_location == 'region' && $region_val != '') {
            $args_current_location = array('what' => $what_is_current_location, 'country_val' => $country_val, 'region_val' => $region_val, 'compare_operator' => '=', 'no_of_records' => '1', 'echo' => false, 'format' => array('type' => 'array'));
            $current_location_array = geodir_get_location_array($args_current_location, $switcher);
        }
        if ($what_is_current_location == 'city' && $city_val != '') {
            $args_current_location = array('what' => $what_is_current_location, 'country_val' => $country_val, 'region_val' => $region_val, 'city_val' => $city_val, 'compare_operator' => '=', 'no_of_records' => '1', 'echo' => false, 'format' => array('type' => 'array'));
            $current_location_array = geodir_get_location_array($args_current_location, $switcher);
        }
        $location_array = geodir_get_location_array($args, $switcher);
        // get country val in case of country search to get selected option
        if (get_option('geodir_everywhere_in_' . $what_is_current_location . '_dropdown')) {
            $output .= '<option value="' . $base_location . '">' . __('Everywhere', GEODIRLOCATION_TEXTDOMAIN) . '</option>';
        }
        $selected = '';
        if (!empty($location_array)) {
            foreach ($location_array as $locations) {
                $selected = '';
                $with_parent = isset($locations->label) ? true : false;
                switch ($what_is_current_location) {
                    case 'country':
                        if (strtolower($country_val) == strtolower($locations->country)) {
                            $selected = 'selected="selected"';
                        }
                        $locations->country = __($locations->country, GEODIRECTORY_TEXTDOMAIN);
                        break;
                    case 'region':
                        $country_iso2 = geodir_location_get_iso2($country_val);
                        $country_iso2 = $country_iso2 != '' ? $country_iso2 : $country_val;
                        $with_parent = $with_parent && strtolower($region_val . ', ' . $country_iso2) == strtolower($locations->label) ? true : false;
                        if (strtolower($region_val) == strtolower($locations->region) || $with_parent) {
                            $selected = 'selected="selected"';
                        }
                        break;
                    case 'city':
                        $with_parent = $with_parent && strtolower($city_val . ', ' . $region_val) == strtolower($locations->label) ? true : false;
                        if (strtolower($city_val) == strtolower($locations->city) || $with_parent) {
                            $selected = 'selected="selected"';
                        }
                        break;
                }
                $output .= '<option value="' . geodir_location_permalink_url($base_location . $locations->location_link) . '" ' . $selected . '>' . ucwords($locations->{$what_is_current_location}) . '</option>';
                if (!$item_set_selected && $selected != '') {
                    $item_set_selected = true;
                }
            }
        }
        if (!empty($current_location_array) && !$item_set_selected) {
            foreach ($current_location_array as $current_location) {
                $selected = '';
                $with_parent = isset($current_location->label) ? true : false;
                switch ($what_is_current_location) {
                    case 'country':
                        if (strtolower($country_val) == strtolower($current_location->country)) {
                            $selected = 'selected="selected"';
                        }
                        $current_location->country = __($current_location->country, GEODIRECTORY_TEXTDOMAIN);
                        break;
                    case 'region':
                        $country_iso2 = geodir_location_get_iso2($country_val);
                        $country_iso2 = $country_iso2 != '' ? $country_iso2 : $country_val;
                        $with_parent = $with_parent && strtolower($region_val . ', ' . $country_iso2) == strtolower($current_location->label) ? true : false;
                        if (strtolower($region_val) == strtolower($current_location->region) || $with_parent) {
                            $selected = 'selected="selected"';
                        }
                        break;
                    case 'city':
                        $with_parent = $with_parent && strtolower($city_val . ', ' . $region_val) == strtolower($current_location->label) ? true : false;
                        if (strtolower($city_val) == strtolower($current_location->city) || $with_parent) {
                            $selected = 'selected="selected"';
                        }
                        break;
                }
                $output .= '<option value="' . geodir_location_permalink_url($base_location . $current_location->location_link) . '" ' . $selected . '>' . ucwords($current_location->{$what_is_current_location}) . '</option>';
            }
        }
        $output .= '</select>';
        $output .= "</div>";
        $output .= '</div>';
        if ($echo) {
            echo $output;
        } else {
            return $output;
        }
    }
}
function offcanvas_right()
{
    the_widget('gdf_welcome_loginwidget');
    // Adds Login & Search Widget
    echo '<h3 class="widget-title">Search Site</h3>';
    if (class_exists('geodir_advance_search_widget')) {
        the_widget('geodir_advance_search_widget', 'mobile-search-widget', '');
    }
    // Adds Location Switcher
    $items = '';
    $current_location = geodir_get_current_location(array('echo' => false));
    if (empty($current_location)) {
        $current_location = 'Everywhere';
    }
    $current_location_link = geodir_get_location_link();
    $items .= '<li id="menu-item-gd-location-switcher" class="menu-item menu-item-type-social menu-item-type-social gd-location-switcher">';
    $items .= '<h3 class="widget-title">Change Location</h3>';
    $items .= '<a href="' . $current_location_link . '"><i class="fa fa-map-marker"></i> Current Location - ' . $current_location . '</a>';
    $items .= '<ul class="sub-menu">';
    $items .= '<li class="menu-item gd-location-switcher-menu-item">';
    $args = array('echo' => false, 'addSearchTermOnNorecord' => 0, 'autoredirect' => true);
    $items .= geodir_location_tab_switcher($args);
    $items .= '</li>';
    $items .= '</ul>';
    $items .= '</li>';
    return $items;
}