var editor;
window.onbeforeunload = function() {
    if ($('.trends-edit-button').hasClass('d-none')) {
        return confirm("Are you sure you want to reload the page without saving your changes?");
    }
};
$(document).ready(function() {

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

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


    var printableCasteJsonData = $.ajax({
        url: "./assets/database/fetch_printable_report_data.php",
        dataType: "json",
        data: {
            table: 'caste_data',
            id: id
        },
        async: false
    }).responseText;
    printableCasteJsonData = JSON.parse(printableCasteJsonData);

    var casteTable = $('.caste_table').DataTable({
        responsive: true,
        paging: false,
        ordering: false,
        searching: true,
        info: false,
        "scrollY": false,
        "scrollX": false,
        "autoWidth": false,
        fixedHeader: true,
        pageLength: 10,
        dom: '<"pull-left"f><"pull-right"l>tip',
        data: printableCasteJsonData,
        columns: [
            { title: 'Caste', data: 'caste' },
            { title: 'INC', data: 'INC' },
            { title: 'BJP', data: 'BJP' },
            { title: 'AAP', data: 'AAP' },
            { title: 'Others', data: 'Others' },
        ],
    });


    // caste filter
    // casteJsonData.filter(item => item.caste !== "Others").forEach(e => $("#caste_filter_list ul").append(`<li><label><input name="caste_filter" type="checkbox" value="${e.caste}">${e.caste}</label></li>`))

    // $("input[name='caste_filter']").on("change", changeInFilter);

    // $('#caste_filter_list_icon').click(function() {
    //     $('#caste_filter_list').toggleClass('active');
    // })

    // $('.caste-filter-reset-button').click(function() {
    //     $('.caste_table').DataTable().destroy();
    //     $('.caste_table').DataTable({
    //         responsive: true,
    //         paging: false,
    //         ordering: false,
    //         searching: true,
    //         info: false,
    //         "scrollY": false,
    //         "scrollX": false,
    //         "autoWidth": false,
    //         fixedHeader: true,
    //         pageLength: 10,
    //         dom: '<"pull-left"f><"pull-right"l>tip',
    //         data: casteJsonData,
    //         columns: [
    //             { title: 'Caste', data: 'caste' },
    //             { title: 'INC', data: 'INC' },
    //             { title: 'BJP', data: 'BJP' },
    //             { title: 'AAP', data: 'AAP' },
    //             { title: 'Others', data: 'Others' },
    //         ],
    //     });
    //     $('#caste_filter_list_icon').css({ 'color': 'black' });
    //     $("input[name='caste_filter']").prop('checked', false);
    // })

    // function changeInFilter() {
    //     const inputs = document.querySelectorAll("input[name='caste_filter']:checked");
    //     const remaningInputs = document.querySelectorAll("input[name='caste_filter']:not(:checked)");
    //     const filterItems = [];
    //     const filterItemsRemaining = [];
    //     Array.prototype.forEach.call(inputs, (item) => {
    //         filterItems.push($(item).val());
    //     });
    //     Array.prototype.forEach.call(remaningInputs, (item) => {
    //         filterItemsRemaining.push($(item).val());
    //     });
    //     // console.log(filterItemsRemaining);
    //     // console.log(casteJsonData.filter(item => filterItemsRemaining.includes(item.caste)));
    //     const filteredData = filterItems.length === 0 ? casteJsonData : casteJsonData.filter(item => filterItems.includes(item.caste));
    //     const filteredDataRemaining = filterItems.length !== 0 ? casteJsonData.filter(item => filterItemsRemaining.includes(item.caste)).reduce((curr, acu) => {
    //         return {
    //             caste: 'Others',
    //             INC: parseFloat(curr.INC) + parseFloat(acu.INC),
    //             BJP: parseFloat(curr.BJP) + parseFloat(acu.BJP),
    //             AAP: parseFloat(curr.AAP) + parseFloat(acu.AAP),
    //             Others: parseFloat(curr.Others) + parseFloat(acu.Others),
    //         }
    //     }) : '';
    //     if (filteredDataRemaining != '') {
    //         filteredDataRemaining.INC = parseFloat(filteredDataRemaining.INC / filterItemsRemaining.length).toFixed(1)
    //         filteredDataRemaining.BJP = parseFloat(filteredDataRemaining.BJP / filterItemsRemaining.length).toFixed(1)
    //         filteredDataRemaining.AAP = parseFloat(filteredDataRemaining.AAP / filterItemsRemaining.length).toFixed(1)
    //         filteredDataRemaining.Others = parseFloat(filteredDataRemaining.Others / filterItemsRemaining.length).toFixed(1)
    //         filteredData.push(filteredDataRemaining);
    //     }
    //     console.log(filteredDataRemaining);
    //     filterItems.length === 0 ? $('#caste_filter_list_icon').css({ 'color': 'black' }) : $('#caste_filter_list_icon').css({ 'color': 'blue' });
    //     $('.caste_table').DataTable().destroy();
    //     $('.caste_table').DataTable({
    //         responsive: true,
    //         paging: false,
    //         ordering: false,
    //         searching: true,
    //         info: false,
    //         "scrollY": false,
    //         "scrollX": false,
    //         "autoWidth": false,
    //         fixedHeader: true,
    //         data: filteredData,
    //         dom: '<"pull-left"f><"pull-right"l>tip',
    //         columns: [
    //             { title: 'Caste', data: 'caste' },
    //             { title: 'INC', data: 'INC' },
    //             { title: 'BJP', data: 'BJP' },
    //             { title: 'AAP', data: 'AAP' },
    //             { title: 'Others', data: 'Others' },
    //         ],
    //     });
    // }


    // caste edit
    $('#caste_edit_icon').click(function() {
        var casteJsonData = $.ajax({
            url: "./assets/database/fetch_data_table.php",
            dataType: "json",
            data: {
                table: 'caste_data',
                id: id
            },
            async: false
        }).responseText;
        casteJsonData = JSON.parse(casteJsonData);
        $('.caste_table').DataTable().destroy();
        $('.caste_table thead').empty();
        $('.caste_table tbody').empty();
        $('.caste_table').DataTable({
            responsive: true,
            paging: false,
            ordering: false,
            searching: true,
            info: false,
            "autoWidth": false,
            fixedHeader: true,
            data: casteJsonData,
            dom: '<"pull-left"f><"pull-right"l>tip',
            columns: [
                { title: 'Caste', data: 'caste', width: "30%" },
                { title: 'INC', data: 'INC', width: "17%" },
                { title: 'BJP', data: 'BJP', width: "17%" },
                { title: 'AAP', data: 'AAP', width: "17%" },
                { title: 'Others', data: 'Others', width: "17%" },
                { title: 'checkbox', data: 'status', width: "2%" }

            ],
        });
        $('.caste-filter-reset-button').click();
        $('#caste_edit_icon').addClass('d-none');
        $('#caste_edit_cancel_icon').removeClass('d-none');
        $('#caste_edit_save_icon').removeClass('d-none');
        $('#trendsCasteDataTable td:not(:first-child, :last-child)').each(function(i, o) {
            o.innerHTML = `<input type="number" min="0" max="100" class="caste_trends_edit_input" data-original='${o.innerText}' value='${o.innerText}' />`
        });
        $('#trendsCasteDataTable td:last-child').each(function(i, o) {
            var show = o.innerHTML == 1 ? 'checked="true"' : '';
            console.log(o.innerHTML);
            o.innerHTML = `<input class="caste_trends_checkbox" name="checkbox_caste" type="checkbox" ${show} na />`
        });
        $('#trendsCasteDataTable th:last-child').each(function(i, o) {
            o.innerHTML = `<input id="caste_select_all_checkbox" type="checkbox" />`
        });
        $('#caste_select_all_checkbox').on('click', function() {
            if (this.checked) {
                $('.caste_trends_checkbox:checkbox').prop('checked', true);
            } else {
                $('.caste_trends_checkbox:checkbox').prop('checked', false);
            }
        });

    });

    $('#caste_edit_cancel_icon').click(function() {
        if (confirm('Do you want to discard your changes?') == true) {
            $('.caste_table').DataTable().destroy();
            $('.caste_table thead').empty();
            $('.caste_table tbody').empty();
            $('.caste_table').DataTable({
                responsive: true,
                paging: false,
                ordering: false,
                searching: true,
                info: false,
                "scrollY": false,
                "scrollX": false,
                "autoWidth": false,
                fixedHeader: true,
                pageLength: 10,
                dom: '<"pull-left"f><"pull-right"l>tip',
                data: printableCasteJsonData,
                columns: [
                    { title: 'Caste', data: 'caste' },
                    { title: 'INC', data: 'INC' },
                    { title: 'BJP', data: 'BJP' },
                    { title: 'AAP', data: 'AAP' },
                    { title: 'Others', data: 'Others' },
                ],
            });
            $('#caste_edit_icon').removeClass('d-none');
            $('#caste_edit_cancel_icon').addClass('d-none');
            $('#caste_edit_save_icon').addClass('d-none');
        } else {
            text = "You canceled!";
        }
    });


    $('#caste_edit_save_icon').click(function() {
        if (confirm('Confirm your changes?') == true) {
            let checkedStatus = $(".caste_trends_checkbox:checkbox").map(function() {
                return $(this)[0].checked ? 1 : 0;
            }).get();
            let casteTrendsEditInput = $(".caste_trends_edit_input").map(function() {
                return $(this).val();
            }).get();

            console.log(checkedStatus, casteTrendsEditInput);

            $.ajax({
                method: "POST",
                url: "./assets/database/update-records.php",
                data: {
                    partyValues: casteTrendsEditInput,
                    partyValuesStatus: checkedStatus,
                    allData: casteJsonData,
                    id: id
                },
                success: function(data) {

                    var printableCasteJsonData = $.ajax({
                        url: "./assets/database/fetch_printable_report_data.php",
                        dataType: "json",
                        data: {
                            table: 'caste_data',
                            id: id
                        },
                        async: false
                    }).responseText;
                    printableCasteJsonData = JSON.parse(printableCasteJsonData);
                    $('.caste_table').DataTable().destroy();
                    $('.caste_table thead').empty();
                    $('.caste_table tbody').empty();
                    $('.caste_table').DataTable({
                        responsive: true,
                        paging: false,
                        ordering: false,
                        searching: true,
                        info: false,
                        "scrollY": false,
                        "scrollX": false,
                        "autoWidth": false,
                        fixedHeader: true,
                        pageLength: 10,
                        dom: '<"pull-left"f><"pull-right"l>tip',
                        data: printableCasteJsonData,
                        columns: [
                            { title: 'Caste', data: 'caste' },
                            { title: 'INC', data: 'INC' },
                            { title: 'BJP', data: 'BJP' },
                            { title: 'AAP', data: 'AAP' },
                            { title: 'Others', data: 'Others' },
                        ],
                    });
                    $('#caste_edit_icon').removeClass('d-none');
                    $('#caste_edit_cancel_icon').addClass('d-none');
                    $('#caste_edit_save_icon').addClass('d-none');
                    alert(data);
                }
            });
        } else {
            text = "You canceled!";
        }
    });









    // occupation data fetch 
    var occupationJsonData = $.ajax({
        url: "./assets/database/fetch_data_table.php",
        dataType: "json",
        data: {
            table: 'occupation_data',
            id: id
        },
        async: false
    }).responseText;
    occupationJsonData = JSON.parse(occupationJsonData);
    var occupationTable = $('.occupation_table').DataTable({
        responsive: true,
        paging: false,
        ordering: false,
        searching: true,
        info: false,
        "scrollY": false,
        "scrollX": false,
        "autoWidth": false,
        fixedHeader: true,
        dom: '<"pull-left"f><"pull-right"l>tip',
        data: occupationJsonData,
        columns: [
            { title: 'Occupation', data: 'occupation' },
            { title: 'INC', data: 'INC' },
            { title: 'BJP', data: 'BJP' },
            { title: 'AAP', data: 'AAP' },
            { title: 'Others', data: 'Others' },
        ],
    });


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

    var educationTable = $('.education_table').DataTable({
        responsive: true,
        paging: false,
        ordering: false,
        searching: true,
        info: false,
        "scrollY": false,
        "scrollX": false,
        "autoWidth": false,
        fixedHeader: true,
        dom: '<"pull-left"f><"pull-right"l>tip',
        data: educationJsonData,
        columns: [
            { title: 'Education', data: 'education' },
            { title: 'INC', data: 'INC' },
            { title: 'BJP', data: 'BJP' },
            { title: 'AAP', data: 'AAP' },
            { title: 'Others', data: 'Others' },
        ],
    });


    //swot table
    // console.log(occupationJsonData);
    var swotTable = $('#swot-table').DataTable({
        responsive: true,
        searching: false,
        paging: false,
        info: false,
        ordering: false,
        data: [
            { SWOT: 'STRONG', value: 32 },
            { SWOT: 'ABOVE AVERAGE', value: 61 },
            { SWOT: 'AVERAGE', value: 76 },
            { SWOT: 'BELOW AVERAGE', value: 47 },
            { SWOT: 'WEAK', value: 26 }
        ],
        columns: [
            { title: 'SWOT', data: 'SWOT' },
            { title: '', data: 'value' },
        ],
    });





});