<?php
/**
 * Distance Utility Class for WooCommerce Multi-Locations Inventory Management
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * WCMLIM_Distance_Util class
 */
class WCMLIM_Distance_Util {
    
    /**
     * Calculate distance between two coordinates using Haversine formula
     *
     * @param float $lat1 First point latitude
     * @param float $lng1 First point longitude
     * @param float $lat2 Second point latitude
     * @param float $lng2 Second point longitude
     * @param string $unit 'km' or 'mi' for kilometers or miles
     * @return float Distance in specified unit
     */
    public static function calculate_distance($lat1, $lng1, $lat2, $lng2, $unit = 'km') {
        // Convert degrees to radians
        $lat1 = deg2rad(floatval($lat1));
        $lng1 = deg2rad(floatval($lng1));
        $lat2 = deg2rad(floatval($lat2));
        $lng2 = deg2rad(floatval($lng2));
        
        // Haversine formula
        $dlat = $lat2 - $lat1;
        $dlng = $lng2 - $lng1;
        $a = sin($dlat/2) * sin($dlat/2) + cos($lat1) * cos($lat2) * sin($dlng/2) * sin($dlng/2);
        $c = 2 * atan2(sqrt($a), sqrt(1-$a));
        
        // Earth's radius in kilometers
        $r = 6371;
        
        // Calculate distance
        $distance = $r * $c;
        
        // Convert to miles if needed
        if ($unit == 'mi') {
            $distance = $distance * 0.621371;
        }
        
        return $distance;
    }
    
    /**
     * Check if a location is within specified radius of a point
     *
     * @param float $user_lat User's latitude
     * @param float $user_lng User's longitude
     * @param float $loc_lat Location's latitude
     * @param float $loc_lng Location's longitude
     * @param float $radius Radius to check against
     * @param string $unit 'km' or 'mi' for kilometers or miles
     * @return boolean Whether location is within radius
     */
    public static function is_within_radius($user_lat, $user_lng, $loc_lat, $loc_lng, $radius, $unit = 'km') {
        $distance = self::calculate_distance($user_lat, $user_lng, $loc_lat, $loc_lng, $unit);
        return $distance <= floatval($radius);
    }
}
