using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security.Cryptography;
using System.Text;
using System.Net.Http;


namespace Uatpayments_NET_MVC.Controllers
{
    public class RequestController : Controller
    {

        public String salt = "18e6063d410586se913fa536be8dbf237a6c15ee";
        public ActionResult SubmitRequest()
        {
            return View();
        }

        [HttpPost]
        public void SubmitRequest(FormCollection request)
        {
            string[] hash_columns = {
            "address_line_1",
            "address_line_2",
            "amount",
            "api_key",
            "city",
            "country",
            "currency",
            "description",
            "email",
            "mode",
            "name",
            "order_id",
            "phone",
            "return_url",
            "state",
            "udf1",
            "udf2",
            "udf3",
            "udf4",
            "udf5",
            "zip_code"
            };

            RemotePost remotepost = new RemotePost();
            request["api_key"] = "9b62ff8e-f03b-4421-b836-b630edad99dg";
            request["salt"] = salt;
            request["return_url"] = Request.Url.ToString().Substring(0, Request.Url.ToString().Length - Request.Url.PathAndQuery.Length + Url.Content("~").Length) + "Request/Return";
            request["currency"] = "INR";
            request["country"] = "IND";

            remotepost.Url = "https://{pg_url}/v2/paymentrequest";
            remotepost.Add("api_key", request["api_key"]);
            remotepost.Add("return_url", request["return_url"]);
            remotepost.Add("mode", request["mode"]);
            remotepost.Add("order_id", request["order_id"]);
            remotepost.Add("amount", request["amount"]);
            remotepost.Add("name", request["name"]);
            remotepost.Add("currency", request["currency"]);
            remotepost.Add("description", request["description"]);
            remotepost.Add("address_line_1", request["address_line_1"]);
            remotepost.Add("address_line_2", request["address_line_2"]);
            remotepost.Add("phone", request["phone"]);
            remotepost.Add("email", request["email"]);
            remotepost.Add("city", request["city"]);
            remotepost.Add("state", request["state"]);
            remotepost.Add("country", request["country"]);
            remotepost.Add("zip_code", request["zip_code"]);
            remotepost.Add("udf1", request["udf1"]);
            remotepost.Add("udf2", request["udf2"]);
            remotepost.Add("udf3", request["udf3"]);
            remotepost.Add("udf4", request["udf4"]);
            remotepost.Add("udf5", request["udf5"]);
            remotepost.Add("hash", gethash(hash_columns, request));
            remotepost.Post();
        }




        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Return(FormCollection form)
        {
            try
            {
                string transaction_id = string.Empty;
                string[] keys = Request.Form.AllKeys;
                Array.Sort(keys);


                string hash = gethash(keys, form);
                if (form["hash"] == hash)
                {
                    if (form["response_code"] == "0")
                    {
                        transaction_id = Request.Form["transaction_id"];
                        ViewData["Message"] = "Transaction is successful. Hash value is matched";
                    }
                    else
                    {
                        string response_message = Request.Form["response_message"];
                        Response.Write(response_message);
                    }

                }
                else
                {
                    ViewData["Message"] = "Hash value Not matched";
                }

            }
            catch (Exception ex)
            {
                Response.Write("<span style='color:red'>" + ex.Message + "</span>");

            }
            return View("../Return/Return");
        }





        public string gethash(string[] hash_columns, FormCollection requests)
        {

            string checksumString;
            checksumString = salt;
            foreach (string column in hash_columns)
            {
                if (requests.Get(column) != null && column != "hash")
                {
                    if (!string.IsNullOrEmpty(requests[column]))
                    {
                        checksumString += "|" + requests[column];
                    }
                }

            }
            string result = Generatehash512(checksumString);
            return result;
        }


        public string Generatehash512(string text)
        {

            byte[] message = System.Text.Encoding.UTF8.GetBytes(text);

            System.Text.UnicodeEncoding UE = new UnicodeEncoding();
            byte[] hashValue;
            SHA512Managed hashString = new SHA512Managed();
            string hex = "";
            hashValue = hashString.ComputeHash(message);
            foreach (byte x in hashValue)
            {
                hex += String.Format("{0:x2}", x);
            }
            return hex.ToUpper();

        }

        public class RemotePost
        {
            private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();


            public string Url = "";
            public string Method = "post";
            public string FormName = "form1";

            public void Add(string name, string value)
            {
                Inputs.Add(name, value);
            }

            public void Post()
            {
                System.Web.HttpContext.Current.Response.Clear();

                System.Web.HttpContext.Current.Response.Write("<html><head>");

                System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));
                System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));
                for (int i = 0; i < Inputs.Keys.Count; i++)
                {
                    System.Web.HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", Inputs.Keys[i], Inputs[Inputs.Keys[i]]));
                }
                System.Web.HttpContext.Current.Response.Write("</form>");
                System.Web.HttpContext.Current.Response.Write("</body></html>");

                System.Web.HttpContext.Current.Response.End();
            }
        }

    }
}