/**
 * @package     VP Prime Framework
 *
 * @author      Abhishek Das <info@virtueplanet.com>
 * @link        https://www.virtueplanet.com
 * @copyright   Copyright (C) 2023-2025 Virtueplanet Services LLP. All Rights Reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

var Joomla = window.Joomla || {};
var Minicart = window.Minicart || {};

(function ($, app, Joomla, document) {
    app.ajaxPool = {};
    app.activeModule = null;
    app.activeModuleId = 0;

    app.update = function (module) {
        var poolKey = 'update-' + module.id;
        var systemPaths = Joomla.getOptions('system.paths');

        if (app.ajaxPool.hasOwnProperty(poolKey) && app.ajaxPool[poolKey].readystate != 4) {
            app.ajaxPool[poolKey].abort();
        }

        var urlParams = {
            'option': 'com_ajax',
            'format': 'json',
            'module': 'vpprime_minicart',
            'id': module.id,
            'aid': app.activeModuleId,
            'Itemid': module.itemid
        };

        if (typeof Virtuemart === 'object' && typeof Virtuemart.vmLangTag === 'string') {
            urlParams['lang'] = Virtuemart.vmLangTag;
        }

        if (module.token) {
            urlParams['token'] = module.token;
            urlParams[module.token] = 1;
        }

        app.ajaxPool[poolKey] = $.ajax({
            dataType: 'JSON',
            type: 'GET',
            cache: false,
            url: systemPaths.base + '/index.php',
            data: urlParams,
            beforeSend: function () {
                app.showLoader();
            },
            success: function (data) {
                if (!data.html) {
                    return false;
                }

                if (typeof data.html === 'string') {
                    data.html = $.parseHTML(data.html);
                }

                var html = $(data.html).filter(module.selector).html();

                if (!html) {
                    html = data.html;
                }

                $(module.selector).html(html);

                app.removeLoader();

                $(document).trigger('vpprimeMinicartUpdated', [data.html]);

                if (app.activeModule) {
                    var moduleOffcanvas = $(app.activeModule).find('.offcanvas.show');

                    if (moduleOffcanvas.length) {
                        $('body').css('padding-right', '');
                        $('body').css('padding-left', '');
                        $('body').css('overflow', '');

                        var bsOffcanvas = new bootstrap.Offcanvas(moduleOffcanvas[0]);
                        bsOffcanvas.show();
                    }
                }

                app.activeModule = null;
                app.activeModuleId = 0;
            },
            error: function () {
                app.removeLoader();
                app.activeModule = null;
                app.activeModuleId = 0;
            }
        });
    }

    app.remove = function (productId, itemid, reload, token) {
        var poolKey = 'remove-' + productId;
        var systemPaths = Joomla.getOptions('system.paths');

        if (app.ajaxPool.hasOwnProperty(poolKey) && app.ajaxPool[poolKey].readystate != 4) {
            app.ajaxPool[poolKey].abort();
        }

        // Get unix timestamp
        var time = new Date();

        app.ajaxPool[poolKey] = $.ajax({
            dataType: 'JSON',
            type: 'POST',
            cache: false,
            url: systemPaths.base + '/index.php?option=com_ajax&format=json&module=vpprime_minicart&_' + time.getTime() + '=1',
            data: {
                'option': 'com_ajax',
                'format': 'json',
                'module': 'vpprime_minicart',
                'method': 'removeProduct',
                'cart_product_id': productId,
                'Itemid': itemid,
                'token': token,
                [token]: 1
            },
            beforeSend: function () {
                app.showLoader();
            },
            success: function (data) {
                if (reload) {
                    window.location.reload();
                    return false;
                }

                if (!data.error) {
                    $(document).trigger('updateVirtueMartCartModule');
                }
            },
            error: function () {
                app.removeLoader();
            }
        });
    }

    app.showLoader = function () {
        $('.mod-minicart__contents').each(function () {
            if (!$(this).find('.mod-loader').length) {
                $('.mod-minicart__contents').append($('<div></div>').addClass('mod-loader'));
            }
        })
    }

    app.removeLoader = function () {
        $('.mod-minicart__contents').find('.mod-loader').remove();
    }

    $(document).on('updateVirtueMartCartModule', function () {
        var modules = Joomla.getOptions('vpprime.minicart', []);

        modules.forEach(function (module) {
            app.update(module);
        })
    });

    $(function () {
        var modules = Joomla.getOptions('vpprime.minicart', []);

        modules.forEach(function (module) {
            if (module.delayedLoading) {
                setTimeout(function () {
                    app.update(module);
                }, 50);
            }
        })

        $(document).on('click', function (event) {
            var removedBtnSelector = '[data-vpprime-minicart="remove"]';

            if (event.target && ($(event.target).is(removedBtnSelector) || $(event.target).closest(removedBtnSelector).length)) {
                event.preventDefault();

                var btn = $(event.target).is(removedBtnSelector) ? $(event.target) : $(event.target).closest(removedBtnSelector);

                app.activeModule = btn.data('vpprime-minicart-active');
                app.activeModuleId = btn.data('vpprime-minicart-mid');

                var modules = Joomla.getOptions('vpprime.minicart', []);
                var token = '';
                var reload = false;

                modules.forEach(function (module) {
                    if (module.id == app.activeModuleId) {
                        token = module.token;

                        if (module.reloadPage) {
                            reload = true;
                        }
                    }
                })

                app.remove(btn.data('vpprime-minicart-pkey'), btn.data('vpprime-minicart-itemid'), reload, token);
            }
        })
    })

})(jQuery, Minicart, Joomla, document);