/**
* 2007-2024 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    PrestaShop SA <contact@prestashop.com>
*  @copyright 2007-2024 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*
* Don't forget to prefix your containers with your own identifier
* to avoid any conflicts with others containers.
*/
var agileGMap = null;

$(document).ready(function(){
    $('.delivery-options').hide();
    $('.js-display-seller-products').on('click', function (event) {
        event.preventDefault();

        var idSellerinfo = $(this).data('idsellerinfo');
        $('#seller-products-list_' + idSellerinfo).toggle(300);
    });

    if ($('#isCariersAvailable').val() == 0) {
        $('button[type="submit"][name="confirmDeliveryOption"]').attr('disabled', true);
    }

    switchCheckoutCarrier();

    if ($('#checkout-delivery-step.-current').length > 0) {
        initGoogleMap();
    }

    $('#agile_order_carriers').on('change', '.location-carrier', function() {

        update_seller_carrier(+$(this).data('idsellerinfo'), +$('#id_cart_sellershipping').val(), false);
        if (agileGMap) {
            agileGMap.displayCenterMarker(+$(this).val());
        }
    })

    $('#checkout-delivery-step .step-title').on('click', function() {
        initGoogleMap();
    })
});

async function request(ajaxMethodName, requestData = null) {
    return new Promise(function(resolve, reject) {
        $.ajax({
            type: "POST",
            url: ajaxShippingUrl,
            data: {
                action: ajaxMethodName,
                requestData: requestData,
            },
            dataType: "json",
            crossDomain: true,
            async: true,
            success: function (response) {
                resolve(response);
            },
            error: function (xhr, status, error) {
                if (error) {
                    alert(error);
                } else {
                    alert('Server Error: ' + xhr.status);
                }

                reject(error);
            },
        });
    });
}

async function update_seller_carrier(idSellerInfo, idCart, isUpdateLocation = true)
{
    var idCarrierReference = $("#id_carrier_sellershipping_" + idSellerInfo).val();

    if (isUpdateLocation && agileGMap) {
        agileGMap.displayCenterMarker(+$("[name=id_location_carrier_" + idSellerInfo + "]:checked").val());
    }

    requestData = {};
    requestData.idCarrierReference = idCarrierReference;
    requestData.idCart = idCart;
    requestData.idSellerInfo = idSellerInfo;
    requestData.idLocationCarrier = +$("[name=id_location_carrier_" + idSellerInfo + "]:checked").val();

    var result = await request('setSellerCartCarrier', requestData);

    if (result.success == true) {
        switchCheckoutCarrier(idSellerInfo);
        $('#js-delivery input:radio:checked').trigger("change");
    } else {
        alert(result.message);
    }
}

function update_seller_carrier_real(idSellerInfo, idCart)
{
    displayLocationsBySeller(idSellerInfo);
    update_seller_carrier(idSellerInfo, idCart);
}

async function switchCheckoutCarrier(idSellerInfo)
{
    if ($('#id_carrier_sellershipping_'+idSellerInfo).length) {
        var selectedIdCarierReference = $('#id_carrier_sellershipping_'+idSellerInfo).val();

        $('#delivery_option_' + carriersIdsByIdReference[selectedIdCarierReference]).prop('checked', true);
    } else {
        $('#delivery_option_' + carriersIdsByIdReference[defaultIdCarrierReference]).prop('checked', true);
    }
}

async function initGoogleMap() {
    if (
        typeof AgileGMapClass !== 'undefined'
        && typeof agileGmapKey !== 'undefined'
        && agileGmapKey
        && !agileGMap
    ) {
        agileGMap = new AgileGMapClass(agileGmapKey);
        agileGMap.downloadGMap();

        await agileGMap.initMap(
            {lat: 0, lng: 0},
            '',
            5,
            false
        );

        var idCart = +$('#id_cart_sellershipping').val()
        var forNumber = 0;

        for (const idSellerInfo in agileSellersLocation) {
            for (const idCarrierReference in agileSellersLocation[idSellerInfo]) {
                var isDisplayCenter = false;

                if (forNumber == 0) {
                    isDisplayCenter = true;
                }

                addMarkerGoogleMap(idSellerInfo, idCarrierReference, isDisplayCenter);
            }
            update_seller_carrier(idSellerInfo, idCart);
            //displayLocationsBySeller(idSellerInfo);
        }
    }

    for (const idSellerInfo in agileSellersLocation) {
        displayLocationsBySeller(idSellerInfo);
    }
}

function addMarkerGoogleMap(idSellerInfo, idCarrierReference, isDisplayCenter = false) {
    if (agileGMap) {
        if (
            typeof agileSellersLocation != 'undefined'
            && typeof agileSellersLocation[idSellerInfo] != 'undefined'
            && typeof agileSellersLocation[idSellerInfo][idCarrierReference] != 'undefined'
            && agileSellersLocation[idSellerInfo][idCarrierReference].length > 0
        ) {
            var locations = agileSellersLocation[idSellerInfo][idCarrierReference];
            var carrierName = $('#agile_prod_name_' + idSellerInfo).text();

            for (let i = 0; i < locations.length; i++) {
                agileGMap.addMarker(
                    {lat: +locations[i].latitude, lng: +locations[i].longitude},
                    locations[i].location,
                    false,
                    carrierName,
                    +locations[i].idLocationCarrier
                )

                if (isDisplayCenter && i == 0) {
                    agileGMap.displayCenterMarker(+locations[i].idLocationCarrier);
                }
            }

            $('#agile_map').show();
        }
    }
}

function displayLocationsBySeller(idSellerInfo) {
    var idCarrierReference = +$("#id_carrier_sellershipping_" + idSellerInfo).val();
    var $sellerLocations = $('#id_carrier_locations_' + idSellerInfo);
    $sellerLocations.html('');

    if (
        $sellerLocations.length > 0
        && typeof agileSellersLocation != 'undefined'
        && typeof agileSellersLocation[idSellerInfo] != 'undefined'
    ) {
        var locations = agileSellersLocation[idSellerInfo];
        var $sellerLocations = $('#id_carrier_locations_' + idSellerInfo);

        if (agileSellersLocation[idSellerInfo][idCarrierReference].length > 0) {
            $sellerLocations.append(`<p>${selectLocationText}</p>`);
        }

        for (const idCarrier in locations) {
            var locationsCarrier = locations[idCarrier];

            for (let i = 0; i < locationsCarrier.length; i++) {
                var idLocationCarrier = +locationsCarrier[i].idLocationCarrier;

                if (locationsCarrier[i].idCarrierReference == idCarrierReference) {
                    $sellerLocations.append(
                        '<div>' +
                        '<input class="form-control location-carrier" id="location_carrier_' + idLocationCarrier + '" name="id_location_carrier_' + idSellerInfo + '" type="radio" value="' + idLocationCarrier + '" ' + (i == 0 ? "checked" : "") + ' data-idsellerinfo="' + idSellerInfo + '">' +

                        '<label for="location_carrier_' + idLocationCarrier + '">' +
                        '<span>' + locationsCarrier[i].location + '</span>' +
                        '</label>' +
                        '</div>'
                    );

                    if (agileGMap) {
                        agileGMap.showMarkerById(idLocationCarrier);
                    }
                } else {
                    if (agileGMap) {
                        agileGMap.hideMarkerById(idLocationCarrier);
                    }
                }
            }
        }
    }
}
