<?php
if ( ! function_exists( 'wpj_get_distance_to_job_location' ) ) {
	function wpj_get_distance_to_job_location( $type, $id ) {
		if ( $type == 'post' || $type == 'job' || $type == 'request' ) {
			$lat = get_post_meta( $id, 'lat', true );
			$lng = get_post_meta( $id, 'long', true );

		} elseif ( $type == 'user' ) {
			$lat = get_user_meta( $id, 'wpj_user_latitude', true );
			$lng = get_user_meta( $id, 'wpj_user_longitude', true );

		} else return false;

		$q_lat = WPJ_Form::get( 'latitude', WPJ_Form::cookie( 'wpj_lat', '' ) );
		$q_lng = WPJ_Form::get( 'longitude', WPJ_Form::cookie( 'wpj_lng', '' ) );

		if ( ! $q_lat || ! $q_lng ) return false;

		if ( false !== $distance = wpj_calculate_distance( [$lat, $lng], [$q_lat, $q_lng] ) ) {
			$dec_sep = wpj_get_option( 'wpjobster_decimal_sum_separator' );

			if ( empty( $dec_sep ) ) { $dec_sep = '.'; }

			$tho_sep = wpj_get_option( 'wpjobster_thousands_sum_separator' );

			if ( empty( $tho_sep ) ) { $tho_sep = ','; }

			if ( wpj_get_option( 'wpjobster_locations_unit' ) == 'miles' )
				return sprintf( __( '%s miles away', 'wpjobster' ), number_format( round( $distance, 1 ), 1, $dec_sep, $tho_sep ) );

			else
				return sprintf( __( '%s km away', 'wpjobster' ), number_format( round( $distance, 1 ), 1, $dec_sep, $tho_sep ) );
		}

		return false;
	}
}