let is_session_expired = 'no';
let sendURL = window.location.protocol + "//" + window.location.host + "/" + 'scripts/short_queries.php';

function get_bypass_status() {
    let url1 = window.location.protocol + "//" + window.location.host + "/" + 'scripts/short_queries.php';

    $.get(url1, { app: "dashboard", process: "get_bypass_status" })
        .done(function (data) {
            if (data !== "yes") {
                show_emergency_notice();
            }
        })
        // error
        .fail(function (jqXHR, textStatus, errorThrown) {
           
            let errorMessage;
            try {
                let error = JSON.parse(jqXHR.responseText);
                errorMessage = "Error: " + error.message; 
            } catch (e) {
                errorMessage = "An unexpected error occurred: " + jqXHR.responseText; 
            }
            bootbox.alert(errorMessage); 
        });
}

$('#sidebarCollapse').on('click', function () {
    $('#sidebar').toggleClass('active');
    $(this).toggleClass('active');
});

function show_emergency_notice() {
    let dialog = bootbox.dialog({
        title: '',
        message: '<div class="row">' +
            '<div class="col-12">' +
            '<h2>EMERGENCY MAINTENANCE ONGOING</h2>' +
            '<p>We\'re doing an emergency maintenance at the moment </p>' +
            '<p>We will  restore Service Vending in couple of hours </p>' +
            '<p>Apologies for any inconvenience this may have caused</p>' +

            '</div></div>',
        size: '',
        buttons: {
            cancel: {
                label: "Thanks for your understanding",
                className: 'btn-danger',
                callback: function () {
                    console.log('Custom cancel clicked');
                    setTimeout(function () {
                        let url1 = window.location.protocol + "//" + window.location.host + "/" + 'scripts/short_queries.php';
                        $.get(url1, {app: "dashboard", process: "get_bypass", url: window.location.href})
                            .done(function (data) {
                                console.log(data);
                                window.location = data;
                            });

                    }, 1000);
                }
            }
        }
    });
}

// function load_unseen_notification(view = '') {
//     let sendURL = window.location.protocol + "//" + window.location.host + "/" + 'scripts/short_queries.php';
//
//     $.ajax({
//         url: sendURL,
//         method: "POST",
//         data: { view: view, app: "dashboard", process: "load_notif" },
//         dataType: "json",
//         success: function (data) {
//             $('.dropdown-menu').html(data.notification);
//
//             if (data.unseen_notification > 0) {
//                 $('.count').html(data.unseen_notification);
//             }
//         },
//         // error
//         error: function (jqXHR, textStatus, errorThrown) {
//
//             let errorMessage;
//             try {
//                 let error = JSON.parse(jqXHR.responseText);
//                 errorMessage = "Error: " + error.message;
//             } catch (e) {
//                 errorMessage = "An unexpected error occurred: " + jqXHR.responseText;
//             }
//             bootbox.alert(errorMessage);
//         }
//     });
// }

function open_drawer(element) {
    $('#' + element).drawer({

        // static: dont close the drawer on click
        keyboard: true,
        focus: true,
        show: true


    });
}

function sortTable(table_id, sortColumn){
    let tableData = document.getElementById(table_id).getElementsByTagName('tbody').item(0);
    let rowData = tableData.getElementsByTagName('tr');
    for(let i = 0; i < rowData.length - 1; i++){
        for(let j = 0; j < rowData.length - (i + 1); j++){
            if(Number(rowData.item(j).getElementsByTagName('td').item(sortColumn).innerHTML.replace(/[^0-9\.]+/g, "")) < Number(rowData.item(j+1).getElementsByTagName('td').item(sortColumn).innerHTML.replace(/[^0-9\.]+/g, ""))){
                tableData.insertBefore(rowData.item(j+1),rowData.item(j));
            }
        }
    }
}

function create_account_numbers(i) {
    $("#verify_details").html("<i class='fa fa-spinner fa-spin'></i>");
    let sendURL = window.location.protocol + "//" + window.location.host + "/" + 'scripts/short_queries.php';

    $.get(sendURL, { sno: i, app: "members", process: "create_account_number" })
        .done(function(data) {
            let obj;
            try {
                obj = jQuery.parseJSON(data); // Parse JSON response
            } catch (e) {
                bootbox.alert("Error parsing response data."); 
                return false;
            }

            bootbox.alert(obj.message);
            $("#verify_details").hide();
            return false;
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            // Handle erors
            let errorMessage;
            try {
                let error = JSON.parse(jqXHR.responseText);
                errorMessage = "Error: " + error.message; 
            } catch (e) {
                errorMessage = "An unexpected error occurred: " + jqXHR.responseText; 
            }
            bootbox.alert(errorMessage);
            $("#verify_details").hide(); 
        });

    return false;
}



function save_pin_code(i) {
    let pin_code = $('#pin_code').val();
    $("#pin_code_submit").html("loading <i class='fa fa-spinner fa-spin'></i>");
    let sendURL = window.location.protocol + "//" + window.location.host + "/" + 'scripts/short_queries.php';

    $.get(sendURL, { sno: i, pin_code: pin_code, app: "dashboard", process: "save_pin_code" })
        .done(function(data) {
            bootbox.alert(data, function() {
                window.location.reload();
            });
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            // Handle erors
            let errorMessage;
            try {
                let error = JSON.parse(jqXHR.responseText);
                errorMessage = "Error: " + error.message; 
            } catch (e) {
                errorMessage = "An unexpected error occurred: " + jqXHR.responseText; 
            }
            bootbox.alert(errorMessage); 
            $("#pin_code_submit").html("Submit"); 
            // ressetting the btn text here
        });

    return false;
}

function check_session()
{
    let login_form = '<form role="form" class="form-signin" method="post" action="#" name="login_dialog" id="login_dialog"\n' +
        '                          autocomplete="off">\n' +
        '\n' +
        '                                <div class="form-group">\n' +
        '                                    <label for="logintoken">Username</label>\n' +
        '                                    <input type="text" class="form-control" name="logintoken"\n' +
        '                                           placeholder="Email Address, Username or Phone Number" id="logintoken"\n' +
        '                                           autofocus/>\n' +
        '                                </div>\n' +
        '\n' +
        '                                <div class="form-group">\n' +
        '                                    <label for="password">Password</label>\n' +
        '                                    <input type="password" class="form-control pwd" name="password" id="password"\n' +
        '                                           placeholder="Enter your password here"/>\n' +
        '                                </div>\n' +
        '\n' +
        '                                <input name="captcha" id="captcha_login" type="hidden" value=""/>\n' +
        '                                <input name="app" id="app_login" type="hidden" value="login"/>\n' +
        '\n' +
        '                    </form>';

        $.ajax({
            url: window.location.protocol + "//" + window.location.host + "/" + 'scripts/short_queries.php',
            method: "POST",
            data: { app: "dashboard", process: "check_session" },
            success: function(data) {
                if (data === '1') {
                    is_session_expired = 'yes';
                    bootbox.dialog({
                        title: 'Session Expired, Please login again',
                        message: login_form,
                        size: 'small',
                        buttons: {
                            cancel: {
                                label: "Cancel",
                                className: 'btn-danger',
                                callback: function() {
                                    console.log('Custom cancel clicked');
                                    check_session();
                                }
                            },
                            ok: {
                                label: "Login",
                                className: 'btn-success',
                                callback: function() {
                                    myApp.showPleaseWait();
                                    $.ajax({
                                        type: "POST",
                                        url: window.location.protocol + "//" + window.location.host + "/scripts/short_queries.php",
                                        data: $('#login_dialog').serialize(),
                                        dataType: "json",
                                        encode: true,
                                        success: function(login_data) {
                                            myApp.hidePleaseWait();
                                            if (login_data.status === true) {
                                                bootbox.alert("Click OK to Continue your work");
                                            } else if (login_data.status === false) {
                                                bootbox.alert("Login Failed, Click OK to Try Again", function() {
                                                    check_session();
                                                });
                                            }
                                        },
                                        fail: function(jqXHR, textStatus, errorThrown) {
                                            myApp.hidePleaseWait(); 
                                            let errorMessage;
                                            try {
                                                let error = JSON.parse(jqXHR.responseText);
                                                errorMessage = "Error: " + error.message; 
                                            } catch (e) {
                                                errorMessage = "An unexpected error occurred: " + jqXHR.responseText; 
                                            }
                                            bootbox.alert(errorMessage); 
                                        }
                                    });
                                }
                            }
                        }
                    });
                }
            },
            fail: function(jqXHR, textStatus, errorThrown) {
                
                let errorMessage;
                try {
                    let error = JSON.parse(jqXHR.responseText);
                    errorMessage = "Error: " + error.message; 
                } catch (e) {
                    errorMessage = "An unexpected error occurred: " + jqXHR.responseText; 
                }
                bootbox.alert(errorMessage); 
            }
        });
}

function set_session_notice(type, value) {
    let sendURL = window.location.protocol + "//" + window.location.host + "/" + 'scripts/short_queries.php';
    
    $.get(sendURL, { type: type, app: "dashboard", process: "set_session_notice", value: value })
        .done(function(data) {
            bootbox.alert("Session notice set successfully: " + data);
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            // Handle errors
            let errorMessage;
            try {
                let error = JSON.parse(jqXHR.responseText);
                errorMessage = "Error: " + error.message; 
            } catch (e) {
                errorMessage = "An unexpected error occurred: " + jqXHR.responseText; 
            }
            bootbox.alert(errorMessage); 
        });

    return false;
}



//For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:
function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}


//For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:
function isEmpty(str) {
    return (!str || str.length === 0 );
}


$('#funds_adder').on('click', function() {
    console.log("blurring");
    $('*').css({
        // 'opacity': '0.5',
        'filter': 'blur(1px)'
    });
    $('.funding').css({
        // 'opacity': '0.5',
        'filter': 'none'
    });
});

function skip_alert() {
    document.getElementById("overlay1").style.display = "none";
}

function closePopup() {
    // Hide the overlay and pop-up
    document.getElementById("overlay1").style.display = "none";
}

function create_user_account(i) {
    let button = $('button#create_account_user');
    button.prop('disabled', true).html("Please wait <i class='fa fa-spinner fa-spin'></i>");
    const data = { app:"kyc", user_id: i, source:"ajax", type: "create_user_account" };

    $.post(sendURL, data)
        .done(function(response) {
            console.log(response);
            bootbox.alert(response);
            setTimeout(function() {
                let newURL = window.location.protocol + "//" + window.location.host + "/v/dashboard";
                window.location = newURL;
            }, 2000);
        })
        .fail(function(jqXHR) {
            button.prop('disabled', false).html("Click here to Generate A Static Account number");
            try {
                let error = JSON.parse(jqXHR.responseText);
                bootbox.alert("Error: " + error.message);
            } catch (e) {
                bootbox.alert("An unexpected error occurred.");
            }
        });
}


function create_user_account_for_user(i) {
    document.getElementById('create_account_user').innerHTML = 'Please Wait...';
    $.get(sendURL, { app: "dashboard", user_id: i, source: "ajax", process: "create_user_account_for_user" })
        .done(function(data) {
            bootbox.alert(data);
            setTimeout(function() {
                let newURL = window.location.protocol + "//" + window.location.host + "/v/dashboard";
                window.location = newURL;
            }, 5000);
        })
        .fail(function(jqXHR) {
            try {
                let error = JSON.parse(jqXHR.responseText);
                bootbox.alert("Error: " + error.message);
            } catch (e) {
                bootbox.alert("An unexpected error occurred.");
            }
        });
}


function generate_other_account(i) {
     // let user_id = $('#user_id').val();
    document.getElementById('generate_other_account').innerHTML = 'Please Wait...';
    $.get(sendURL, { app: "dashboard", user_id: i, source: "ajax", process: "generate_other_account" })
        .done(function(data) {
            bootbox.alert(data);
            setTimeout(function() {
                let newURL = window.location.protocol + "//" + window.location.host + "/v/dashboard";
                window.location = newURL;
            }, 5000);
        })
        .fail(function(jqXHR) {
            try {
                let error = JSON.parse(jqXHR.responseText);
                bootbox.alert("Error: " + error.message);
            } catch (e) {
                bootbox.alert("An unexpected error occurred.");
            }
        });
}




function create_user_account_for_user_old(i) {
    document.getElementById('create_account_user_old').innerHTML = 'Please Wait...';
    $.get(sendURL, { app: "dashboard", user_id: i, source: "ajax", process: "create_user_account_for_user_old"})
        .done(function(data) {
            bootbox.alert(data);
            setTimeout(function() {
                let newURL = window.location.protocol + "//" + window.location.host + "/v/dashboard";
                window.location = newURL;
            }, 5000);
        })
        .fail(function(jqXHR) {
            try {
                let error = JSON.parse(jqXHR.responseText);
                bootbox.alert("Error: " + error.message);
            } catch (e) {
                bootbox.alert("An unexpected error occurred.");
            }
        });
}

function create_user_account_for_user_using_admin_detail(i) {
    // Disable the button and update its text
    const button = document.getElementById('create_account_user_using_admin');
    button.disabled = true;
    button.innerHTML = 'Please Wait...';

    let data = {
        app: "dashboard",
        user_id: i,
        source: "ajax",
        process: "create_account_user_using_admin"
    };

    let server_response = $.get(sendURL, data);

    server_response.done(function(data) {
        myApp.hidePleaseWait();
        bootbox.alert(data, function() {
            window.location.reload();
        });
    });

    server_response.fail(function(jqXHR, textStatus, errorThrown) {
        myApp.hidePleaseWait();
        bootbox.alert(jqXHR.responseText, function() {
            window.location.reload();
        });
    });

    server_response.always(function() {
        // Re-enable the button and reset its text after the request finishes
        button.disabled = false;
        button.innerHTML = 'Create Account';
    });

    return false;
}

function cancelAllAjaxRequests() {
    if (typeof XMLHttpRequest !== 'undefined') {
        // Get all the active AJAX requests
        let xhrInstances = [];
        for (let prop in window) {
            if (window.hasOwnProperty(prop) && window[prop] instanceof XMLHttpRequest) {
                xhrInstances.push(window[prop]);
            }
        }
        // Cancel each request
        xhrInstances.forEach(function(xhr) {
            xhr.abort();
        });
    }
}
cancelAllAjaxRequests();


// function show_login_notice() {
//
//
//     $.get( sendURL, { type: "reseller", app:"dashboard", process:"get_notice" })
//         .done(function( data )
//         {
//             if(data === "shown_reseller")
//             {
//                 $.get( sendURL, { type: "root", app:"dashboard", process:"get_notice" })
//                     .done(function( data_root )
//                     {
//                         if(data_root === "shown_root")
//                         {
//                             return false;
//                         }
//                         else
//                         {
//                             if(isBlank(data_root))
//                             {
//                                 return false;
//                             }
//                             else
//                             {
//                                 bootbox.alert(data_root, function(){
//                                     set_session_notice("root", "yes");
//                                 });
//                             }
//
//                         }
//
//                     });
//             }
//             else
//             {
//                 if(isBlank(data))
//                 {
//                     $.get( sendURL, { type: "root", app:"dashboard", process:"get_notice" })
//                         .done(function( data_root )
//                         {
//                             if(data_root === "shown_root")
//                             {
//                                 return false;
//                             }
//                             else
//                             {
//                                 if(isBlank(data_root))
//                                 {
//                                     return false;
//                                 }
//                                 else {
//                                     bootbox.alert(data_root, function () {
//                                         set_session_notice("root", "yes");
//                                     });
//                                 }
//                             }
//
//                         });
//                 }
//                 else
//                 {
//                     bootbox.alert(data , function(){
//
//                         set_session_notice("reseller", "yes");
//
//                         $.get( sendURL, { type: "root", app:"dashboard", process:"get_notice" })
//                             .done(function( data_root )
//                             {
//                                 if(data_root === "shown_root")
//                                 {
//                                     return false;
//                                 }
//                                 else
//                                 {
//                                     if(isBlank(data_root))
//                                     {
//                                         return false;
//                                     }
//                                     else {
//                                         bootbox.alert(data_root, function () {
//                                             set_session_notice("root", "yes");
//                                         });
//                                     }
//                                 }
//
//                             });
//                     } );
//                 }
//
//             }
//
//             return false;
//         });
//
//     return false;
// }

let platformType = $(".platform-type").data('platform_type') ?? "";
if (platformType.toLowerCase() === "aiben") {
    let resultField = $(".platform-type");
    loadDashboardStats(resultField)
}

function loadDashboardStats(resultField) {
    $.ajax({
        url: sendURL,
        data: {app: "dashboard", process: "dashboard_statistics"},
        type: "POST",
        beforeSend: function() {
            resultField.html("<strong class='fs-18'><i class='fa fa-spin fa-spinner fa-3x'></i> Fetching Data</strong>")
        },
        success: function(resultData) {
            let decodeData = JSON.parse(resultData);
            let wallets = decodeData.wallet
            let transactions = decodeData.transaction
            let payments = decodeData.payment
            let resultHtml = "";

            resultHtml += `<div class="col-xl-4 col-md-6 mb-4">
                <div class="card border-left-info shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-uppercase mb-1" style="color: #000; font-size: 16px">
                                    Total Members
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    ${decodeData.members}
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="text-primary fas fa-users fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>`

            for (let i = 0; i < wallets.length; i++) {
                const formattedValue = wallets[i].currency === "NGN"
                    ? `${wallets[i].currency} ${Number(wallets[i].value).toLocaleString()}`
                    : `${Number(wallets[i].value).toLocaleString()} ${wallets[i].currency}`

                resultHtml += `<div class="col-xl-4 col-md-6 mb-4">
                    <div class="card border-left-info shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-uppercase mb-1" style="color: #000; font-size: 16px">
                                        ${wallets[i].name}
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                                        ${formattedValue}
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <i class="text-primary fas fa-wallet fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>`
            }

            
            resultHtml += `
            
            <div class="col-xl-4 col-md-6 mb-4">
                <div class="card border-left-info shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-uppercase mb-1" style="color: #000; font-size: 16px">
                                    Total Cashback Balance
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">
                                    NGN 1, 000, 000
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="text-primary fas fa-wallet fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-12 mb-4">
                <h4><strong>Transactions</strong>
            </div>`
            
            for (let [transactionKey, transactionData] of Object.entries(transactions)) {                
                resultHtml += `<div class="col-xl-4 col-md-6 mb-4">
                    <div class="card border-left-info shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-uppercase mb-1" style="color: #000; font-size: 16px">
                                        ${transactionKey.replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase())}
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                                        NGN ${Number(transactionData).toLocaleString()}
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <i class="text-primary fas fa-wallet fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>`
            }
            
            resultHtml += `<div class="col-md-12 mb-4">
                <h4><strong>Payments</strong>
            </div>`
            
            for (let [paymentKey, paymentData] of Object.entries(payments)) {                
                resultHtml += `<div class="col-xl-4 col-md-6 mb-4">
                    <div class="card border-left-info shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-uppercase mb-1" style="color: #000; font-size: 16px">
                                        ${paymentKey.replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase())}
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800">
                                        NGN ${Number(paymentData).toLocaleString()}
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <i class="text-primary fas fa-wallet fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>`
            }

            resultField.html(resultHtml);
        },
        error: function(jqXHR, errorThrown, status) {            
            resultField.html("<strong class='fs-18'>Please refresh your page. If issue persists, contact Developer</strong>")
        }
    });
}