
jQuery().ready(function ($) {
    $('#pg_connectivity').click(function () {
        var merchant_id = document.getElementById('params_merchant_id').value;
        var encryption_key = document.getElementById('params_encryption_key').value;
        var signing_key = document.getElementById('params_signing_key').value;
        var client_key = document.getElementById('params_client_id').value;
        var key_id = document.getElementById('params_key_id').value;
        var item_code = document.getElementById('params_item_code').value;
        var env = document.getElementById('params_environment').value; // Clear previous messages
        document.getElementById('show_error').innerHTML = '';
        document.getElementById('show_mess').innerHTML = '';

        // Validation
        var missingFields = [];
        if (!merchant_id) missingFields.push("Merchant ID");
        if (!encryption_key) missingFields.push("Encryption Key");
        if (!signing_key) missingFields.push("Signing Key");
        if (!client_key) missingFields.push("Client Id");
        if (!key_id) missingFields.push("Key ID");

        if (missingFields.length > 0) {
            document.getElementById('show_error').innerHTML = "Please fill the following fields: <b>" + missingFields.join(", ") + "</b>";
            return false; // stop execution
        }



        jQuery.ajax({
            url: Virtuemart.vmSiteurl + 'index.php?option=com_virtuemart&view=pluginresponse&task=pluginnotification',
            data: {
                merchant_id: merchant_id,
                encryption_key: encryption_key,
                signing_key:signing_key,
                client_key: client_key,
                key_id: key_id,
                item_code: item_code,
                env: env
            },
            type: "post",
            success: function (data) {
                var txn = JSON.parse(data);
                if (txn.status === 401 || txn.status === 404 || txn.status === 500 || txn.status === 422 || txn.status === 400) {
                    document.getElementById('show_error').innerHTML += '<b><U>' + "ERROR_MESSAGE : " + txn.message + '</U></b></br>' + "ERROR_CODE : " + txn.error_code + '</br>' + " ERROR_TYPE : " + txn.error_type + "\n";
                    return false;
                }
                else {
                    document.getElementById('show_mess').innerHTML += '<b><U>Successful PG Connectivity </U></b>';
                }
            },
            error: function (data) {
                alert("Fail: " + data);
            }
        });
    });
});


