
function doTheDashboardTask(){

    if($('#dashboard-page')[0]){

        $('#notif-box').html('');
        $('#admin-notifications-box').html('');

        $.ajax({
            type: "POST",
            dataType: 'text',
            url: mpPanelBaseUrl + "/dashboard-task",
            data: {},
            cache: false,
            timeout: 30000,
            success: function (data) { 
    
                $('#dashboard-loading').hide();
                $('#dashboard-chart').show();
                let ret = JSON.parse(data);
                
                openChart(ret['day_purchases'],ret['day_dates']);

                if(ret['auto_migrate_needed']) openMigrateDialog("3");
                if(ret['migrate_db3to4_needed']) openMigrateDialog("4");
                if(ret['migrate_db4to5_needed']) openMigrateDialog("5");
                if(ret['migrate_db5to6_needed']) openMigrateDialog("6");
                if(ret['migrate_db6to7_needed']) openMigrateDialog("7");
                if(ret['migrate_db7to8_needed']) openMigrateDialog("8");
                if(ret['migrate_db8to9_needed']) openMigrateDialog("9");
                if(ret['migrate_db9to10_needed']) openMigrateDialog("10");
    
                if(ret['is_majoris_empty']){
                    setTimeout(function(){
                        openEasyIsntaller("normal");
                    },1000);
                    addNotif(ret['easy_installer_notif']);
                }else{
                    if(ret['switch_demo_notif'] != "") addNotif(ret['switch_demo_notif']);
                }
                
                if(ret['php_warning'] != "") addNotif(ret['php_warning']);
                
                if(ret['expire_status_notif'] != "") addNotif(ret['expire_status_notif']);
                
                if(ret['configs_notif'] != ""){
                    addNotif(ret['configs_notif']);
                    setTimeout(function(){
                        $(".new-gen-success-box").slideUp(500);
                    },4000);
                }

                if(ret['configs_notif'] != ""){
                    $('.ngsb-close').click(function () {
                        $(".new-gen-success-box").hide();
                    });
                    
                }
    
                setCounters(ret);
    
                setImportantNotifs(ret);
    
                setTimeout(function(){
                    $('#start-easy-install-btn').click(function (e) {
                        openEasyIsntaller("normal");
                    });
                    $('#switch-demo').click(function () {
                        openEasyIsntaller("force");
                    });
                },500);
    
            },
            error: function(xhr, status, error) {
                notyf.error('Error: ' + xhr.status + ' ' + xhr.statusText);
                $('#dashboard-loading').hide();
                $('#dashboard-chart').show();
            }
    
        });

    }

}

function addNotif(htmlData) {
    $('#notif-box').append(htmlData);
}

function setCounters(ret) {
    $('#user_count').text(ret['user_count']);
    $('#comment_count').text(ret['comment_count']);
    $('#post_count').text(ret['post_count']);
    $('#form_responses_count').text(ret['form_responses_count']);
    $('#payments').text(ret['payments'] + " ت");
    $('#wallet_payments').text(ret['wallet_payments']+ " ت");
}

function setImportantNotifs(ret) {
    if(ret['checking_payments'] > 0){
        let item = '';
        item += '<a href="'+mpPanelBaseUrl+'/payment-log" class="anb-item anb-payment">';
        item += '<i class="anbic ph ph-credit-card"></i>';
        item += '<span class="anbtext">پرداخت‌های نیازمند بررسی</span>';
        item += '<span class="anb-count">'+ret['checking_payments']+'</span>';
        item += '<i class="anbarrow ph ph-caret-left"></i>';
        item += '</a>';
        $('.admin-notifications-box').append(item);
    }
    if(ret['active_order_count'] > 0){
        let item = '';
        item += '<a href="'+mpPanelBaseUrl+'/physical-orders" class="anb-item anb-order">';
        item += '<i class="anbic ph ph-rows"></i>';
        item += '<span class="anbtext">سفارش‌های فعال</span>';
        item += '<span class="anb-count">'+ret['active_order_count']+'</span>';
        item += '<i class="anbarrow ph ph-caret-left"></i>';
        item += '</a>';
        $('.admin-notifications-box').append(item);
    }
    if(ret['active_form_order_count'] > 0){
        let item = '';
        item += '<a href="'+mpPanelBaseUrl+'/form-orders" class="anb-item anb-form-order">';
        item += '<i class="anbic ph ph-rows"></i>';
        item += '<span class="anbtext">سفارش‌های فرم فعال</span>';
        item += '<span class="anb-count">'+ret['active_form_order_count']+'</span>';
        item += '<i class="anbarrow ph ph-caret-left"></i>';
        item += '</a>';
        $('.admin-notifications-box').append(item);
    }
    if(ret['unconfirmed_comment_count'] > 0){
        let item = '';
        item += '<a href="'+mpPanelBaseUrl+'/comments" class="anb-item anb-comment">';
        item += '<i class="anbic ph ph-chat-centered-text"></i>';
        item += '<span class="anbtext">کامنت‌های تایید نشده</span>';
        item += '<span class="anb-count">'+ret['unconfirmed_comment_count']+'</span>';
        item += '<i class="anbarrow ph ph-caret-left"></i>';
        item += '</a>';
        $('.admin-notifications-box').append(item);
    }
    if(ret['unanswered_ticket_count'] > 0){
        let item = '';
        item += '<a href="'+mpPanelBaseUrl+'/tickets" class="anb-item anb-ticket">';
        item += '<i class="anbic ph ph-chats"></i>';
        item += '<span class="anbtext">تیکت‌های باز</span>';
        item += '<span class="anb-count">'+ret['unanswered_ticket_count']+'</span>';
        item += '<i class="anbarrow ph ph-caret-left"></i>';
        item += '</a>';
        $('.admin-notifications-box').append(item);
    }
}

function openChart(chart_data_array,chart_date_array){

    Chart.defaults.font.family = 'iransansfa';
    Chart.defaults.color = "#282828e6";

    //chart_data_array = [556000,1950000,748000,1229000,649000,528000,1479000];
    let saleChart = Chart.getChart("saleChart"); // <canvas> id
    if (saleChart != undefined) {
        saleChart.destroy();
    }

    saleChart = new Chart($('#saleChart'), {
        type: 'line',
        data: {
            labels: chart_date_array,
            datasets: [{
                label: 'فروش',
                data: chart_data_array,
                lineTension: 0.3,
                borderWidth: 3,
                pointRadius: 5,
                pointHoverRadius: 8,
                borderColor: '#007bff',
                backgroundColor: '#6eb4ff',
            }]
        },
        options: {
            bezierCurve: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    type: 'linear',
                    grace: '20%',
                    grid: {
                        color: '#0000000d'
                    },
                    ticks: {
                        padding: 15
                    }
                },
                x: {
                    grid: {
                        color: '#0000000a'
                    },
                    ticks: {
                        padding: 15,
                        maxRotation: 90
                    }
                }
            },
            plugins: {
                legend: {
                  display: false
                }
              }
        }
    });

    setTimeout(function () {
        saleChart.update();
    }, 300);

}

function openMigrateDialog(version){

    //v3 make db update from 2 to 9
    //v4 make db update from 3 to 9
    //v5 make db update from 4 to 9
    //v6 make db update from 5 to 9
    //v7 make db update from 6 to 9
    //v8 make db update from 7 to 9
    //v9 make db update from 8 to 9
    //v10 make db update from 9 to 10

    let dialogLoaderReqUrl = "/dialog-html-loader/migration_dialog?version="+version;
    let doBtnId = "#migrate-v"+version+"-do";
    let loadingId = "#migration-loading";
    let updateReqUrl = "/migrate-database-to-v"+version;

    $('#dialog-holder').append(dialogHtmlGenerator("dialog","migration_dialog"));

    let dialog_id = "#migration_dialog";
    let contentBox = $(dialog_id + " .majorisbox-final-content");
    let closeBtn = $(dialog_id + " .majorisbox-close");
    let closeLayout = $(dialog_id+" .majorisbox-close-layout");
    let loadingOverlay = $(dialog_id).find('.majorisbox-loading');
    contentBox.hide();

    $(dialog_id).fadeIn('fast');
    $("html").css("overflow", "hidden");
    
    closeBtn.hide();
    // closeBtn.add(closeLayout).click(function () {
    //     contentBox.html("");
    //     $(dialog_id).fadeOut('fast');
    //     $('#dialog-holder').find(dialog_id).remove();
    // });

    loadingOverlay.show();

    contentBox.html("");

    setTimeout(function() {
        $.ajax({
            type: "POST",
            url: mpPanelBaseUrl + dialogLoaderReqUrl,
            cache: false,
            timeout: 25000,
            success: function (data) {
                contentBox.html(data);
                contentBox.show();
                loadingOverlay.hide();
                
                $(doBtnId).click(function () { //this will update from v2 upto v10

                    $(doBtnId).prop("disabled",true);
                    $(doBtnId).hide();
                    $(loadingId).show();
            
                    $.ajax({
                        type: "POST",
                        url: mpPanelBaseUrl + updateReqUrl, //this will auto update to v10
                        data: {},
                        async: true,
                        timeout: 18000000, //5hours
                        cache: false,
                        success: function (data) {
                            //we check of one or more ok in string: (for eg. when we migrate from some older db to new db)
                            //for times we have more that one version diffrence (v3tov6 for example return okokok)
                            if (/^(ok)+$/.test(data)) { 
                                contentBox.html("");
                                $(dialog_id).fadeOut('fast');
                                $("html").css("overflow", "auto");
                                notyf.success("عملیات با موفقیت انجام شد");
                                setTimeout(function () {
                                    window.location.reload();
                                }, 1500);
                            } else {
                                notyf.error(data);
                                $(doBtnId).prop("disabled",false);
                                $(doBtnId).show();
                                $(loadingId).hide();
                                $('#dialog-holder').find(dialog_id).remove();
                                $("html").css("overflow", "auto");
                            }
                        },
                        error: function (xhr, status, error) {
                            $(doBtnId).prop("disabled",false);
                            $(doBtnId).show();
                            $(loadingId).hide();
                            notyf.error('Error: ' + xhr.status + ' ' + xhr.statusText);
                            $('#dialog-holder').find(dialog_id).remove();
                            $("html").css("overflow", "auto");
                        }
                    });
            
                });
                
            },
            error: function (xhr, status, error) {
                notyf.error('Error: ' + xhr.status + ' ' + xhr.statusText);
                $(dialog_id).fadeOut('fast');
                $('#dialog-holder').find(dialog_id).remove();
                $("html").css("overflow", "auto");
            }

        });
    }, 200);

}


$(function () { // start of document ready:

    doTheDashboardTask();

}); //end of jqury doc ready