/*-------- START for chart ---------*/
// Fetch and render chart on load
$(document).ready(function() {
    setTimeout(function () {
        fetchAndRenderChart();
    },400);
});

var compact = 0;
var collapse = false;
var colors =
    [
        "#FF5733",
        "#33FF57",
        "#3357FF",
        "#FF33A1",
        "#FFD700",
        "#800080",
        "#00CED1",
        "#467d05",
        "#00cc6a",
        "#10893e",
    ]
const statusColors = {
    active: "#008000",     // Dark Green
    deleted: "#343A40",    // Dark Gray
    suspended: "#B35C00",  // Dark Orange
    abandoned: "#8B0000",  // Dark Red
    lockout: "#004085"     // Dark Blue
};

function collapseAndFit() {
    chart.collapseAll()  // Collapse all nodes
        .fit();         // Fit the chart to the container

    setTimeout(() => { // Get current zoom level
        chart.zoomOut(); // Zoom out by 20%
    }, 500);
}

// Function to fetch JSON data and render chart
function fetchAndRenderChart(loadUpline='No') {
    $("#chart-container").html('');

    var status =  $('#status').val();
    var rank =  $('#rank').val();
    var tsv =  $('#tsv').val();
    var exclude =  $('#exclude_user').val();
    var searchid = $('#member_searchid').val();

    if ($("#encryptedUserId").length){
        searchid = $('#encryptedUserId').val();
        status = ['active'];
        tsv = '999';
        rank = [5];
    }

    var url = baseURL + "member/my-team/network-chart/data";

    const postData = {
        loadUpline,
        status,
        tsv,
        exclude,
        rank,
        searchid
    };


    fetch(url,{
        method: 'POST', // Use POST method
        headers: {
            'Content-Type': 'application/json', // Specifies that we're sending JSON data
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        body: JSON.stringify(postData), // Convert the data to JSON
    }) // Replace with your API URL
        .then(response => response.json())
        .then(data => {
            // console.log('data', data.data)

            if (data.data.length != 0) {
                var requiredData = data.data.map(item => ({
                    "parentId": item.parentid === 0 ? null : item.parentid,
                    ...item
                }));

                chart = new d3.OrgChart()
                    .container('#chart-container')
                    .data(requiredData)
                    .nodeWidth(d => 260)
                    .nodeHeight(d => 150)
                    .initialZoom(0.5)
                    .childrenMargin(d => 40)
                    .compactMarginBetween(d => 30)
                    .compactMarginPair(d => 80)
                    .compact(!!(compact++%2))
                    .linkUpdate(function(d, i, arr) {
                        d3.select(this)
                            .attr("stroke", "gray")  // Change stroke color
                            .attr("stroke-width", 1); // Adjust thickness
                    })
                    .nodeContent(function (d) {
                         var redirectUrl = baseURL + 'member/my-team/member-detail/'+d.data.redirect_id;
                        return `
                    <div style="background-color:none; height:${d.height}px; border-radius:2px; overflow:visible; text-align:center;">
                      <div style="height:${d.height}px; background-color:white; border:1px solid lightgray;">
                        <div style="padding:10px; text-align:center; color: white; background-color: ${colors[d.data.rank]};display: flex; justify-content: space-between; align-items: center;">
                          <span style="flex: 1; text-align: left;">${d.data.rank}</span>
                          <span style="flex: 1;">${d.data.id}</span>
                          <span style="flex: 1; text-align: right;">${d.data.tsv}</span>
                        </div>
                        <div style="padding:10px; color:white; background-color: ${statusColors[d.data.status]}; font-size:16px;font-weight:bold;display: flex; justify-content: space-between; align-items: center;">
                          <span style="flex: 1; text-align: left;">${d.data.status}</span>
                          <span style="flex: 1; text-align: right;"><a href="${redirectUrl}" class="text-white" target="_blank">${d.data.username}</a></span>
                        </div>
                        <div style="padding:10px; padding-top:10px;text-align:center">
                          <div style="color:#404040;font-size:16px;margin-top:4px"> ${d.data.name} </div>
                          <div style="color:#404040;font-size:16px;margin-top:4px"><b>Reg:</b>${d.data.date}|<b>Login:</b>${d.data.last_login}</div>
                        </div>
                      </div>
                    </div>
                    `;
                    })
                    .render()
                    .expandAll() // Expand all nodes by default
                    .fit();
            } else {
                $("#chart-container").html('<h4 class="text-center mt-2 text-muted fw-bold py-3">No Record Found</h4>');
            }

            setTimeout(function () {
                $("#loader-chart").hide();
            },400);

        })
        .catch(error => console.error('Error fetching data:', error));
}
/*-------- END for chart ---------*/
