$(document).ready(function() {

    var url_string = window.location;
    var url = new URL(url_string);
    var id = url.searchParams.get("id");

    // fetch color
    var color = $.ajax({
        url: "./assets/database/fetch_data_chart.php",
        dataType: "json",
        data: {
            type: 'fetchColor'
        },
        async: false
    }).responseText;
    var x = color.slice(2, -2);
    var arrColor = JSON.parse(x.replace(/\\/g, ""));

    const INC_color = arrColor[0];
    const BJP_color = arrColor[1];
    const AAP_color = arrColor[2];
    const Others_color = arrColor[3];

    const State_color = arrColor[4];
    const MLA_work_color = arrColor[5];
    const MLA_image_color = arrColor[6];


    // set chart colors 2
    Highcharts.setOptions({
        colors: [INC_color, BJP_color, AAP_color, Others_color]
    });


    // fetch inclination chart
    var inclinstionPieChartJsonData = $.ajax({
        url: "./assets/database/fetch_data_chart.php?id=" + id,
        dataType: "json",
        data: {
            type: 'inclinstionPieChart'
        },
        async: false
    }).responseText;
    inclinstionPieChartJsonData = JSON.parse(inclinstionPieChartJsonData);

    // inclination chart
    const inclinationChart = Highcharts.chart('inclinationChartContainer', {
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: '',
            align: 'left'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        accessibility: {
            point: {
                valueSuffix: '%'
            }
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                }
            }
        },
        series: [{
            name: 'Percentage',
            colorByPoint: true,
            sliced: false,
            selected: true,
            data: JSON.parse(convertInclinationData(inclinstionPieChartJsonData))
        }]
    });

    // convert inclination data
    function convertInclinationData(arr) {
        let result = [];

        Object.entries(arr).forEach(([key, index]) => {
            let d = parseFloat(arr[key]);
            let t = { name: `${key}`, y: d };

            return result.push(t);;
        });

        return JSON.stringify(result);
    }






    // fetch age group data 
    var agegroupJsonData = $.ajax({
        url: "./assets/database/fetch_data_table.php",
        dataType: "json",
        data: {
            table: 'agegroup_data',
            id: id
        },
        async: false
    }).responseText;
    agegroupJsonData = JSON.parse(agegroupJsonData);


    // age group chart 
    var chart = Highcharts.chart('trendsAgeGroupDataTable', {
        chart: {
            type: 'column',
            height: 500,
            options3d: {
                enabled: true,
                alpha: 5,
                beta: 10,
                viewDistance: 45,
                depth: 100
            }
        },
        title: {
            text: '',
        },
        series: JSON.parse(chartData(agegroupJsonData)),

        xAxis: {
            categories: ['18-22', '23-30', '31-45', '46-60', '60+'],
            labels: {
                skew3d: true,
            }
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Vote Percentage',
                skew3d: true,
            },
        },
        tooltip: {
            pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
            shared: true
        },
        plotOptions: {
            column: {
                stacking: 'percent',
                depth: 100,
                dataLabels: {
                    enabled: true,
                    format: '{point.percentage:.1f} %'
                }
            }
        },
    });

    // convert age group data
    function chartData(agegroupJsonData) {

        let inc = { name: 'INC', data: [] };
        let bjp = { name: 'BJP', data: [] };
        let aap = { name: 'AAP', data: [] };
        let others = { name: 'Others', data: [] };
        JSON.stringify(agegroupJsonData.map((agegroupJsonData) => {

            inc['data'].push(parseFloat(agegroupJsonData['INC']));
            bjp['data'].push(parseFloat(agegroupJsonData['BJP']));
            aap['data'].push(parseFloat(agegroupJsonData['AAP']));
            others['data'].push(parseFloat(agegroupJsonData['Others']));

            return null;
        }), null, 2);

        let result = [];
        result.push(inc);
        result.push(bjp);
        result.push(aap);
        result.push(others);

        return JSON.stringify(result);
    }






    // fetch ratings data 
    var q1JsonData = $.ajax({
        url: "./assets/database/fetch_data_chart.php?id=" + id,
        dataType: "json",
        data: {
            type: 'ratingBarChartQ1'
        },
        async: false
    }).responseText;
    q1JsonData = JSON.parse(q1JsonData);

    var q2JsonData = $.ajax({
        url: "./assets/database/fetch_data_chart.php?id=" + id,
        dataType: "json",
        data: {
            type: 'ratingBarChartQ2'
        },
        async: false
    }).responseText;
    q2JsonData = JSON.parse(q2JsonData);

    var q3JsonData = $.ajax({
        url: "./assets/database/fetch_data_chart.php?id=" + id,
        dataType: "json",
        data: {
            type: 'ratingBarChartQ3'
        },
        async: false
    }).responseText;
    q3JsonData = JSON.parse(q3JsonData);

    Highcharts.setOptions({
        colors: [State_color, MLA_work_color, MLA_image_color]
    });

    // ratings chart
    var chart = Highcharts.chart('ratings-charts', {
        title: {
            text: '',
        },
        series: JSON.parse(ratingChartData(agegroupJsonData)),

        xAxis: {
            categories: ['0-2', '3-4', '5-6', '7-8', '9-10'],
            title: {
                text: 'Ratings'
            }

        },
        yAxis: {
            title: {
                text: 'Percentage'
            }
        },
        tooltip: {
            pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
            shared: true
        },
        legend: {
            layout: 'horizontal',
            align: 'center',
            verticalAlign: 'bottom'
        },
        plotOptions: {
            series: {
                label: {
                    connectorAllowed: false
                },
            }
        },
        responsive: {
            rules: [{
                condition: {
                    maxWidth: 500
                },
                chartOptions: {
                    legend: {
                        layout: 'horizontal',
                        align: 'center',
                        verticalAlign: 'bottom'
                    }
                }
            }]
        }

    });

    // convert ratings data 
    function ratingChartData() {

        let State = { name: 'State', data: [] };
        let MLA_work = { name: 'MLA Work', data: [] };
        let MLA_image = { name: 'MLA Image', data: [] };

        JSON.stringify(q1JsonData.map((q1JsonData) => {

            State['data'].push(parseFloat(q1JsonData['total_per']));
            return null;

        }), null, 2);
        JSON.stringify(q2JsonData.map((q2JsonData) => {

            MLA_work['data'].push(parseFloat(q2JsonData['total_per']));
            return null;

        }), null, 2);
        JSON.stringify(q3JsonData.map((q3JsonData) => {

            MLA_image['data'].push(parseFloat(q3JsonData['total_per']));

            return null;
        }), null, 2);

        let result = [];
        result.push(State);
        result.push(MLA_work);
        result.push(MLA_image);

        return JSON.stringify(result);
    }


    Highcharts.setOptions({
        colors: [INC_color, AAP_color, BJP_color]
    });

    // fetch gender data 
    // ... 

    // gender chart 
    var chart = Highcharts.chart('gender-charts', {
        chart: {
            type: 'pie'
        },

        xAxis: {
            categories: ['INC', 'AAP', 'BJP'],
            title: {
                text: 'percentage'
            }

        },
        title: {
            text: 'GENDER PREFERENCE'
        },
        tooltip: {
            enabled: false
        },
        series: [{
            name: 'Male',
            innerSize: 175,
            size: 200,
            data: [
                ['Male, INC, <br>41%', 41],
                ['Male, AAP, <br>33%', 33],
                ['Male, BJP, <br>26%', 26],
            ]
        }, {
            name: 'Female',
            innerSize: 150,
            size: 175,
            data: [
                ['Female, INC, <br>45%', 45],
                ['Female, AAP, <br>31%', 31],
                ['Female, BJP, <br>24%', 24]
            ],
            dataLabels: {
                color: '#000',
                distance: -50
            }
        }]
    });

    // convert gender data
    // ... 



    var partyChart = Highcharts.chart('party-charts', {
        title: {
            text: 'WHICH PARTY WORKERS MORE ACTIVE ?'
        },
        colors: [BJP_color, INC_color, AAP_color],

        xAxis: {
            categories: ['BJP', 'INC', 'AAP']
        },
        yAxis: {
            min: 0,
            title: {
                text: ''
            }
        },
        legend: {
            enabled: false
        },
        tooltip: {
            enabled: false
        },
        series: [{
            data: [24.5, 40.7, 30.7],
            type: 'column',
            colorByPoint: true,
            dataLabels: {
                enabled: true,
                color: '#FFFFFF',
                align: 'center',
                format: '{point.y:.1f}%', // one decimal
                style: {
                    fontSize: '13px',
                    fontFamily: 'Verdana, sans-serif'
                }
            }
        }]
    });



})