/**
 * WooCommerce Multi-Locations Inventory Management - Auto Detect Location
 * Uses IP geolocation to automatically determine user's location and set the closest store
 */

const { ajaxurl } = multi_inventory;

jQuery(document).ready(function ($) {
    // Check if location cookies exist
    var autodetect_wcmlim_nearby_location = getCookie("autodetect_independent_wcmlim_nearby_location");
    var selected_location = getCookie("wcmlim_selected_location_termid");
    var get_user_ip = getCookie("wcmlim_user_ip") ?? false;

    // Only detect location if cookies aren't set
    if ((autodetect_wcmlim_nearby_location === "" || selected_location === "") && (get_user_ip === false || get_user_ip === "")) {  
        DetectLocationByIP();
    }
});

/**
 * Main function to detect user location via IP and set closest store
 */
var DetectLocationByIP = (function () {
    var getLocationFromIP = function () {
        // Get location data from ipinfo.io API
        jQuery.ajax({
            url: 'https://ipinfo.io/json?token=' + wcmlim_ipinfo.ipinfo_api_token,
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                setcookie("wcmlim_user_ip", response['ip']);
                // Set the autodetect location cookie
                if (typeof setcookie === 'function') {
                    setcookie("autodetect_independent_wcmlim_nearby_location", response['loc']);
                } else {
                    document.cookie = "autodetect_independent_wcmlim_nearby_location=" + response['loc'] + "; path=/";
                }

                // Parse coordinates from response
                var loc = response['loc'].split(',');
                var lat = loc[0];
                var lng = loc[1];

                // Find closest store location based on coordinates
                jQuery.ajax({
                    url: ajaxurl,
                    type: "post",
                    data: {
                        lat: lat,
                        lng: lng,
                        action: "wcmlim_closest_location",
                    },
                    dataType: "json",
                    success: function (response) {
                        // Save location preferences in cookies
                        setcookie("wcmlim_selected_location", response.loc_key);
                        setcookie("wcmlim_selected_location_termid", response.loc_term_id);
                        setcookie("wcmlim_user_lat", lat);
                        setcookie("wcmlim_user_lng", lng);
                        setcookie("wcmlim_selected_location_regid", response.secgrouploc);

                        // Store location priority order
                        setcookie("wcmlim_location_priority_order_by_user_loc", response.sorted_by_proximity);

                        // Reload the page to apply location changes
                        window.location.reload();
                    },
                    error: function (xhr, status, error) {
                        console.error("Error fetching closest location:", error);
                    }
                });
            },
            error: function (xhr, status, error) {
                console.error("Error fetching location data from IPInfo:", error);
            }
        });
    };

    return function () {
        getLocationFromIP();
    };
})();

/**
 * Helper function to get cookie value by name
 */
function getCookie(cname) {
    let name = cname + "=";
    let ca = document.cookie.split(";");
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == " ") {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

/**
 * Helper function to set cookie with optional expiration days
 */
function setcookie(name, value, days) {
    let date = new Date();
    if (days) {
        date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
        var expires = `; expires=${date.toUTCString()}`;
    } else {
        date.setTime(date.getTime() + 1 * 24 * 60 * 60 * 1000);
        var expires = `; expires=${date.toUTCString()}`; // Default: 1 day expiration
    }
    document.cookie = `${name}=${value}${expires};path=/`;
}