using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Linq;
using System.Net;
using Newtonsoft.Json;
using Sapphire.Ohu.BaseFramework.Utilities;
using System.Configuration;
using System.Data;
public partial class GenerateChecksum : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (Request.Form.AllKeys.Length > 0)
        //{
            try
            {
                CommonFunctions cf = new CommonFunctions();
                string MERCHANT_KEY = Request.QueryString["MERCHANT_KEY"];
                string MID = Request.QueryString["MID"];
                string ORDER_ID = Request.QueryString["ORDER_ID"];
                string CUST_ID = Request.QueryString["CUST_ID"];
                string CHANNEL_ID = Request.QueryString["CHANNEL_ID"];
                string INDUSTRY_TYPE_ID = Request.QueryString["INDUSTRY_TYPE_ID"];
                string WEBSITE = Request.QueryString["WEBSITE"];
                string TXN_AMOUNT = Request.QueryString["TXN_AMOUNT"];
                string CALLBACK_URL = Request.QueryString["CALLBACK_URL"];

                Dictionary<string, object> body = new Dictionary<string, object>();
                Dictionary<string, string> head = new Dictionary<string, string>();
                Dictionary<string, object> requestBody = new Dictionary<string, object>();

                Dictionary<string, string> txnAmount = new Dictionary<string, string>();
                txnAmount.Add("value", TXN_AMOUNT);
                txnAmount.Add("currency", "INR");
                Dictionary<string, string> userInfo = new Dictionary<string, string>();
                userInfo.Add("custId", CUST_ID);
                body.Add("requestType", "Payment");
                body.Add("mid", MID);
                body.Add("websiteName", WEBSITE);
                body.Add("orderId", ORDER_ID);
                body.Add("txnAmount", txnAmount);
                body.Add("userInfo", userInfo);
                body.Add("callbackUrl", CALLBACK_URL);
                
                string paytmChecksum = Paytm.Checksum.generateSignature(JsonConvert.SerializeObject(body), MERCHANT_KEY);
                
                head.Add("signature", paytmChecksum);

                requestBody.Add("body", body);
                requestBody.Add("head", head);

                string post_data = JsonConvert.SerializeObject(requestBody);

                CommonHelper.LogWriter("Paytm post_data : " + post_data, 1, "GenerateChecksumIOS", HttpContext.Current.Request.Url.AbsoluteUri);

                string url = string.Empty;
                int OrgGroupId = int.Parse(ConfigurationManager.AppSettings["DefaultOrgGroupId"].ToString());
                string SQL = "SELECT ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 464 AND SourceId = " + OrgGroupId + " AND SourceTypeId = 2010";
                DataSet ds = cf.GetDataset(SQL);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0][0].ToString() == "True")
                        url = "https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid=" + MID + "&orderId=" + ORDER_ID;
                    else
                        url = "https://securegw.paytm.in/theia/api/v1/initiateTransaction?mid=" + MID + "&orderId=" + ORDER_ID;
                }
                else
                    url = "https://securegw.paytm.in/theia/api/v1/initiateTransaction?mid=" + MID + "&orderId=" + ORDER_ID;

                CommonHelper.LogWriter("Paytm initiateTransaction : " + url, 1, "GenerateChecksumIOS", HttpContext.Current.Request.Url.AbsoluteUri);

                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11;

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

                webRequest.Method = "POST";
                webRequest.ContentType = "application/json";
                webRequest.ContentLength = post_data.Length;

                using (StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream()))
                {
                    requestWriter.Write(post_data);
                }

                string responseData = string.Empty;

                using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
                {
                    responseData = responseReader.ReadToEnd();
                    Console.WriteLine(responseData);
                }

                //string responseData = "{\"head\":{\"responseTimestamp\":\"1526969112101\",\"version\":\"v1\",\"clientId\":\"C11\",\"signature\":\"TXBw50YPUKIgJd8gR8RpZuOMZ+csvCT7i0/YXmG//J8+BpFdY5goPBiLAkCzKlCkOvAQip/Op5aD6Vs+cNUTjFmC55JBxvp7WunZ45Ke2q0=\"},\"body\":{\"resultInfo\":{\"resultStatus\":\"S\",\"resultCode\":\"0000\",\"resultMsg\":\"Success\"},\"txnToken\":\"fe795335ed3049c78a57271075f2199e1526969112097\",\"isPromoCodeValid\":false,\"authenticated\":false}}";
                dynamic data = Newtonsoft.Json.Linq.JObject.Parse(responseData);
                CommonHelper.LogWriter("Paytm data : " + data, 1, "GenerateChecksumIOS", HttpContext.Current.Request.Url.AbsoluteUri);

                string txnToken = data.body.txnToken;
                CommonHelper.LogWriter("Paytm txnToken : " + txnToken, 1, "GenerateChecksumIOS", HttpContext.Current.Request.Url.AbsoluteUri);

                Response.AddHeader("Content-type", "application/json");
                Response.Write("{\"ORDER_ID\":\"" + ORDER_ID + "\",\"CHECKSUMHASH\":\"" + paytmChecksum + "\",\"payt_STATUS\":\"1\",\"txnToken\":\"" + txnToken + "\",\"PaytmMID\":\"" + MID + "\"}");
            }
            catch (Exception)
            {
            }
        //}
    }   
}
