let baseUrl = window.location.href;
let selLanguage = {};

let storeDetails = {},
    backupStatus = false;
let upgradeStatus = false;

$(document).ready(function () {
    authenticateUser();
    loadLanguageFile();
    let reqUrl = baseUrl + "service/index.php?reqmethod=getLicenseKey";
    $.get(reqUrl, function (data, status) {
        if (status === "success") {
            getStoreDetails(data);
            getLatestVersion();
        } else {
            console.log("Error in getting license key")
        }
    });
    $.get(baseUrl + "service/index.php?reqmethod=checkServerConfig", function (serverData, status) {
        var response = JSON.parse(serverData);
        if (response.proceed_next === 1) {
            console.log("Server settings are matching");
        } else {
            $("#serverConfigCheck").css("display", "block");
            $("#serverConfigStatusCheck").css("display", "block");
            var innerContent = '';
            var i;
            var iLength = response.error_config.length;
            for (i = 0; i < iLength; i++) {
                innerContent += "<br>" + response.error_config[i][0] + "&nbsp;&nbsp;&nbsp;" + response.error_config[i][1];
            }
            $("#serverConfigStatusCheck").html(innerContent);
        }
    });
    $("#pageOne").show();
    $("#pageTwo").hide();
    $("#pageThree").hide();
    $("#pageFour").hide();
    $("#updateLoader").hide();
    document.getElementById("applyUpdate").disabled = true;
    document.getElementById("applyUpdate").style.opacity = .5;
});

/**
 * Used to get store details.
 *
 * @param {object} data - license data
 *
 * @author travis@imprintnext.com
 * @date   12 April 2022
 *
 */
function getStoreDetails(data) {
    if (data) {
        let licenseData = JSON.parse(data);
        if (licenseData.status) {
            let currentStoreData = JSON.parse(localStorage.getItem('currentStoreData'));
            storeDetails.storeName = currentStoreData['storeName'];
            storeDetails.storeVersion = currentStoreData['storeVersion'];
            storeDetails.adminVersion = currentStoreData['adminVersion'];
            storeDetails.subscriptionType = currentStoreData['subscriptionType'];
            document.getElementById("version").innerHTML = storeDetails.adminVersion;
            document.getElementById("subscriptionType").innerHTML = storeDetails.subscriptionType;
            document.getElementById("ecomPlatform").innerHTML = storeDetails.storeName + ' ' + storeDetails.storeVersion;
            if (licenseData.is_custom_development === 'true') {
                $("#pageOne").hide();
                $("#pageTwo").hide();
                $("#pageThree").hide();
                $("#pageFour").show();
            }
        } else {
            console.log("Error in getting license key");
        }
    }
}

/**
 * After back up taken move to next step.
 *
 * @param event
 *
 * @author travis@imprintnext.com
 * @date   12 April 2022
 *
 */
function onBackupTaken(event) {
    authenticateUser();
    backupStatus = event.target.checked;
    $.get(baseUrl + "service/index.php?reqmethod=checkServerConfig", function (serverData, status) {
        var response = JSON.parse(serverData);
        if (response.proceed_next === 1) {
            if (backupStatus) {
                document.getElementById("applyUpdate").disabled = false;
                document.getElementById("applyUpdate").style.opacity = 1;
            } else {
                document.getElementById("applyUpdate").disabled = true;
                document.getElementById("applyUpdate").style.opacity = .5;
            }
        } else {
            if (!backupStatus) {
                document.getElementById("applyUpdate").disabled = true;
                document.getElementById("applyUpdate").style.opacity = .5;
            }
        }
    });
}

/**
 * This function is called when apply button is clicked.
 *
 *
 * @author travis@imprintnext.com
 * @date   12 April 2022
 *
 */
function onApplyUpdate() {
    authenticateUser();
    $("#updateLoader").show();
    let domain = btoa(window.location.host.replace('www.', ''));
    let isSecure = (window.location.protocol == 'https:') ? 1 : 0;
    let downloadReqUrls = "https://imprintnext.com/license_check/get_package_link.php?domain_name=" + domain + "&current_version=" + btoa(storeDetails.adminVersion) + "&store_type=" + storeDetails.storeName.toLowerCase() + "&store_version=" + storeDetails.storeVersion + "&is_secure=" + isSecure;
    $.get(downloadReqUrls, function (downloadPkgRes, downloadStatus) {
        if (downloadStatus === "success") {
            if (downloadPkgRes.status === "success") {
                let reqUrls = baseUrl + "service/index.php?reqmethod=updatePackage";
                let fd = new FormData();
                fd.append('zip_url', downloadPkgRes.upgrade_package_path);
                fd.append('current_version', storeDetails.adminVersion);
                $.ajax({
                    url: reqUrls,
                    type: "POST",
                    data: fd,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        let tempResp = JSON.parse(res);
                        if (tempResp.status) {
                            upgradeStatus = true;
                            $("#pageOne").hide();
                            $("#pageTwo").show();
                            document.getElementById("failedUpdate").innerHTML = '';
                            showUpdatedVersion();
                            let deleteReqUrls = "https://imprintnext.com/license_check/delete_package_link.php?unique_key=" + downloadPkgRes.random_key;
                            $.get(deleteReqUrls, function (deletedData, deletedStatus) {
                                if (deletedStatus === "success") {
                                    console.log('Package deleted');

                                    // Clean up of backed up files after upgradation
                                    cleanupBackupFiles();
                                }
                            });
                        } else {
                            upgradeStatus = false;
                            $("#pageOne").show();
                            $("#pageTwo").hide();
                            document.getElementById("failedUpdate").innerHTML = selLanguage && selLanguage['failed-update'] ? selLanguage['failed-update'] : 'Failed to update. Please contact to ImprintNext Support';
                        }
                        $("#updateLoader").hide();
                    }
                });
            } else {
                document.getElementById("failedUpdate").innerHTML = 'Error in getting latest package, Please contact to ImprintNext <a href="https://imprintnext.freshdesk.com/support/login" rel="support">Support.</a>';
                $("#updateLoader").hide();
            }
        } else {
            document.getElementById("failedUpdate").innerHTML = 'Error in getting latest package, Please contact to ImprintNext <a href="https://imprintnext.freshdesk.com/support/login" rel="support">Support.</a>';
            $("#updateLoader").hide();
        }
    });
}

/**
 *  This function is called to get latest version
 *
 * @author travis@imprintnext.com
 * @date   12 April 2022
 *
 */
function getLatestVersion() {
    let reqestedUrl = baseUrl + "service/index.php?reqmethod=getLatestVersion&current_version=" + storeDetails.adminVersion;
    $.get(reqestedUrl, function (data, status) {
        if (status === "success") {
            let tempResponse = JSON.parse(data);
            if (tempResponse.message == 'current version is latest version') {
                $("#pageOne").hide();
                $("#pageTwo").hide();
                $("#pageThree").show();
            } else {
                if (tempResponse.status) {
                    if (tempResponse.data && tempResponse.data.next_version) {
                        document.getElementById("latestVersion").innerHTML = tempResponse.data.next_version;
                        document.getElementById("latestVersionDesc").innerHTML = tempResponse.data.next_version;
                    }
                } else {
                    $("#pageOne").hide();
                    $("#pageTwo").hide();
                    $("#pageThree").hide();
                    $("#pageFour").show();
                }
            }
        } else {
            console.log("Error in getting latest version");
        }
    });
}

/**
 *  Show latest version after upadte version
 *
 * @author travis@imprintnext.com
 * @date   12 April 2022
 *
 */
function showUpdatedVersion() {
    let reqUrl = baseUrl + "service/index.php?reqmethod=getLicenseKey";
    $.get(reqUrl, function (data, status) {
        if (status === "success") {
            getStoreDetails(data);
        } else {
            console.log("Error in getting license key")
        }
    });
}

/**
 *  This function is used to authenticate user
 *
 * @author travis@imprintnext.com
 * @date   12 April 2022
 *
 */
function authenticateUser() {
    let roleId = localStorage.getItem('role_id');
    if (roleId !== '1') {
        localStorage.clear();
        let tempBaseUrl = baseUrl.replace("update/", "");
        let adminUrl = tempBaseUrl + 'admin';
        window.open(adminUrl, "_self");
    }
}

/**
 *  This function is used to load selected language file.
 *
 * @author travis@imprintnext.com
 * @date   12 April 2022
 *
 */
function loadLanguageFile() {
    let defaultLanguage = localStorage.getItem('defaultLanguage') ? localStorage.getItem('defaultLanguage') : 'english';
    let languageUrl = baseUrl + "service/index.php?reqmethod=getLanguages";
    $.get(languageUrl, function (data, status) {
        if (status === "success") {
            let languageData = JSON.parse(data);
            if (languageData.status) {
                if (languageData.data) {
                    let defaultLanguageData = languageData.data.filter(function (el) {
                        return el.name.toLowerCase() === defaultLanguage;
                    })[0];
                    if (defaultLanguageData) {
                        getLanguageFileContent(defaultLanguageData.file_name);
                    }
                }
            } else {
                console.log("Error in getting language.");
            }
        } else {
            console.log("Error in getting language.");
        }
    });
}

/**
 *  This function is used to get language file content.
 *  @param filePath: file path
 *
 * @author travis@imprintnext.com
 * @date   12 April 2022
 *
 */
function getLanguageFileContent(filePath) {
    $.get(filePath, { headers: { 'Content-Type': 'application/json' } }).then((res) => {
        selLanguage = res['update-package'];
        if (selLanguage) {
            $("#versionLabel").html(selLanguage['current-version']);
            $("#subscriptionLabel").html(selLanguage['subsciption-type']);
            $("#ecomPlatformLabel").html(selLanguage['e-commerce-platform']);
            $("#takeBackupLabel").html(selLanguage['take-backup']);
            $("#takeBackupDescLabel").html(selLanguage['take-server-backup']);
            $("#backupTakenLabel").html(selLanguage['backup-taken']);
            $("#updatePackageLabel").html(selLanguage['upload-update-package']);
            $("#downLoadLabel").html(selLanguage['download-upadte-package']);
            $("#licensePortalLabel").html(selLanguage['license-portal']);
            $("#updateFileLabel").html(selLanguage['update-file']);
            $("#uploadUpdateFileLabel").html(selLanguage['upload-update-file']);
            $("#finalStepLabel").html(selLanguage['final-step']);
            $("#clickApplyLabel").html(selLanguage['click-apply']);
            $("#processTimeLabel").html(selLanguage['proccess-time']);
            $("#applyUpdateLabel").html(selLanguage['apply-update']);
            $("#successHeadingLabel").html(selLanguage['message']);
            $("#successDescLabel").html(selLanguage['success-message']);
            $("#latestVerHeadingLabel").html(selLanguage['message']);
            $("#latestVerDescLabel").html(selLanguage['latest-version-message']);
            $("#description").html(selLanguage['update-language']);
            $("#updateMessage").html(selLanguage['change-version-message']);
            $("#applyUpdate").html(selLanguage['apply-update-btn']);
            $("#serverConfigCheck").html(selLanguage['server-config-message']);
        }
    }).catch((err) => {
        console.log("Error in getting language file content.");
    });
}

/**
 *  Redirect to Admin Dashboard
 *
 * @author travis@imprintnext.com
 * @date   12 April 2022
 *
 */
function redirectToAdmin() {
    let roleId = localStorage.getItem('role_id');
    let tempBaseUrl = baseUrl.replace("update/", "");
    let adminUrl = tempBaseUrl + 'admin/#/user/edit-user/' + roleId;
    window.open(adminUrl, "_self");
}

/**
 *  Redirect to Admin Sign In
 *
 * @author travis@imprintnext.com
 * @date   12 April 2022
 *
 */
function redirectToUserPage() {
    let tempBaseUrl = baseUrl.replace("update/", "");
    let adminUrl = tempBaseUrl + 'admin/#/auth';
    window.open(adminUrl, "_self");
}

/**
 *  clean up of backed up files after ImprintNext upgradation
 *
 * @author pansy@imprintnext.com
 * @date   17 April 2024
 *
 */
function cleanupBackupFiles() {
    let delReqUrl = baseUrl + "service/index.php?reqmethod=deleteBackupFiles";
    $.ajax({
        url: delReqUrl,
        type: "POST",
        contentType: false,
        success: function (res) {
            if (res.success) {
                alert('Files deleted successfully!');
            } else {
                alert('Failed to delete files: ' + response.message);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('Error deleting files: ' + textStatus + ' - ' + errorThrown);
        }
    });
}