<?php

/**
 * Calculate distance between two geographic points using the Haversine formula
 *
 * @param float $lat1 User latitude
 * @param float $lng1 User longitude
 * @param float $lat2 Location latitude
 * @param float $lng2 Location longitude
 * @param string $unit Unit of measurement ('km' or 'miles')
 * @return mixed Distance in specified unit or 'N/A' if coordinates are missing
 */
function wcmlim_calculate_distance($lat1, $lng1, $lat2, $lng2, $unit = 'km') {
    // Check if any coordinates are missing or invalid
    if (empty($lat1) || empty($lng1) || empty($lat2) || empty($lng2)) {
        return 'N/A';
    }
    
    $earthRadius = ($unit == 'miles') ? 3959 : 6371; // Radius of the earth in km or miles
    
    $latDelta = deg2rad($lat2 - $lat1);
    $lngDelta = deg2rad($lng2 - $lng1);
    
    $a = sin($latDelta/2) * sin($latDelta/2) +
         cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * 
         sin($lngDelta/2) * sin($lngDelta/2);
         
    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    $distance = $earthRadius * $c;
    
    return round($distance, 2);
}

/**
 * Get the distance to a location from the user's position
 *
 * @param int $location_term_id The term ID of the location
 * @return string Formatted distance with unit or 'N/A' if not available
 */
function wcmlim_get_distance_to_location($location_term_id) {
   
 
    
    // Get user coordinates from cookies
    $user_lat = isset($_COOKIE['wcmlim_user_lat']) ? floatval($_COOKIE['wcmlim_user_lat']) : null;
    $user_lng = isset($_COOKIE['wcmlim_user_lng']) ? floatval($_COOKIE['wcmlim_user_lng']) : null;
    
    // Get location coordinates from term meta
    $location_lat = get_term_meta($location_term_id, 'wcmlim_lat', true);
    $location_lng = get_term_meta($location_term_id, 'wcmlim_lng', true);


 
    
    // Get distance unit from settings (default to km)
    $unit = get_option('wcmlim_location_distance_unit', 'km');
    
    $distance = wcmlim_calculate_distance($user_lat, $user_lng, $location_lat, $location_lng, $unit);
    
    if ($distance === 'N/A') {
        return 'N/A';
    } else {
        return $distance . ' ' . $unit;
    }
}

?>