
jQuery(document).ready(function ($) {
    function loadLocations($placeholder, productId) {

        $.ajax({
            url: wcmlim_ajax.ajax_url,
            method: "POST",
            dataType: "json", // Ensure JSON response
            data: {
                action: "wcmlim_load_locations_data",
                product_id: productId,
                security: wcmlim_ajax.security,
            },
            success: function (response) {

                if (response.success) {
                    $placeholder.html(response.data.html);
                } else {
                    console.error("Server Error:", response.data.message);
                    $placeholder.html(
                        '<mark class="error">Error: ' + response.data.message + "</mark>"
                    );
                }
            },
            error: function (xhr, status, error) {
                $placeholder.html('<mark class="error">Error loading data</mark>');
            },
        });
    }

    // Load locations for each placeholder
    $('.wcmlim-locations-placeholder').each(function () {
        const $placeholder = $(this);
        const productId = $placeholder.data('product-id');
        loadLocations($placeholder, productId);
    });

    // Show the "Save" button on input focus
    $(document).on('focus', '.wcmlim-stock-input', function () {
        const $button = $(this).siblings('.wcmlim-edit-stock-button');
        $button.fadeIn();
    });

    // Hide the "Save" button on blur if the value is unchanged
    $(document).on('blur', '.wcmlim-stock-input', function () {
        const $input = $(this);
        const $button = $input.siblings('.wcmlim-edit-stock-button');
        if ($input.data('initial-value') === $input.val()) {
            $button.fadeOut();
        }
    });
    

    // Handle stock editing
    $(document).on('click', '.wcmlim-edit-stock-button', function () {
        const $button = $(this);
        const productId = $button.data('product-id');
        const locationId = $button.data('location-id');
        const newStock = $button.siblings('.wcmlim-stock-input').val();

        $.ajax({
            url: wcmlim_ajax.ajax_url,
            method: 'POST',
            data: {
                action: 'wcmlim_update_stock_data',
                product_id: productId,
                location_id: locationId,
                new_stock: newStock,
                security: wcmlim_ajax.security,
            },
            success: function (response) {
                if (response.success) {
                    $button.siblings('.wcmlim-stock-display').text(newStock);
                } else {
                    alert('Error: ' + response.data.message);
                }
            },
            error: function (xhr, status, error) {
                alert('Error updating stock.');
                console.error('AJAX Error:', status, error);
            },
        });
    });

  

});


