jQuery(document).ready(function($){
    const enrollWidgetTabs = () => {
        const individualTab = $(".academy-btn-enroll-tab-individual");
        const teamTab = $(".academy-btn-enroll-tab-team");
        const contentIndividual = $(".academy-widget-enroll__content");
        const contentTeam = $(".academy-g-plus-enroll-content-team");
        
        if (individualTab.length == 0 || teamTab.length == 0 || contentIndividual.length == 0 || contentTeam.length == 0 ) {
            return;
        }
        // Initial state: show individual content, hide team content
        contentIndividual.show();
        // contentTeam.hide();
        individualTab.addClass("active");

        function clearActiveTabs() {
            individualTab.removeClass("active");
            teamTab.removeClass("active");
        }

        individualTab.on("click", function () {
            clearActiveTabs();
            individualTab.addClass("active");
            contentTeam.fadeOut();
            contentTeam.hide();
            contentIndividual.fadeIn();
        });

        teamTab.on("click", function () {
            clearActiveTabs();
            teamTab.addClass("active");
            contentIndividual.fadeOut();
            contentIndividual.hide();
            contentTeam.fadeIn();
        });
    },
    loadTeams = function(elm,s){
        $.ajax({
            url: academy_group.ajax_url,
            type: 'POST',
            data: {
                action: 'academy_pro_group_plus/frontend/ecommerce/get_groups',
                _wpnonce: academy_group.nonce,
                search: s,
            },
            success: function(data){
                let options = '';
                data.data.data.forEach(function(g){
                    options += `<option value="${g.id}">${g.name}</option>`;
                });
                $(elm).find('#academy_group_id').html(options)
            },
            error: function(error){
                console.log(error)
            }
        });
    },
    showErrors = function(elm, msg){
        if(msg){
            elm.show();
            elm.text(msg);
            return;
        }
        elm.hide();
        elm.text('');
    },
    academy_errors = $('#academy_errors'),
    academy_messages = $('#academy_messages'),
    academy_group_errors = $('#academy_group_errors'),
    academy_group_name_errors = $('#academy_group_name_errors'),
    academy_group_id_errors = $('#academy_group_id_errors');
    quantity_errors = $('#academy_g_plus_quantity_errors'),
    quantity = $('input[name="quantity"]'),
    group_name = $('#academy_g_plus_group_name'),
    academy_group_id = $('#academy_group_id'),
    type_ = function(element){
            let type;
            element.each(function(index,elm){
                if(elm.checked){
                    type = elm.value;
                }
            });
            return type;
        },
    type_e = $('[name="group_"]'),
    academy_product_id = $('#academy_product_id');
    
    enrollWidgetTabs();
    showErrors(academy_errors, false);
    showErrors(academy_messages, false);
    showErrors(academy_group_errors, false);
    showErrors(academy_group_name_errors, false);
    showErrors(academy_group_id_errors, false);
    showErrors(quantity_errors, false);


    $('#academy-bulk-purchase-from-single-course, #academy-bulk-purchase-from-single-product-page').each(function(index, elm){
        // load teams
        loadTeams(elm,'');
        // search team
        $(elm).find('#academy_group_search').keyup(function(){
            loadTeams(elm,this.value);
        });

        // only for single product page
        if(this.id == 'academy-bulk-purchase-from-single-product-page'){
            $(elm.children[1]).hide();
            $(elm).fadeIn();
        }
        else{
            let price_total = $(elm).find('#academy_g_plus_price_total');
            $(elm).find('#academy_g_plus_quantity').on('input', function(){
                let price = String(elm.dataset.curSym == undefined ? '' : elm.dataset.curSym) + String(elm.dataset.unitPrice * this.value)
                price_total.val(price);
                price_total.text(price);
            })
        }

        $(elm).find('[data-id="new_group"]').first().hide();
        $(elm).find('[data-id="group_existing"]').first().hide();

        // only for single product page
        $(elm).find('#academy_g_plus_bulk_purchase').click(function(){
            if(this.checked){
                 $(this).parent().next().fadeIn();
            }
            else{
                 $(this).parent().next().fadeOut();
            }
           
        });

        $(elm).find('[name="group_"]').click(function(){
            if(this.value == 'new_group'){
                 $(elm).find('[data-id="new_group"]').first().fadeIn();
                 $(elm).find('[data-id="group_existing"]').first().fadeOut();
            }
            else{
                $(elm).find('[data-id="new_group"]').first().fadeOut();
                $(elm).find('[data-id="group_existing"]').first().fadeIn();
            }
           
        });
        $(elm).fadeIn();
    })


    $('[name="add-to-cart"]').click(function(e){

        let procuct_page = $('#academy_g_plus_bulk_purchase');
        if(
            ($('.academy-g-plus-enroll-content-team').length && this.value) ||
            ( procuct_page.length > 0 && !procuct_page[0].checked)
        ) return;
        
        if ( procuct_page.length !== 0 ) {
            e.preventDefault();
        }
        showErrors(academy_errors, false);
        showErrors(academy_messages, false);
        showErrors(academy_group_errors, false);
        showErrors(academy_group_name_errors, false);
        showErrors(academy_group_id_errors, false);
        showErrors(quantity_errors, false);
        // procuct_page: only for single product page
        if(
            procuct_page.length == 0 ||
            procuct_page[0].checked
        ){
            if(procuct_page.length > 0){
                $('[name="add-to-cart"]')[0].disabled = true;
            }
            
            $.ajax({
                url: academy_group.ajax_url,
                type: 'POST',
                data: {
                    action: 'academy_pro_group_plus/frontend/ecommerce/add_to_cart',
                    _wpnonce: academy_group.nonce,
                    product_id: academy_product_id.val(),
                    quantity:   quantity.val(),
                    group_name: group_name.val(),
                    group_id:   academy_group_id.val(),
                    type:       type_(type_e),
                },
                success: function(data){
                    if(procuct_page.length > 0){
                        $('[name="add-to-cart"]')[0].disabled = false;
                    }
                    
                    showErrors(academy_messages, data.data.message);
                    setTimeout(function(){
                        window.location.href = data.data.cart_url;
                    }, 500);
                },
                error: function(error){
                    let data = error.responseJSON.data;
                    data = typeof error.responseJSON.data.errors == 'object' ? error.responseJSON.data.errors : {};
                    if(procuct_page.length > 0){
                        $('[name="add-to-cart"]')[0].disabled = false;
                    }
                    else{
                        showErrors(quantity_errors, typeof data.quantity == 'object' ? data.quantity.join("\n"):'');
                    }
                    
                    showErrors(academy_errors,data.message);
                    showErrors(academy_group_errors,typeof data.type == 'object' ? data.type.join("\n"):'');
                    showErrors(academy_group_name_errors,typeof data.group_name == 'object' ? data.group_name.join("\n"):'');
                    showErrors(academy_group_id_errors,typeof data.group_id == 'object' ? data.group_id.join("\n"):'');
                }
            });
        }
    })
});
    