using Sapphire.Ohu.BaseFramework.Utilities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Integration_Easebuzz_easebuzzResponseHandler : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ReceiptGeneratedFlag.Value = "";
        string[] merc_hash_vars_seq;
        string merc_hash_string = string.Empty;
        string merc_hash = string.Empty;
        string order_id = string.Empty;
        string hash_seq = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
        string QueryString = Request.Url.Query;
        order_id = Request.Form["txnid"];
        CommonHelper.PaymentLogWriter("Easebuzz Response txnid: " + order_id, 2, "Easebuzz Webview", HttpContext.Current.Request.Url.AbsoluteUri);

        string ReceiptBookId = Request.QueryString["ReceiptBookId"];
        CommonFunctions cf = new CommonFunctions();
        string SQL_String = string.Empty;
        DataSet ds = new DataSet();
        SQL_String = "SELECT GP.GatewayURL,ISNULL(GP.EasebuzzKey,'') AS EasebuzzKey,ISNULL(GP.EasebuzzSalt,'') AS EasebuzzSalt FROM sOp.tGatewayProduct GP INNER JOIN sOp.tGatewayConfiguration GC ON GC.Id = GP.GatewayConfigurationId  INNER JOIN sOp.tGatewayProductReceiptBookMapping GPRBM ON GP.Id = GPRBM.GatewayProductId WHERE ReceiptBookId  = " + ReceiptBookId + " AND ISNULL(GPRBM.IsObsolete,0) = 0 AND GC.PaymentGAtewayId = 15";
        ds = cf.GetDataset(SQL_String);

        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            string EasebuzzSalt = ds.Tables[0].Rows[0]["EasebuzzSalt"].ToString();
            string TransactionRequest = "Select TransactionRequest from sOp.tPaymentTransaction Where Id=" + Request.Form["txnid"];
            DataSet TransactionRequestDS = cf.GetDataset(TransactionRequest);
            string ActualRequest = string.Empty, req_gen_hash = string.Empty, req_merc_hash = string.Empty;

            if (TransactionRequestDS != null && TransactionRequestDS.Tables.Count > 0 && TransactionRequestDS.Tables[0] != null && TransactionRequestDS.Tables[0].Rows.Count > 0)
            {
                ActualRequest = TransactionRequestDS.Tables[0].Rows[0]["TransactionRequest"].ToString();
                CommonHelper.PaymentLogWriter("Easebuzz Actual Transaction Request : " + ActualRequest, 2, "Easebuzz Webview", HttpContext.Current.Request.Url.AbsoluteUri);
                if (!string.IsNullOrEmpty(ActualRequest))
                {
                    var keyValuePairs = new Dictionary<string, string>();
                    var queryParameters = ActualRequest.Split('&');
                    foreach (var parameter in queryParameters)
                    {
                        var keyValuePair = parameter.Split(new[] { '=' }, 2);
                        if (keyValuePair.Length == 2)
                        {
                            if (HttpUtility.UrlDecode(keyValuePair[0]) == "amount")
                            {
                                keyValuePair[1] = !keyValuePair[1].ToString().Trim().Contains(".") ? keyValuePair[1] + ".0" : keyValuePair[1];
                            }
                            keyValuePairs.Add(HttpUtility.UrlDecode(keyValuePair[0]), HttpUtility.UrlDecode(keyValuePair[1]));
                        }
                    }
                    req_gen_hash = EasebuzzSalt
                        + "|" + Request.Form["status"] + "|" + keyValuePairs["udf10"]
                        + "|" + keyValuePairs["udf9"] + "|" + keyValuePairs["udf8"]
                        + "|" + keyValuePairs["udf7"] + "|" + keyValuePairs["udf6"]
                        + "|" + keyValuePairs["udf5"] + "|" + keyValuePairs["udf4"]
                        + "|" + keyValuePairs["udf3"] + "|" + keyValuePairs["udf2"]
                        + "|" + keyValuePairs["udf1"] + "|" + keyValuePairs["email"]
                        + "|" + keyValuePairs["firstname"] + "|" + keyValuePairs["productinfo"]
                        + "|" + keyValuePairs["amount"] + "|" + keyValuePairs["txnid"]
                        + "|" + keyValuePairs["key"];
                    req_merc_hash = Easebuzz_Generatehash512(req_gen_hash).ToLower();
                    CommonHelper.PaymentLogWriter("Easebuzz Transaction Request Hash: " + req_merc_hash, 2, "Easebuzz Webview", HttpContext.Current.Request.Url.AbsoluteUri);
                }
            }
            merc_hash_vars_seq = hash_seq.Split('|');
            Array.Reverse(merc_hash_vars_seq);
            merc_hash_string = EasebuzzSalt + "|" + Request.Form["status"];

            foreach (string merc_hash_var in merc_hash_vars_seq)
            {
                merc_hash_string += "|";
                merc_hash_string = merc_hash_string + (Request.Form[merc_hash_var] != null ? Request.Form[merc_hash_var] : "");
            }
            CommonHelper.PaymentLogWriter("Easebuzz Response Hash: " + merc_hash_string, 2, "Easebuzz Webview", HttpContext.Current.Request.Url.AbsoluteUri);
            merc_hash = Easebuzz_Generatehash512(merc_hash_string).ToLower();
            string TransactionResponse = Request.Form.ToString();
            CommonHelper.PaymentLogWriter("Easebuzz Request Form Hash : " + Request.Form["hash"], 2, "Easebuzz Webview", HttpContext.Current.Request.Url.AbsoluteUri);

            if (merc_hash == Request.Form["hash"] && req_merc_hash == merc_hash && req_merc_hash == Request.Form["hash"])
            {
                CommonHelper.PaymentLogWriter("Easebuzz Response status: " + Request.Form["status"], 2, "Easebuzz Webview", HttpContext.Current.Request.Url.AbsoluteUri);
                if (Request.Form["status"] == "success")
                {
                    PaymentStatus.Value = "success";
                    string SQL_PaymentTransaction = "IF NOT EXISTS(SELECT 1 FROM [sFee].[tReceipt] WHERE [PaymentTransactionId] = " + order_id + ") SELECT 1 AS PaymentTransactionExists";
                    CommonFunctions CF = new CommonFunctions();
                    DataSet PaymentTransactionDS = CF.GetDataset(SQL_PaymentTransaction);
                    if (PaymentTransactionDS != null && PaymentTransactionDS.Tables != null && PaymentTransactionDS.Tables[0] != null && PaymentTransactionDS.Tables[0].Rows.Count > 0)
                    {
                        string SQLString = "UPDATE sOp.tPaymentTransaction SET TransactionStatusId =2," +
                                             "MerchantTransactionId=" + order_id + ",BankTransactionId=" + order_id + ",BankName='Easebuzz'," +
                                             "PaymentType='NB',CardNumber='' WHERE Id =" + order_id;
                        CF.GetDataset(SQLString);
                    }
                    else
                    {
                        ReceiptGeneratedFlag.Value = "ReceiptAlreadyGenerated";
                        PaymentStatus.Value = "success";
                    }
                    CommonHelper.PaymentLogWriter("Easebuzz Response ReceiptGeneratedFlag: " + ReceiptGeneratedFlag.Value, 2, "Easebuzz Webview", HttpContext.Current.Request.Url.AbsoluteUri);
                }
                else if (Request.Form["status"] == "initiated" || Request.Form["status"] == "pending")
                {
                    PaymentStatus.Value = "initiated";
                    string SQLString = "UPDATE sOp.tPaymentTransaction SET TransactionStatusId = 1," +
                                       "MerchantTransactionId=" + order_id + ",BankTransactionId=" + order_id + ",BankName='Easebuzz'," +
                                       "PaymentType='NB',CardNumber='' WHERE Id =" + order_id;
                    CommonFunctions CF = new CommonFunctions();
                    CF.GetDataset(SQLString);
                }
                else
                {
                    PaymentStatus.Value = "fail";
                    string SQLString = "UPDATE sOp.tPaymentTransaction SET TransactionStatusId =3," +
                                       "MerchantTransactionId=" + order_id + ",BankTransactionId=" + order_id + ",BankName='Easebuzz'," +
                                       "PaymentType='NB',CardNumber='' WHERE Id =" + order_id;
                    CommonFunctions CF = new CommonFunctions();
                    CF.GetDataset(SQLString);
                }
            }
            else
            {
                CommonHelper.PaymentLogWriter("Easebuzz Response merc_hash: " + merc_hash, 2, "Easebuzz Webview", HttpContext.Current.Request.Url.AbsoluteUri);
                CommonHelper.PaymentLogWriter("Easebuzz Response req hash: " + Request.Form["hash"], 2, "Easebuzz Webview", HttpContext.Current.Request.Url.AbsoluteUri);
                PaymentStatus.Value = "fail";
                string SQLString = "UPDATE sOp.tPaymentTransaction SET TransactionStatusId =3," +
                                    "MerchantTransactionId=" + order_id + ",BankTransactionId=" + order_id + ",BankName='Easebuzz'," +
                                    "PaymentType='NB',CardNumber='' WHERE Id =" + order_id;
                CommonFunctions CF = new CommonFunctions();
                CF.GetDataset(SQLString);
            }
            CommonHelper.PaymentLogWriter("Easebuzz Payment Status : " + PaymentStatus.Value, 2, "Easebuzz Webview", HttpContext.Current.Request.Url.AbsoluteUri);
        }
    }

    // hashcode generation
    public string Easebuzz_Generatehash512(string text)
    {

        byte[] message = Encoding.UTF8.GetBytes(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;
    }
}