Subversion Repositories SmartDukaan

Rev

Rev 36452 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

$(document).ready(function () {
    $(document).on('change', 'select.criteria-brands', function () {
        changed = true;
    });
    $(document).on('click', ".scheme_offer", function () {
        loadOffer("main-content");
    });
    $(document).on('click', '#yearmonth-submit', function () {
        let yearMonth = $("#yearmonth").val();
        loadOfferHistory('#main-content', yearMonth);

    });

    $(document).on('click', 'a.mk_partner_view', function () {
        let $offerTr = $(this).closest('tr');
        let offerId = $offerTr.data('offerid');
        if (typeof (offerId) == "undefined") {
            offerId = $(this).closest('th').data('offerid');
            let idx = $(this).closest('th').data('idx');
            priceCircularTable.order([[parseInt(idx), 'desc']]).draw();
        }
        doGetAjaxRequestHandler(`${context}/getOfferMargins?offerId=${offerId}`, function (data) {
            $('#offerDescription .modal-content').html(data);
            $("#offerDescription").modal('show');
        });
    });

    $(document).on('click', 'a.mk_offer_detail', function () {
        let $offerTr = $(this).closest('tr');
        let offerId = $offerTr.data('offerid');
        doGetAjaxRequestHandler(`${context}/getOfferMargins?offerId=${offerId}`, function (data) {
            $('#offerDescription .modal-content').html(data);
            $("#offerDescription").modal('show');
        });
    });
    $(document).on('click', 'a.offer_history', function () {
        let dt = new Date();
        loadOfferHistory('#main-content', new Date().toISOString().slice(0, 7));
    });
    $(document).on('click', 'input.create-offer', function () {
        console.log("Click called");
        createOfferNew();
    });

    $(document).on('click', 'a.process_offer', function () {
        let $offerTr = $(this).closest('tr');
        let offerId = $offerTr.data('offerid');
        let $clicked = $(this);
        if (confirm("Are your sure you want to process?")) {
            $clicked.hide();
            $.ajax({
                url: `${context}/offer/process/${offerId}`,
                type: 'GET',
                success: function () {
                    var now = moment().format("DD/MM/YYYY HH:mm");
                    $offerTr.find('.processed-timestamp').text(now);
                    $clicked.replaceWith('<span style="color:grey;">Processing...</span>');
                },
                error: function (xhr) {
                    var msg = "Failed to process offer";
                    if (xhr.responseJSON && xhr.responseJSON.response && xhr.responseJSON.response.message) {
                        msg = xhr.responseJSON.response.message;
                    }
                    alert(msg);
                    $clicked.show();
                }
            });
        }
    });

    $(document).on('change', 'input[name=schemeType]', function () {
        if ($('input[name=schemeType]').val() == 'ACTIVATION') {
            $("div.activation-brands").show();
        } else {
            $("div.activation-brands").hide();
        }
    });
    $(document).on('change', 'input[name^=amountType]', function () {
        let payoutType = $('input[name=payoutType]:checked').val();
        let holder1 = payoutType == "QUANTITY" ? "Qty" : "Rs.";
        let holder2 = payoutType == "QUANTITY" ? "pc(s) onwards, " : "onwards,";
        let holder3 = "% of value";
        if ($(this).val() == "FIXED") {
            holder3 = "per pc";
        } else if ($(this).val() == "SLAB_FIXED") {
            holder3 = "";
        }
        let slabHtml = `<div class="input-group slab">
                <span class="input-group-addon">${holder1}</span>
                <input  type="text" class="slabOnwardsAmount form-control"  value="0"/>
                <span class="input-group-addon">${holder2}</span>
                <input type="text" class="form-control payoutValue"  value="0"/>
                <span class="input-group-addon">${holder3}</span>
                </div>`;
        $(this).closest('.itemcriteriapayout').find('div.slab-container').html(slabHtml.repeat(15));
    });
});

function changeTargetType() {
    let holder1 = "Rs.";
    let holder2 = "onwards,";
    if ($(this).val() == "QUANTITY") {
        holder1 = "Qty";
        holder2 = "pc(s) onwards, ";
    }
    let targetHtml = `<span class="input-group-addon">${holder1}</span>
                                    <input type="text" style="width:100px" class="form-control payoutTarget" value="0">
                                    <span class="input-group-addon">${holder2}</span>
                                    <input type="text" class="form-control targetDescription" placeholder="Description">`;
    $('div.targetContainer').html(targetHtml);
}

function changePayoutType() {
    let holder1 = "Rs.";
    let holder2 = "onwards,";
    $allSlabContainers = $('div.slab-container');
    $('div.slab-payout input:radio[value="PERCENTAGE"]').prop('checked', true);
    $('div.slab-payout input:radio[value!="PERCENTAGE"]').prop('checked', false).prop('disabled', false);
    if ($(this).val() == "QUANTITY") {
        holder1 = "Qty";
        holder2 = "pc(s) onwards, ";
    }
    let holder3 = "% of value";
    $allSlabContainers.each(function() {
        let slabHtml = `<div class="input-group slab">
                <span class="input-group-addon">${holder1}</span>
                <input  type="text" class="slabOnwardsAmount form-control"  value="0"/>
                <span class="input-group-addon">${holder2}</span>
                <input type="text" class="form-control payoutValue"  value="0"/>
                <span class="input-group-addon">${holder3}</span>
                </div>`;
        $(this).html(slabHtml.repeat(15));
    });
}

$(document).on('click', 'a.mk_offer_active', function () {
    let $clicked = $(this);
    let offerId = $clicked.closest('tr').data("offerid");
    if (confirm(`Are you sure want to activate ${offerId}?`)) {
        doGetAjaxRequestHandler(`${context}/offer/active/${offerId}`, function (response) {
            alert("Offer is now active");
            $clicked.closest("li").html(`<a class="mk_offer_inactive" href="javascript:void(0)">Mark Inactive</a>`);
        });
    }
});
$(document).on('click', 'a.mk_offer_inactive', function () {
    let $clicked = $(this);
    let offerId = $clicked.closest('tr').data("offerid");
    if (confirm(`Are you sure want to deactivate ${offerId}?`)) {
        doGetAjaxRequestHandler(`${context}/offer/active/${offerId}?active=false`, function (response) {
            alert("Offer is now inactive");
            $clicked.closest("li").html(`<a class="mk_offer_active" href="javascript:void(0)">Mark Active</a>`);
        });
    }
});
$(document).on('click', 'a.delete_offer', function () {
    let $clicked = $(this);
    let offerId = $clicked.closest('tr').data("offerid");
    if (confirm(`Are you sure you want to delete offer ${offerId}? This cannot be undone.`)) {
        doDeleteAjaxRequestHandler(`${context}/offer/delete/${offerId}`, function (response) {
            alert("Offer deleted");
            $clicked.closest('tr').remove();
        });
    }
});
$(document).on('click', '#publish-all-btn', function () {
    let yearMonth = $("#yearmonth").val();
    if (!yearMonth) {
        yearMonth = new Date().toISOString().slice(0, 7);
    }
    if (confirm(`Publish all unpublished offers for ${yearMonth}?`)) {
        doPostAjaxRequestHandler(`${context}/offers/publishAll?yearMonth=${yearMonth}`, function (response) {
            alert(response);
            loadOfferHistory('#main-content', yearMonth);
        });
    }
});
$(document).on('click', 'button.slab-add', function () {
    newTargetSlab = $(targetSlabTemplate);
    $('div.targetslabscontainer').append(newTargetSlab);
    newTargetSlab.find("select.criteria-brands").toggle().next().remove();
    newTargetSlab.find("select.criteria-brands").chosen({no_results_text: "Oops, nothing found!"});
});
$(document).on('click', 'button.slab-remove', function () {
    targetSlabContainer = $('div.targetslabscontainer');
    if (targetSlabContainer.find(".targetslabs").length > 1) {
        targetSlabContainer.find(".targetslabs:last").remove();
    } else {
        alert("Cant remove single Slab");
    }
});
$(document).on('click', 'button.slab-copy', function () {
    newTargetSlab = $('div.targetslabs').eq(0).clone().appendTo('div.targetslabscontainer');
    catalogIdSelectContainers = $('div.targetslabs').eq(0).find('select.criteria-catalogids');
    newCatalogIdSelectContainers = newTargetSlab.find('select.criteria-catalogids');
    for (let i = 0; i < 15; i++) {
        let selectContainer = catalogIdSelectContainers.get(i);
        let newSelectContainer = newCatalogIdSelectContainers.get(i);
        for (let j = 0; j < selectContainer.options.length; j++) {
            newSelectContainer.options[j].selected = selectContainer.options[j].selected;
        }
        newSelectContainer.closest('span').replaceWith(newSelectContainer);
        $(newSelectContainer).multiselect({
            includeSelectAllOption: true,
            maxHeight: 400,
            buttonWidth: '240px',
            numberDisplayed: 1,
            nonSelectedText: 'Items',
            nSelectedText: ' - Items Selected',
            allSelectedText: 'All Items Selected',
            enableFiltering: true,
            enableCaseInsensitiveFiltering: true,
        });
    }
    selectContainers = newTargetSlab.find("select.criteria-brands");
    selectContainers.each((y, x) => {
        $next = $(x).toggle().next();
        $next.find("a.search-choice-close").each(function (index, ele) {
            x.options[$(ele).data('option-array-index') + 0].selected = true;
        });
        $next.remove();
    });
    newTargetSlab.find("select.criteria-brands").chosen({no_results_text: "Oops, nothing found!"});
    //createSlabFrom(currentHtml);
});

$(document).on('click', '.scheme_block_imeis_panel', function () {
    reloadBlockImeiPanel();
    $('div.modal-backdrop.fade').remove();


});

$(document).on('click', '.eligible_offer_imeis_panel', function () {
    doGetAjaxRequestHandler(`${context}/offerEligibleImeis/panel`, function (response) {
        $('#main-content').html(response);
    });
    $('div.modal-backdrop.fade').remove();


});


$(document).on('click', '#submit_scheme_block_imeis', function () {
    let blockImei = $('#block_imei_scheme').val();
    console.log("blockImei - ", blockImei);
    if (!blockImei) {
        alert("Please enter Imei");
        return;
    }

    let url = `${context}/createBlockImei?imeiNumbers=${blockImei}`;
    if (confirm('Are you sure to block all enter Imei numbers')) {
        doPostAjaxRequestHandler(url, function (response) {
            if (response) {
                alert("Imei blocked successfully");
                reloadBlockImeiList();
            }
        });
    } else {
        return;
    }

});
$(document).on('click', '#submit_offer_eligible_imeis', function () {
    let eligibleImeis = $('#offer_eligible_imeis').val();
    let offerId = $('#offerId').val();
    console.log("Eligible Imeeis - ", eligibleImeis);
    console.log("offer id - ", offerId);
    if (!offerId) {
        alert("Please enter Offer Id");
        return;
    }
    if (!eligibleImeis) {
        alert("Please enter Imei");
        return;
    }

    let url = `${context}/offerEligibleImeis/create?imeis=${eligibleImeis}&offerId=${offerId}`;
    if (confirm('Are you sure to submit')) {
        doPostAjaxRequestHandler(url, function (response) {
            if (response) {
                reloadOfferEligibleImeisList();
                alert("submited successfully");
            }
        });
    } else {
        return;
    }
});


$(document).on('click', '.scheme_imei_block_unblock_button', function () {
    let blockedImeiId = $(this).val();
    if (confirm("Are you sure to change status")) {
        doPutAjaxRequestHandler(`${context}/blockUnblockImei?id=${blockedImeiId}`, function (response) {
            reloadBlockImeiList();
        });
    } else {
        return;
    }
});

$(document).on('click', '.offer_eligible_imeis_EligibilityChange_button', function () {
    let blockedImeiId = $(this).val();
    if (confirm("Are you sure to change status")) {
        doPutAjaxRequestHandler(`${context}/offerEligibleImeis/changeStatus?id=${blockedImeiId}`, function (response) {
            reloadOfferEligibleImeisList();
            alert("Status changed successfully");
        });
    } else {
        return;
    }
});

$(document).on('click', '.scheme_blocked_imei_remove_button', function () {
    let blockedImeiId = $(this).val();
    if (confirm("Are you sure to remove")) {
        doDeleteAjaxRequestHandler(`${context}/removeBlockedImei?id=${blockedImeiId}`, function (response) {
            if (response) {
                reloadBlockImeiList();
            }
        });
    } else {
        return;
    }


});
$(document).on('click', '.offer_eligible_imei_remove_button', function () {
    let offerId = $(this).val();
    if (confirm("Are you sure to remove")) {
        doDeleteAjaxRequestHandler(`${context}/offerEligibleImeis/deleteByOfferId?offerId=${offerId}`, function (response) {
            if (response) {
                reloadOfferEligibleImeisList();
                alert("Removed successfully");
            }
        });
    } else {
        return;
    }
});

function reloadBlockImeiPanel() {
    doGetAjaxRequestHandler(`${context}/blockImeiPanel`, function (response) {
        $('#main-content').html(response);
    });
    // $('div.modal-backdrop.fade').remove();
}
function reloadBlockImeiOfferPanel() {
    doGetAjaxRequestHandler(`${context}/blockImeiOfferPanel`, function (response) {
        $('#main-content').html(response);
    });
    $('div.modal-backdrop.fade').remove();
}

function reloadBlockImeiList() {
    doGetAjaxRequestHandler(`${context}/blockImeiList`, function (response) {
        $('#scheme_blocked_imeis_div').empty();
        $('#scheme_blocked_imeis_div').html(response);
    });
}

function reloadOfferEligibleImeisList() {
    doGetAjaxRequestHandler(`${context}/offerEligibleImeis/allList`, function (response) {
        $('#offer_eligible_imeis_div').empty();
        $('#offer_eligible_imeis_div').html(response);

    });
}

$(document).on('click', 'select.criteria-catalogids+div > button', function () {
    if (changed) {
        let brands = $(this).closest('.item-criteria').find('select').val();
        let led = $(this).closest('.item-criteria').find('input[name=led]').is(":checked");
        let tablet = $(this).closest('.item-criteria').find('input[name=tablet]').is(":checked");
        let smartWatch = $(this).closest('.item-criteria').find('input[name=smartwatch]').is(":checked");
        let openBoxLapTops = $(this).closest('.item-criteria').find('input[name=openboxlaptops]').is(":checked");
        $brandsContainer = $(this);
        let categoryId = 3;
        if (led) {
            categoryId = 14202;
        }
        if (tablet) {
            categoryId = 10010;
        }
        if (smartWatch) {
            categoryId = 6;
        }

        if (openBoxLapTops) {
            categoryId = 6;
        }
        var url = `${context}/entity?brands=${brands.join(",")}&categoryId=${categoryId}&limit=0`;
        $select = $brandsContainer.closest('.item-criteria').find('.criteria-catalogids');
        $select.html('');
        if (brands.length > 0) {
            doGetAjaxRequestHandler(url, function (response) {
                data = JSON.parse(response);
                for (i = 0; i < data.length; i++) {
                    $select.append(`<option value="${data[i].catalogId_i}">${data[i].title_s}</option>`);
                }
                $select.multiselect('rebuild');
            });
        } else {
            $select.html('');
            $select.multiselect('rebuild');
        }
        changed = !changed;
    }
});

var ckEditor;

function createOfferNew() {
    let validated = true;
    if (!$("#offer_reference").val() || $("#offer_reference").val().trim() === '') {
        alert("Reference is required");
        $("#offer_reference").focus();
        return;
    }
    let rangePicker = getDatesFromPicker('input[name="dateRange"]');
    let createOfferRequest = {};
    createOfferRequest['name'] = $("#offer_name").val();
    createOfferRequest['startDate'] = rangePicker.startDate;
    createOfferRequest['endDate'] = rangePicker.endDate;
    createOfferRequest['offerNotes'] = $("#offer_notes").val();
    createOfferRequest['baseCriteria'] = $("input[name=base_criteria]").is(":checked");
    createOfferRequest['terms'] = ckEditor.getData() //$("#offer_terms").val();
    createOfferRequest['targetType'] = $("input[name=targetType]:checked").val();
    createOfferRequest['payoutType'] = $("input[name=payoutType]:checked").val();
    createOfferRequest['schemeType'] = $("select[name=schemeType]").val();
    createOfferRequest['booster'] = false;
    createOfferRequest['activationBrands'] = null;
    createOfferRequest['discount'] = $("input[name=discount]").is(':checked');
    createOfferRequest['reference'] = $("#offer_reference").val();
    if (createOfferRequest['schemeType'] == 'ACTIVATION') {
        createOfferRequest['activationBrands'] = $("div.activation-brands select").val().join(",") || null;
    } else if (createOfferRequest['schemeType'] == 'SELLINBOOSTER') {
        createOfferRequest['schemeType'] = 'SELLIN';
        createOfferRequest['booster'] = true;
    }
    createOfferRequest['sellinPercentage'] = $("#sellinPercentage").val();
    createOfferRequest['brandShareTerms'] = $('#brandShare').val();
    createOfferRequest['partnerCriteria'] = {};
    createOfferRequest['partnerCriteria']['fofoIds'] = ($("#partners").val() || []).map(Number);
    createOfferRequest['partnerCriteria']['excludeFofoIds'] = [];
    let excludeFofoIdChecked = $('input.excludeFofoId').is(':checked');
    if (excludeFofoIdChecked) {
        createOfferRequest['partnerCriteria']['excludeFofoIds'] = createOfferRequest['partnerCriteria']['fofoIds'];
        createOfferRequest['partnerCriteria']['fofoIds'] = [];
    }
    createOfferRequest['partnerCriteria']['partnerTypes'] = ($("select.criteria-partner-type").val() || []);
    createOfferRequest['partnerCriteria']['regionIds'] = ($("select.criteria-warehouseregion").val() || []).map(Number);

    createOfferRequest['itemCriteria'] = itemCriteria($('div.itemCriteria'));
    let targetSlabs = [];
    $('div.targetslabs').each(function (index, ele) {
        let $targetSlab = $(ele);
        let targetOnwardsValue = $targetSlab.find('.payoutTarget').val();
        let targetDescription = $targetSlab.find('.targetDescription').val();
        let itemCriteriaPayouts = [];
        if (isNaN(targetOnwardsValue) || targetOnwardsValue < 0) {
            validated = false;
            alert(`Invalid Number - ${targetOnwardsValue}`);
        } else {
            if (index == 0 || targetOnwardsValue > 0) {
                let $itemCriteriaPayoutContainers = $targetSlab.find('.itemcriteriapayout');
                $itemCriteriaPayoutContainers.each(function (index, itemCriteriaPayoutContainer) {
                    let $itemCriteriaPayoutContainer = $(itemCriteriaPayoutContainer);
                    let amountType = $itemCriteriaPayoutContainer.find('input[name^=amountType]:checked').val();
                    let startDate = $itemCriteriaPayoutContainer.find('input.startDate').val();
                    let endDate = $itemCriteriaPayoutContainer.find('input.endDate').val();
                    if ((startDate == "" && endDate != "") && (startDate != "" && endDate == "")) {
                        alert("Criteria specific date is required");
                        return false;
                    }
                    let payoutSlabs = [];
                    let itemCriteria1 = itemCriteria($itemCriteriaPayoutContainer);
                    let $payoutSlabContainers = $itemCriteriaPayoutContainer.find('.slab');
                    let itemCriteriaChanged = itemCriteria1['smartPhone'] || itemCriteria1['featuredPhone']
                        || itemCriteria1['catalogIds'].length > 0 || itemCriteria1['brands'].length > 0
                        || itemCriteria1['excludeCatalogIds'].length > 0
                        || itemCriteria1['startPrice'] > 0 || itemCriteria1['endPrice'] > itemCriteria1['startPrice'] > 0;
                    if (itemCriteriaChanged || index == 0) {
                        $payoutSlabContainers.each(function (slabContainerIndex, slabContainer) {
                            let $slab = $(slabContainer);

                            let slabOnwardsAmount = $slab.find('.slabOnwardsAmount').val();
                            if (isNaN(slabOnwardsAmount) || slabOnwardsAmount < 0) {
                                validated = false;
                                alert(`Invalid Payout Slab Amount - ${slabOnwardsAmount}`);
                            } else {
                                if (slabContainerIndex == 0 || slabOnwardsAmount > 0) {
                                    let payoutAmount = $slab.find('.payoutValue').val();
                                    if (isNaN(payoutAmount) || payoutAmount <= 0) {
                                        validated = false;
                                        alert(`Invalid Payout Slab Amount - ${slabOnwardsAmount}`);
                                    }
                                    let payoutSlab = {
                                        onwardsAmount: Number(slabOnwardsAmount),
                                        payoutAmount: Number(payoutAmount)
                                    }
                                    payoutSlabs.push(payoutSlab);
                                }
                            }
                        });
                        let itemCriteriaPayout = {
                            itemCriteria: itemCriteria1,
                            payoutSlabs: payoutSlabs,
                            amountType: amountType,
                            startDate: jsonStartDate(startDate),
                            endDate: jsonEndDate(endDate)
                        };
                        itemCriteriaPayouts.push(itemCriteriaPayout);
                    }
                });
                targetSlabs.push({
                    onwardsAmount: targetOnwardsValue,
                    targetDescription: targetDescription,
                    itemCriteriaPayouts: itemCriteriaPayouts
                });
            }
        }
    });
    createOfferRequest['targetSlabs'] = targetSlabs;
    if (validated && confirm("Confirm creating scheme offer")) {
        console.log("Validated");
        console.log(createOfferRequest);
        doPostAjaxRequestWithJsonHandler(`${context}/createOffer`, JSON.stringify(createOfferRequest), function (response) {
            alert("Offer created successfully");
            let dt = new Date();
            loadOfferHistory('#main-content', new Date().toISOString().slice(0, 7));
        });
    } else {
        console.log("Invalid Offer");
    }
}

function itemCriteria($container) {
    let smartPhone = $container.find("input[name=smartphone]").is(":checked");
    let featuredPhone = $container.find("input[name=featuredphone]").is(":checked");
    let led = $container.find("input[name=led]").is(":checked");
    let smartWatch = $container.find("input[name=smartwatch]").is(":checked");
    let catalogIds = $container.find('.criteria-catalogids').val() || [];
    let excludeCatalogIds = [];
    let excludeChecked = $container.find('input.exclude').is(':checked');
    if (excludeChecked) {
        excludeCatalogIds = catalogIds;
        catalogIds = [];
    }
    let brands = $container.find('.criteria-brands').val() || [];
    return {
        startPrice: Number($container.find('.startValue').val()),
        endPrice: Number($container.find('.endValue').val()),
        catalogIds: catalogIds.map(Number),
        excludeCatalogIds: excludeCatalogIds.map(Number),
        brands: brands,
        smartPhone: smartPhone,
        featuredPhone: featuredPhone,
        smartWatch: smartWatch,
        led: led
    };
}

function loadOffer(domId) {
    console.log(domId);
    doGetAjaxRequestHandler(context + "/getCreateOffer", function (response) {
        $('#' + domId).html(response);

        DecoupledEditor
            .create(document.querySelector('#offer_terms'))


            .then(newEditor => {
                const toolbarContainer = document.querySelector('#toolbar-container');

                toolbarContainer.appendChild(newEditor.ui.view.toolbar.element);

                ckEditor = newEditor
            })
            .catch(error => {
                console.error(error);
            });

    });
}

function loadOfferHistory(domId, yearMonth) {
    doGetAjaxRequestHandler(`${context}/offerHistory?yearMonth=${yearMonth}`, function (response) {
        $(domId).html(response);
        $(domId).find("#yearmonth").val(yearMonth);
    });
}

// ===== Offer Partner & Target Management =====

// Manage Partners - open modal
$(document).on('click', 'a.manage_offer_partners', function () {
    let offerId = $(this).closest('tr').data('offerid');
    doGetAjaxRequestHandler(`${context}/offer/partners?offerId=${offerId}`, function (data) {
        $('#offerDescription .modal-content').html(data);
        $("#offerDescription").modal('show');
    });
});

// Select All checkbox
$(document).on('change', '#select-all-partners', function () {
    $('.partner-checkbox').prop('checked', $(this).is(':checked'));
});

// Remove Selected Partners - show options
$(document).on('click', '.remove-selected-partners', function () {
    let checked = $('.partner-checkbox:checked');
    if (checked.length === 0) {
        alert("Please select at least one partner to remove.");
        return;
    }
    $('#remove-options').show();
});

// Cancel remove
$(document).on('click', '.cancel-remove-partners', function () {
    $('#remove-options').hide();
    $('#create-new-offer-checkbox').prop('checked', false);
    $('#custom-targets-section').hide();
});

// Toggle custom targets section
$(document).on('change', '#create-new-offer-checkbox', function () {
    if ($(this).is(':checked')) {
        $('#custom-targets-section').show();
    } else {
        $('#custom-targets-section').hide();
    }
});

// Confirm Remove Partners
$(document).on('click', '.confirm-remove-partners', function () {
    let offerId = $('#offer-partners-table').data('offerid');
    let fofoIds = [];
    $('.partner-checkbox:checked').each(function () {
        fofoIds.push($(this).val());
    });
    let createNewOffer = $('#create-new-offer-checkbox').is(':checked');
    let targets = [];
    if (createNewOffer) {
        $('.new-offer-target').each(function () {
            targets.push($(this).val());
        });
    }

    let url = `${context}/offer/removePartners?offerId=${offerId}&fofoIds=${fofoIds.join(',')}`;
    url += `&createNewOffer=${createNewOffer}`;
    if (createNewOffer && targets.length > 0) {
        url += `&targets=${targets.join(',')}`;
    }

    if (confirm("Are you sure you want to remove " + fofoIds.length + " partner(s) from this offer?")) {
        doPostAjaxRequestHandler(url, function (response) {
            let data = typeof response === 'string' ? JSON.parse(response) : response;
            alert(data.message || "Partners removed successfully.");
            $('#offerDescription').modal('hide');
            let yearMonth = data.yearMonth || $("#yearmonth").val() || new Date().toISOString().slice(0, 7);
            loadOfferHistory('#main-content', yearMonth);
        });
    }
});

// Add Partners
$(document).on('click', '.add-selected-partners', function () {
    let offerId = $('#offer-partners-table').data('offerid');
    if (!offerId) {
        offerId = $(this).closest('.modal-body').find('[data-offerid]').data('offerid');
    }
    let selectedFofoIds = $('#add-partner-select').val();
    if (!selectedFofoIds || selectedFofoIds.length === 0) {
        alert("Please select at least one partner to add.");
        return;
    }

    let url = `${context}/offer/addPartners?offerId=${offerId}&fofoIds=${selectedFofoIds.join(',')}`;
    if (confirm("Add " + selectedFofoIds.length + " partner(s) to Offer #" + offerId + "?")) {
        doPostAjaxRequestHandler(url, function (response) {
            let data = typeof response === 'string' ? JSON.parse(response) : response;
            alert(data.message || "Partners added successfully.");
            // Reload the modal to show updated partner list
            doGetAjaxRequestHandler(`${context}/offer/partners?offerId=${offerId}`, function (modalData) {
                $('#offerDescription .modal-content').html(modalData);
            });
        });
    }
});

// Update Offer Targets & Payouts (per slab)
$(document).on('click', '.update-offer-slabs', function () {
    let offerId = $('#edit-slabs-table').data('offerid');
    let slabs = [];

    $('#edit-slabs-table tbody tr').each(function () {
        let $target = $(this).find('.edit-slab-target');
        let $payout = $(this).find('.edit-slab-payout');
        if ($target.length) {
            slabs.push({
                id: parseInt($target.data('slabid')),
                payoutTarget: parseInt($target.val()),
                payoutValue: parseFloat($payout.val())
            });
        }
    });

    if (slabs.length === 0) {
        alert("No slabs to update.");
        return;
    }

    if (confirm("Update targets & payouts for Offer #" + offerId + "?")) {
        $.ajax({
            url: context + '/offer/updateSlabs',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ offerId: offerId, slabs: slabs }),
            success: function (response) {
                alert("Targets & payouts updated for Offer #" + offerId + ".");
                $('#offerDescription').modal('hide');
                let yearMonth = $("#yearmonth").val() || new Date().toISOString().slice(0, 7);
                loadOfferHistory('#main-content', yearMonth);
            },
            error: function (xhr) {
                alert("Failed to update: " + (xhr.responseJSON ? xhr.responseJSON.statusMessage : xhr.statusText));
            }
        });
    }
});