// CUSTOM PLUGINS TO SHOW THE DATA LABELS IN CHARTS

let sales = [];
let profit = [];
let months = [];
let prevsales = [];
let prevprofit = [];
let prevmonths = [];
let churnReason = [];
let lostSales = [];
let oppByPack = [];
let avgByPack = [];
let tableData = [];
let finalTable = "";
let quarter = "";
let activeElement = "";
var year;


function getChurnData() {
    const card = document.getElementById("churnReason");
    if (!card) return console.log("churnReason card not found");
    handleCardClick({ target: card });
}





// PERFORMING SPECIFIC ACTIVITIES ONCE THE CONTENT IS FULLY LOADED
document.addEventListener("DOMContentLoaded", function () {
    const input = document.getElementById('dateToday');
    input.value = new Date().toISOString().split('T')[0];
    year = new Date().toISOString().split('-')[0];
    input.addEventListener('focus', () => input.blur());
    input.addEventListener('click', function () {
        input.blur();
        if (this.showPicker) {
            this.showPicker();
        }
    });
    chartLoader();
});

// QUERY SELECTOR WITH CLICK EVENT TO ENSURE BUTTON TOGGLE FEATURE
document.querySelectorAll(".quarterSelect button").forEach(button => {
    button.addEventListener("click", () => {
        document.querySelectorAll(".quarterSelect button").forEach(btn => {
            if (btn != button) {
                btn.classList.remove("active");
            }
        });
        button.classList.toggle("active");
        makeTable(tableData);
        setTimeout(()=>{
            const activeButtons = document.querySelector(".quarterSelect button.active");
            if(!activeButtons){
                document.getElementById('specialCase1').classList.toggle('half-span');
                document.getElementById('specialCase1').classList.toggle('full-span');
                document.getElementById('specialCase2').classList.toggle('half-span');
                document.getElementById('specialCase2').classList.toggle('full-span');
            }
            else{
                document.getElementById('specialCase1').classList.add('half-span');
                document.getElementById('specialCase1').classList.remove('full-span');
                document.getElementById('specialCase2').classList.add('half-span');
                document.getElementById('specialCase2').classList.remove('full-span');
            }
        },2000)
    });
});

const chartRegistry = {};


// BUILDING CHARTS WHEN THE SCRIPT LOADS
function chartLoader() {
    initChart('salesAndProfitByMarket')
    initChart('prevSalesAndProfitByMarket')
    initChart('churnReasons')
    initChart('mainChart')
}

function makeTable(tableData) {
    if (tableData) {
        for (i = 0; i < tableData.length; i++) {
            finalTable += "<tr><td>" + tableData[i]['Stage'] + "</td>";
            finalTable += "<td>" + tableData[i]['Opportunity_Name'] + "</td>";
            finalTable += "<td>" + tableData[i]['Sum of Opportunity_id'] + "</td>";
            finalTable += "<td>" + tableData[i]['Comment'] + "</td>";
            finalTable += "<td>" + tableData[i]['package'] + "</td></tr>";
        }
        document.getElementById('dataBody').innerHTML = finalTable;
        finalTable = "";
    }
    else {
        document.getElementById('dataBody').innerHTML = '<tr><td colspan = "9"> No Data Found For <b id = "emptyQuarter">' + document.getElementsByClassName('active')[0].textContent + '</b></td></tr>';
    }
}

function getData() {
    document.getElementById('preloader').classList.remove('fade-out');
    setTimeout(() => {
        getDataValues();
    }, 500);
}

function getDataValues() {
    quarter = "";
    activeElement = document.getElementsByClassName('active');
    let currentYear = document.getElementById('currentYear').value;
    if (activeElement.length > 0) {
        quarter = parseInt(activeElement[0].value);
    }
    fetch('it_sales.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            quarter: quarter,
            currentYear: currentYear
        })
    })
        .then(response => response.json())
        .then(data => {
            sales = data['TOTAL_SALES'];
            profit = data['TOTAL_PROFIT'];
            months = data['MONTHS'];
            prevsales = data['PREV_TOTAL_SALES'];
            prevprofit = data['PREV_TOTAL_PROFIT'];
            prevmonths = data['PREV_MONTHS'];
            churnReason = data['churnReasons'];
            lostSales = data['lostSales'];
            oppByPack = data['oppByPack'];
            avgByPack = data['avgByPack'];
            tableData = data['tableData'];
            if(months.length<prevmonths.length){
                months = prevmonths;
                for(i=0; i<prevmonths.length; i++){
                    months[i] = prevmonths[i].replace(prevmonths[i].slice(-4),(parseInt(prevmonths[i].slice(-4)))+1);
                }
            }

            let average_purchase_value = (data['WON_PURCHASE_VALUE'] / data['TOTAL_WON_OPPORTUNITIES']).toFixed(2);
            document.getElementById('current_opportunities').innerHTML = data['CURRENT_OPPORTUNITIES'];
            document.getElementById('current_purchase_value').innerHTML = "₹ " + converter(data['CURRENT_PURCHASE_VALUE']);
            document.getElementById('average_purchase_value').innerHTML = "₹ " + converter(average_purchase_value);
            document.getElementById('win_rate').innerHTML = (data['TOTAL_WON_OPPORTUNITIES'] / data['TOTAL_ENTRIES'] * 100).toFixed(2) + " %";
            document.getElementById('lost_opportunities').innerHTML = data['LOST_OPPORTUNITIES'];
            document.getElementById('lost_purchases').innerHTML = "₹ " + converter(data['LOST_PURCHASE_VALUE']);
            document.getElementById('churn_rate').innerHTML = (data['TOTAL_LOST_ENTRIES'] / data['TOTAL_ENTRIES'] * 100).toFixed(2) + " %";
            makeTable(tableData);


            chartLoader();
            document.getElementById('preloader').classList.add('fade-out');
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

function converter(a) {
    if (a > 99999) {
        return (a / 100000).toFixed(2) + " L";
    }
    else if (a > 999) {
        return (a / 1000).toFixed(2) + " K";
    }
    else {
        return a;
    }
}