$('.select2').each(function () {
    var $select = $(this);

    // Check if the element is inside a modal
    if ($select.closest('.modal').length > 0) {
        // Re-initialize Select2 with dropdownParent set to the modal
        $select.select2({
            dropdownParent: $select.closest('.modal')
        });
    }
});

$('#assign_ids').select2({
    dropdownParent: $('#todoModal'),
    placeholder: 'Select Members',
    width: '100%' // Ensures correct width and alignment
});

$('#label').select2({
    tags: true,
    multiple: true, // allow multiple selections
    tokenSeparators: [','], // optional: allows comma or space to create tag
    dropdownParent: $('#todoModal'),
    width: '100%',
    placeholder: 'Add Labels'
});
// dashboard/infinity-star-bonus-sum
getInfinityStarBonusSum();
$(document).on('change','#infinityStarBonusMonth',function () {
    getInfinityStarBonusSum($(this).val());
});

$(document).ready(function (){
    $(document).on("change","#is_assign_to_someone",function (){
       var isAssignToSomeone = $(this).val();

        $(".assignTodoDiv").hide();
       if (isAssignToSomeone == 'Yes'){
           $(".assignTodoDiv").show();
       }
    });
})

function getInfinityStarBonusSum(year_month=null) {
    $.ajax({
        url: baseURL+'member/dashboard/infinity-star-bonus-sum',
        type: 'POST',
        data: {
            'year_month' : year_month,
        },
        dataType: 'json',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        beforeSend: function () {

        },
        success: function (response) {
            $("#isb_wtsv_total").text(response.data.wtsv_total || 0);
            $("#isb_wtsvGreaterLeg_total").text(response.data.wtsvGreaterLeg_total || 0);
            $("#isb_wtsvOtherLegs_total").text(response.data.wtsvOtherLegs_total || 0);
            $("#myBvs_total").text(response.data.myBvs_total || 0);
        },
        error: function (errorResponse) {

        }
    });
}

/*-------- START for chart --------*/
var options = {
    series: [],
    colors: ["#1c3750"],
    chart: {
        type: 'bar',
        height: 362,
        toolbar: {
            show: false
        }
    },
    dataLabels: {
        enabled: false
    },
    xaxis: {
        categories: ['1', '2', '3', '4'],
    },
    fill: {
        opacity: 1
    },
    tooltip: {
        custom: function({ series, seriesIndex, dataPointIndex, w }) {
            var data = w.globals.series[seriesIndex][dataPointIndex];
            return '<div class="apexcharts-tooltip-title">Week : ' + w.globals.labels[dataPointIndex] + '</div>' +
                '<div class="fw-bold px-2 mb-1"> Value : ' + data + '</div>';
        }
    },
    title: {
        text: 'Week',
        floating: false,
        offsetY: 345,
        align: 'center',
    },
    yaxis: {
        labels: {
            formatter: function (value) {
                // Remove decimal if it's .0
                return value % 1 === 0 ? value : value.toFixed(1);
            }
        }
    },
    noData: {
        text: "No Data Found",
        align: "center",
        verticalAlign: "middle",
        offsetX: 0,
        offsetY: 10,
        style: {
            color: "#7c8088",
            fontSize: '18px',
        }
    },
};

var chartStarRank = new ApexCharts(document.querySelector("#chartStarRank"), options);
chartStarRank.render();

var chartUniLevel = new ApexCharts(document.querySelector("#chartUniLevel"), options);
chartUniLevel.render();

var chartMatchingBounce = new ApexCharts(document.querySelector("#chartMatchingBounce"), options);
chartMatchingBounce.render();

var chartCustomerAcquisitionBonus = new ApexCharts(document.querySelector("#chartCustomerAcquisitionBonus"), options);
chartCustomerAcquisitionBonus.render();

getChartData();
$(document).on('change','#month',function () {
    var tab = $("#chartDiv .nav-link.active").data('chart');
    getChartData($(this).val(),tab);
});

$(document).on('click','#chartDiv .nav-link',function () {
    var tab = $(this).data('chart');
    getChartData($("#month").val(),tab);
});

function getChartData(year_month=null,tab='chartStarRank') {
    var chartDiv = $('#chartDiv .chart');
    var chartLoader = $('#chartDiv #chart-loader');
    $.ajax({
        url: baseURL+'member/dashboard/chart-data',
        type: 'POST',
        data: {
            'year_month' : year_month,
            'tab' : tab,
        },
        dataType: 'json',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        beforeSend: function () {
            // Show the loader before sending the request
            chartLoader.show();
            chartDiv.hide();
        },
        success: function (response) {
            chartLoader.hide();
            chartDiv.show();

            var data = response.data;
            if (tab == 'chartStarRank') {
                chartStarRank.updateOptions({
                    xaxis: {
                        categories: data.week
                    },
                    series: [{
                        data: data.infinityStar,
                    }],
                });
            } else if (tab == 'chartUniLevel') {
                chartUniLevel.updateOptions({
                    xaxis: {
                        categories: data.week
                    },
                    series:[{
                        data: data.uniLevel,
                    }],
                });
            } else if (tab == 'chartMatchingBounce') {
                chartMatchingBounce.updateOptions({
                    xaxis: {
                        categories: data.week
                    },
                    series:[{
                        data: data.matchingBounce,
                    }],
                });
            } else if (tab == 'chartCustomerAcquisitionBonus') {
                chartCustomerAcquisitionBonus.updateOptions({
                    xaxis: {
                        categories: data.week
                    },
                    series:[{
                        data: data.customerAcquisitionBonus,
                    }],
                });
            }
        },
        error: function (errorResponse) {
            chartLoader.hide();
            chartDiv.show();
        }
    });
}

var monthlyBonusChartOptions = {
    series: [],
    chart: {
        height: 400,
        type: 'donut'
    },
    labels: ['Infinity Star Bonus', 'Uni Level Commission', 'Matching Bonus', 'Customer Acquisition Bonus'],
    fill: {
        opacity: 1
    },
    stroke: {
        width: 1,
        colors: ['#fff']
    },
    yaxis: {
        show: false
    },
    legend: {
        position: 'bottom'
    },
    colors: ['#1E90FF', '#00BFFF', '#87CEEB', '#4682B4', '#5F9EA0'],
    theme: {
        monochrome: {
            enabled: false // Disable monochrome to apply the colors
        }
    },noData: {
        text: "No Data Found",
        align: "center",
        verticalAlign: "middle",
        offsetX: 0,
        offsetY: 0,
        style: {
            color: "#7c8088",
            fontSize: '18px',
        }
    },
};

var monthlyBonusChart = new ApexCharts(document.querySelector("#monthlyBonusChart"), monthlyBonusChartOptions);
monthlyBonusChart.render();


getMonthlyBonusChartData();
$(document).on('change','#monthlyBonusChartMonth',function () {
    getMonthlyBonusChartData($(this).val());
});

function getMonthlyBonusChartData(year_month=null) {
    var chartDiv = $('#monthlyBonusChartDiv .chart');
    var chartLoader = $('#monthlyBonusChartDiv #chart-loader');
    $.ajax({
        url: baseURL+'member/dashboard/chart-data/monthly-bonus',
        type: 'POST',
        data: {
            'year_month' : year_month,
        },
        dataType: 'json',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        beforeSend: function () {
            chartLoader.show();
            chartDiv.hide();
        },
        success: function (response) {
            chartLoader.hide();
            chartDiv.show();

            var data = response.data;
            var numbersArray = data.map(function(item) {
                return parseFloat(item);
            });

            monthlyBonusChart.updateOptions({
                series: numbersArray,
            });
        },
        error: function (errorResponse) {
            chartLoader.hide();
            chartDiv.show();
        }
    });
}
