function cancelCompanyProfileEntry() {
    prevscreen('CompanyProfile');
    companyProfileFilter();
}

function addCompanyProfile() {
    saveCompanyProfileEntry(C_ADD);
}
function updateCompanyProfile() {
    saveCompanyProfileEntry(C_UPDATE);
}

function saveCompanyProfileEntry(type) {
    LoadingScreen("show");
    if (validateCompanyProfileEntry()) {
        var data = {
            "type"              : type,

            "id"                : $('#txtCompanyProfileID').val(),
            "code"              : $('#txtCompanyProfileCode').val(),
            "active"            : ($('#chkCompanyProfileActive').is(':checked') ? '1' : '0'),
            "name"              : $('#txtCompanyProfileName').val(),
            "url"               : $('#txtCompanyProfileUrl').val(),

            "oauth"             : $('#cobCompanyProfileOAuth').val(),
            "tenant_id"         : $('#txtCompanyProfileTenantID').val(),
            "mail_server"       : $('#txtCompanyProfileMailServer').val(),
            "port"              : $('#txtCompanyProfilePort').val(),
            "mail_sender"       : $('#txtCompanyProfileMailSender').val(),
            "mail_password"     : $('#txtCompanyProfileMailPassword').val(),
            "ea"                : ($('#chkCompanyProfileEA').is(':checked') ? '1' : '0'),
            "ssl"               : ($('#chkCompanyProfileSSL').is(':checked') ? '1' : '0'),

            "base64file"        : $('#txtCompanyProfileLogoFileBase64').html(),
            "extension"         : $('#txtCompanyProfileLogoFileExt').val(),
            "filename"          : $('#txtCompanyProfileLogoFilename').val(),
            
            "sig_base64file"    : $('#txtCompanyProfileSignatureFileBase64').html(),
            "sig_extension"     : $('#txtCompanyProfileSignatureFileExt').val(),
            "sig_filename"      : $('#txtCompanyProfileSignatureFilename').val(),
        };
        var url = "index.pzx?c=" + company_profile_url + "&d=" + new Date().getTime();
        callServer(url, "json", data, onResponseCompanyProfileEntry, null);
        return false;
    } else {
        LoadingScreen("hide");
    }
}

function validateCompanyProfileEntry() {
    if ($('#txtCompanyProfileCode').blank()) {
        swal.fire("Warning", "Company Profile Code cannot be blank", "warning");
        return false;
    }

    if ($('#txtCompanyProfileName').blank()) {
        swal.fire("Warning", "Company Profile Name cannot be blank", "warning");
        return false;
    }

    return true;
}

function onResponseCompanyProfileEntry(obj, resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK) {
        swal.fire('Warning', resp.mesg, 'warning');
        return;
    }

    if (resp.type == C_ADD) {
        swal.fire('Success', resp.mesg, 'success');
        $(".btnSaveCompanyProfile").attr("onclick", "updateCompanyProfile();");
        $("#txtCompanyProfileID").val(resp.data.id);

        $('#txtCompanyProfileLogoFilename').val(resp.data.logo);
        $('#txtCompanyProfileSignatureFilename').val(resp.data.signature);
    }
    if (resp.type == C_UPDATE) {
        swal.fire('Success', resp.mesg, 'success');
        $(".btnSaveCompanyProfile").attr("onclick", "updateCompanyProfile();");

        $('#txtCompanyProfileLogoFilename').val(resp.data.logo);
        $('#txtCompanyProfileSignatureFilename').val(resp.data.signature);
    }
}

//logo
//=================================================
function hasExtensionCompanyProfileLogo(inputID, exts) {
    var fileName = document.getElementById(inputID).value;
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName.toLowerCase());
}

function getFileExtensionCompanyProfileLogo(filename) {
    var ext = /^.+\.([^.]+)$/.exec(filename);
    return ext == null ? "" : ext[1];
}

function encodeImageFileAsURLCompanyProfileLogo(event) {
    var filesSelected = document.getElementById("txtCompanyProfileLogo").files;
    if (!hasExtensionCompanyProfileLogo('txtCompanyProfileLogo', ['.jpg', '.jpeg', '.png'])) {
        alert("The image format have to be in 'jpg', 'jpeg', 'png' ");
        $("#txtCompanyProfileLogo").val("");
        return;
    }

    if (filesSelected.length > 0) {
        var fileToLoad = filesSelected[0];
        var fileExt = getFileExtensionCompanyProfileLogo(filesSelected[0].name);

        var fileReader = new FileReader();

        fileReader.onload = function (fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result; // <--- data: base64
            $('#txtCompanyProfileLogoFileBase64').html(srcData);
            $('#txtCompanyProfileLogoFileExt').val(fileExt);
        }

        fileReader.readAsDataURL(fileToLoad);
    }

    src = URL.createObjectURL(event.target.files[0])
    $('#imgCompanyProfileLogo').attr('src', src);
}

function removeCompanyProfileLogo() {
    Swal.fire({
        title: "System Confirmation",
        text: "Confirm you want to remove the company logo?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        customClass: {
            confirmButton: 'swal-btn-confirm',
            cancelButton: 'swal-btn-cancel'
        }
    }).then(function (result) {
        if (result.isConfirmed) {
            var data = { "type": "DELETE_COMPANY_PROFILE_LOGO", "id": 0, "path": $('#imgCompanyProfileLogo').attr('src') };
            var url = "index.pzx?c=" + company_profile_url + "&d=" + new Date().getTime();
            callServer(url, "json", data, onResponseCompanyProfileLogo, null);
        }
    });
}

function onResponseCompanyProfileLogo(obj, resp) {
    if (resp.status != C_OK) {
        swal.fire("Warning", resp.mesg, 'warning');
        return;
    }

    if (resp.type == "DELETE_COMPANY_PROFILE_LOGO") {
        $('#txtCompanyProfileLogoFilename').val("");
        $("#imgCompanyProfileLogo").attr("src", resp.data.src);
    }
}
//=================================================

//signature
//=================================================
function hasExtensionCompanyProfileSignature(inputID, exts) {
    var fileName = document.getElementById(inputID).value;
    return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName.toLowerCase());
}

function getFileExtensionCompanyProfileSignature(filename) {
    var ext = /^.+\.([^.]+)$/.exec(filename);
    return ext == null ? "" : ext[1];
}

function encodeImageFileAsURLCompanyProfileSignature(event) {
    var filesSelected = document.getElementById("txtCompanyProfileSignature").files;
    if (!hasExtensionCompanyProfileSignature('txtCompanyProfileSignature', ['.jpg', '.jpeg', '.png'])) {
        alert("The image format have to be in 'jpg', 'jpeg', 'png' ");
        $("#txtCompanyProfileSignature").val("");
        return;
    }

    if (filesSelected.length > 0) {
        var fileToLoad = filesSelected[0];
        var fileExt = getFileExtensionCompanyProfileSignature(filesSelected[0].name);

        var fileReader = new FileReader();

        fileReader.onload = function (fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result; // <--- data: base64
            $('#txtCompanyProfileSignatureFileBase64').html(srcData);
            $('#txtCompanyProfileSignatureFileExt').val(fileExt);
        }

        fileReader.readAsDataURL(fileToLoad);
    }

    src = URL.createObjectURL(event.target.files[0])
    $('#imgCompanyProfileSignature').attr('src', src);
}

function removeCompanyProfileSignature() {
    Swal.fire({
        title: "System Confirmation",
        text: "Confirm you want to remove the company Signature?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        customClass: {
            confirmButton: 'swal-btn-confirm',
            cancelButton: 'swal-btn-cancel'
        }
    }).then(function (result) {
        if (result.isConfirmed) {
            var data = { "type": "DELETE_COMPANY_PROFILE_SIGNATURE", "id": 0, "path": $('#imgCompanyProfileSignature').attr('src') };
            var url = "index.pzx?c=" + company_profile_url + "&d=" + new Date().getTime();
            callServer(url, "json", data, onResponseCompanyProfileSignature, null);
        }
    });
}

function onResponseCompanyProfileSignature(obj, resp) {
    if (resp.status != C_OK) {
        swal.fire("Warning", resp.mesg, 'warning');
        return;
    }

    if (resp.type == "DELETE_COMPANY_PROFILE_SIGNATURE") {
        $('#txtCompanyProfileSignatureFilename').val("");
        $("#imgCompanyProfileSignature").attr("src", resp.data.src);
    }
}
//=================================================

function settingGrantPermission(){
    var tenantID = $('#cobCompanyProfileTenantID').val();
    var clientID = $('#cobCompanyProfileClientID').val();
    var url = "https://login.microsoftonline.com/" + tenantID + "/adminconsent?client_id=" + clientID

    window.open(url, "_blank");
}

// Email Test ==============================================================>
function showEmailTestModal() {
    $('#emailTestModal').modal('show');
}

function submitCompanyEmailTest() {
    LoadingScreen("show");
    if($('#emailTestSubmitTo').val() == ""){
        swal.fire("Warning", "Email cannot be blank.", "warning");
        return;
    } else {
        var data = {
            "type"          : "SEND_EMAIL_TESTING",
            "id"            : $('#txtCompanyProfileID').val(),
            "to_email"      : $('#emailTestSubmitTo').val(),
        };
        var url = "index.pzx?c=" + company_profile_entry_url + "&d=" + new Date().getTime() ;
        callServer(url,"json",data,onResponseEmailTest,null) ;
    }
}

function onResponseEmailTest(obj,resp) {
    LoadingScreen("hide");
    if (resp.status != C_OK){
        swal.fire("Warning",resp.mesg,'warning');
        return;
    }

    if (resp.type == "SEND_EMAIL_TESTING"){
        swal.fire("Success",resp.mesg,'success');
        $('#emailTestModal').modal('hide');
    }
}
