/// <summary>
        /// Updates the SagePay Server Transaction
        /// </summary>
        /// <param name="sagePayServerTransaction">The SagePay Server Transaction</param>
        public virtual void UpdateSagePayServerTransaction(SagePayServerTransaction sagePayServerTransaction)
        {
            if (sagePayServerTransaction == null)
                throw new ArgumentNullException("sagePayServerTransaction");

            _sagePayServerTransactionRepository.Update(sagePayServerTransaction);
        }
        public ActionResult PaymentInfo()
        {
            var model = new PaymentSagePayServerModel();

            //First validate if this is the response of failed transaction (Status INVALID)
            var StatusDetail = Request.QueryString["StatusDetail"];

            if (StatusDetail != null)
            {
                model.Warnings.Add(StatusDetail);
                return View("Nop.Plugin.Payments.SagePayServer.Views.PaymentSagePayServer.PaymentInfo", model);
            }

            var webClient = new WebClient();

            var data = new NVPCodec();

            data.Add("VPSProtocol", SagePayHelper.GetProtocol());
            data.Add("TxType", _sagePayServerPaymentSettings.TransactType);
            data.Add("Vendor", _sagePayServerPaymentSettings.VendorName.ToLower());

            var orderGuid = Guid.NewGuid();

            data.Add("VendorTxCode", orderGuid.ToString());

            if (!String.IsNullOrWhiteSpace(_sagePayServerPaymentSettings.PartnerID))
                data.Add("ReferrerID", _sagePayServerPaymentSettings.PartnerID);

            var cart = _workContext.CurrentCustomer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
            
            decimal? shoppingCartTotalBase = _orderTotalCalculationService.GetShoppingCartTotal(cart);

            var OrderTotal = shoppingCartTotalBase.GetValueOrDefault();

            data.Add("Amount", OrderTotal.ToString("F2", CultureInfo.InvariantCulture));

            if (_workContext.WorkingCurrency != null)
                data.Add("Currency", _workContext.WorkingCurrency.CurrencyCode);
            else if (_workContext.CurrentCustomer.CurrencyId.HasValue && _workContext.CurrentCustomer.Currency != null)
                data.Add("Currency", _workContext.CurrentCustomer.Currency.CurrencyCode);
            else
                data.Add("Currency", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode);                        

            data.Add("Description", "DescriptionText");

            // The Notification URL is the page to which Server calls back when a transaction completes

            var notificationUrl = _sagePayServerPaymentSettings.NotificationFullyQualifiedDomainName;

            data.Add("NotificationURL", notificationUrl + "Plugins/PaymentSagePayServer/NotificationPage");

            // Billing Details
            data.Add("BillingSurname", _workContext.CurrentCustomer.BillingAddress.LastName);
            data.Add("BillingFirstnames", _workContext.CurrentCustomer.BillingAddress.FirstName);
            data.Add("BillingAddress1", _workContext.CurrentCustomer.BillingAddress.Address1);

            if (!String.IsNullOrWhiteSpace(_workContext.CurrentCustomer.BillingAddress.Address2))
                data.Add("BillingAddress2", _workContext.CurrentCustomer.BillingAddress.Address2);

            data.Add("BillingCity", _workContext.CurrentCustomer.BillingAddress.City);
            data.Add("BillingPostCode", _workContext.CurrentCustomer.BillingAddress.ZipPostalCode);
            data.Add("BillingCountry", _workContext.CurrentCustomer.BillingAddress.Country.TwoLetterIsoCode); //TODO: Verify if it is ISO 3166-1 country code

            if (_workContext.CurrentCustomer.BillingAddress.StateProvince != null)
                data.Add("BillingState", _workContext.CurrentCustomer.BillingAddress.StateProvince.Abbreviation);

            if (!String.IsNullOrWhiteSpace(_workContext.CurrentCustomer.BillingAddress.PhoneNumber))
                data.Add("BillingPhone", _workContext.CurrentCustomer.BillingAddress.PhoneNumber);


            // Delivery Details
            if (_workContext.CurrentCustomer.ShippingAddress != null)
            {
                data.Add("DeliverySurname", _workContext.CurrentCustomer.ShippingAddress.LastName);
                data.Add("DeliveryFirstnames", _workContext.CurrentCustomer.ShippingAddress.FirstName);
                data.Add("DeliveryAddress1", _workContext.CurrentCustomer.ShippingAddress.Address1);

                if (!String.IsNullOrWhiteSpace(_workContext.CurrentCustomer.ShippingAddress.Address2))
                    data.Add("DeliveryAddress2", _workContext.CurrentCustomer.ShippingAddress.Address2);

                data.Add("DeliveryCity", _workContext.CurrentCustomer.ShippingAddress.City);
                data.Add("DeliveryPostCode", _workContext.CurrentCustomer.ShippingAddress.ZipPostalCode);

                if (_workContext.CurrentCustomer.ShippingAddress.Country != null)
                {
                    data.Add("DeliveryCountry", _workContext.CurrentCustomer.ShippingAddress.Country.TwoLetterIsoCode);
                }

                if (_workContext.CurrentCustomer.ShippingAddress.StateProvince != null)
                    data.Add("DeliveryState", _workContext.CurrentCustomer.ShippingAddress.StateProvince.Abbreviation);

                if (!String.IsNullOrWhiteSpace(_workContext.CurrentCustomer.ShippingAddress.PhoneNumber))
                    data.Add("DeliveryPhone", _workContext.CurrentCustomer.ShippingAddress.PhoneNumber);

            }
            else {
                //Thanks to 'nomisit' for pointing this out. http://www.nopcommerce.com/p/258/sagepay-server-integration-iframe-and-redirect-methods.aspx
                data.Add("DeliverySurname", "");
                data.Add("DeliveryFirstnames", "");
                data.Add("DeliveryAddress1", "");
                data.Add("DeliveryAddress2", "");
                data.Add("DeliveryCity", "");
                data.Add("DeliveryPostCode", "");
                data.Add("DeliveryCountry", "");
                data.Add("DeliveryState", "");
                data.Add("DeliveryPhone", "");
            }

            data.Add("CustomerEMail", _workContext.CurrentCustomer.Email);

            //var strBasket = String.Empty;
            //strBasket = cart.Count + ":";

            //for (int i = 0; i < cart.Count; i++)
            //{
            //    ShoppingCartItem item = cart[i];
            //    strBasket += item.ProductVariant.FullProductName) + ":" +
            //                    item.Quantity + ":" + item.ProductVariant.Price + ":" +
            //                    item.ProductVariant.TaxCategoryId;
            //};

            //data.Add("Basket", strBasket);

            data.Add("AllowGiftAid", "0");

            // Allow fine control over AVS/CV2 checks and rules by changing this value. 0 is Default
            if (_sagePayServerPaymentSettings.TransactType != "AUTHENTICATE") data.Add("ApplyAVSCV2", "0");

            // Allow fine control over 3D-Secure checks and rules by changing this value. 0 is Default
            data.Add("Apply3DSecure", "0");

            if (String.Compare(_sagePayServerPaymentSettings.Profile, "LOW", true) == 0)
            {
                data.Add("Profile", "LOW"); //simpler payment page version.
            }

            var postURL = SagePayHelper.GetSageSystemUrl(_sagePayServerPaymentSettings.ConnectTo, "purchase");

            string strResponse = string.Empty;

            try
            {

                Byte[] responseData = webClient.UploadValues(postURL, data);

                strResponse = Encoding.ASCII.GetString(responseData);


            }
            catch (WebException ex)
            {

                return Content(String.Format(
                    @"Your server was unable to register this transaction with Sage Pay.
                    Check that you do not have a firewall restricting the POST and 
                    that your server can correctly resolve the address {0}. <br/>
                    The Status Number is: {1}<br/>
                    The Description given is: {2}", postURL, ex.Status, ex.Message));

            }

            if (string.IsNullOrWhiteSpace(strResponse))
                return Content(String.Format(
                    @"Your server was unable to register this transaction with Sage Pay.
                    Check that you do not have a firewall restricting the POST and 
                    that your server can correctly resolve the address {0}.", postURL));

            var strStatus = SagePayHelper.FindField("Status", strResponse);
            var strStatusDetail = SagePayHelper.FindField("StatusDetail", strResponse);

            switch (strStatus)
            {
                case "OK":

                    var strVPSTxId = SagePayHelper.FindField("VPSTxId", strResponse);
                    var strSecurityKey = SagePayHelper.FindField("SecurityKey", strResponse);
                    var strNextURL = SagePayHelper.FindField("NextURL", strResponse);

                    var transx = new SagePayServerTransaction()
                    {
                        CreatedOnUtc = DateTime.UtcNow,
                        VPSTxId = strVPSTxId,
                        SecurityKey = strSecurityKey,
                        NotificationResponse = strResponse,
                        VendorTxCode = orderGuid.ToString()
                    };

                    //Store this record in DB
                    _sagePayServerTransactionService.InsertSagePayServerTransaction(transx);
                   
                    
                    ViewBag.UseOnePageCheckout = UseOnePageCheckout();

                    if (_sagePayServerPaymentSettings.Profile == SagePayServerPaymentSettings.ProfileValues.LOW || ViewBag.UseOnePageCheckout)
                    {//Iframe
                        model.FrameURL = strNextURL;

                        return View("Nop.Plugin.Payments.SagePayServer.Views.PaymentSagePayServer.PaymentInfo", model);
                    }
                    else {
                        HttpContext.Response.Redirect(strNextURL);
                        HttpContext.Response.End();

                        return null;
                    }


                case "MALFORMED":
                    return Content(string.Format("Error ({0}: {1}) <br/> {2}", strStatus, strStatusDetail, data.Encode()));

                case "INVALID":
                    return Content(string.Format("Error ({0}: {1}) <br/> {2}", strStatus, strStatusDetail, data.Encode()));

                default:
                    return Content(string.Format("Error ({0}: {1})", strStatus, strStatusDetail));

            }

        }