using Sapphire.Ohu.BaseFramework.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
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_RazorpayCollectNow_RazorpayCollectNowResponseHandler : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CommonHelper.LogWriter("Integration_RazorpayCollectNow_RazorpayCollectNowResponseHandler Called", 1, "Razorpay Collect Now Webview", HttpContext.Current.Request.Url.AbsoluteUri);
        NameValueCollection nvc = Request.Form;
        foreach (string key in nvc.AllKeys)
        {
            string value = nvc[key];
            CommonHelper.LogWriter("Integration_RazorpayCollectNow_RazorpayCollectNowResponseHandler Response Form: " + "Key: " + key + ", Value: " + value, 1, "Razorpay Collect Now Webview", HttpContext.Current.Request.Url.AbsoluteUri);
        }
        if (nvc.Count > 0)
        {
            CommonHelper.LogWriter("Integration_RazorpayCollectNow_RazorpayCollectNowResponseHandler nvc.Count " + nvc.Count, 1, "Razorpay Collect Now Webview", HttpContext.Current.Request.Url.AbsoluteUri);
            string PaymentTransactionId = Request.QueryString["PaymentTransactionId"];
            CommonFunctions cf = new CommonFunctions();
            string SQL_String = string.Empty;
            DataSet ds = new DataSet();
            SQL_String = "SELECT TOP 1 ISNULL(GP.RazorpayCollectNowMID,'') AS RazorpayCollectNowMID,ISNULL(GP.RazorpayCollectNowKeyID,'') AS RazorpayCollectNowKeyID,ISNULL(GP.RazorpayCollectNowSecretKey,'') AS RazorpayCollectNowSecretKey FROM sOp.tGatewayproduct GP"
                           + " INNER JOIN sOp.tGatewayConfiguration GC ON GC.Id = GP.GatewayConfigurationId"
                           + " INNER JOIN sOp.tGatewayProductReceiptBookMapping GPRBM ON GPRBM.GatewayProductId = GP.Id"
                           + " INNER JOIN sOp.tPaymentTransaction PT ON PT.PaymentGatewayId = GC.PaymentGatewayId"
                           + " INNER JOIN sFee.tOnlineFee TOF ON TOF.Id = PT.TransactionSourceId AND GPRBM.ReceiptBookId = TOF.ReceiptBookId"
                           + " WHERE PT.PaymentGatewayId = 18 AND ISNULL(GPRBM.IsObsolete,0) = 0 AND PT.TransactionSourceTypeId = 2024 AND PT.Id = " + PaymentTransactionId;

            CommonHelper.LogWriter("Integration_RazorpayCollectNow_RazorpayCollectNowResponseHandler SQL_String: " + SQL_String, 1, "Razorpay Collect Now Webview", HttpContext.Current.Request.Url.AbsoluteUri);

            ds = cf.GetDataset(SQL_String);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                string RazorpayCollectNowMID = "", RazorpayCollectNowKeyID = "", RazorpayCollectNowSecretKey = "";
                RazorpayCollectNowMID = ds.Tables[0].Rows[0]["RazorpayCollectNowMID"].ToString();
                RazorpayCollectNowKeyID = ds.Tables[0].Rows[0]["RazorpayCollectNowKeyID"].ToString();
                RazorpayCollectNowSecretKey = ds.Tables[0].Rows[0]["RazorpayCollectNowSecretKey"].ToString();
                if (!string.IsNullOrEmpty(RazorpayCollectNowMID) && !string.IsNullOrEmpty(RazorpayCollectNowKeyID) && !string.IsNullOrEmpty(RazorpayCollectNowSecretKey))
                {
                    string TransactionRequest = "Select TransactionRequest from sOp.tPaymentTransaction Where Id=" + PaymentTransactionId;
                    DataSet TransactionRequestDS = cf.GetDataset(TransactionRequest);
                    string ActualOrderId = string.Empty, ActualRequest = 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();

                        if (!string.IsNullOrEmpty(ActualRequest))
                        {
                            string[] RequestArray = ActualRequest.Split('&');
                            ActualRequest = RequestArray[2].Substring(9);
                            ActualOrderId = ActualRequest;
                        }
                    }

                    string paymentId = Request.Form["razorpay_payment_id"];
                    string Orderid = Request.Form["razorpay_order_id"];
                    string razorpay_signature = Request.Form["razorpay_signature"];

                    if (ActualOrderId == Orderid)
                    {
                        string Actual_generated_signature = calculateRFC2104HMAC(ActualOrderId + "|" + Request.Form["razorpay_payment_id"], RazorpayCollectNowSecretKey);
                        string generated_signature = calculateRFC2104HMAC(Orderid + "|" + Request.Form["razorpay_payment_id"], RazorpayCollectNowSecretKey);

                        string responseData;
                        responseData = "Key=" + RazorpayCollectNowKeyID
                           + "&Paymentid=" + Request.Form["razorpay_payment_id"]
                           + "&Orderid=" + Request.Form["razorpay_order_id"]
                           + "&Response_Signature=" + Request.Form["razorpay_signature"]
                           + "&PaymentTransactionId=" + PaymentTransactionId
                           + "&Actual_Generated_Signature=" + Actual_generated_signature
                           + "&Generated_Signature=" + generated_signature;

                        CommonHelper.LogWriter("Razorpay Collect Now Response : " + responseData, 1, "Razorpay Collect Now Webview", HttpContext.Current.Request.Url.AbsoluteUri);

                        if (generated_signature == razorpay_signature && Actual_generated_signature == generated_signature && Actual_generated_signature == razorpay_signature)
                        {
                            PaymentStatus.Value = "success";

                            string SQL_PaymentTransaction = "IF NOT EXISTS(SELECT 1 FROM [sFee].[tReceipt] WHERE [PaymentTransactionId] = " + PaymentTransactionId + ") 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=" + PaymentTransactionId + ",BankTransactionId=" + PaymentTransactionId + ",BankName='Razorpay Collect Now'," +
                                                     "PaymentType='NB',CardNumber='',TransactionResponse='" + responseData + "' WHERE Id =" + PaymentTransactionId;
                                CF.GetDataset(SQLString);
                            }
                            else
                            {
                                string SQLString = "UPDATE sOp.tPaymentTransaction SET TransactionStatusId = 2," +
                                                     "MerchantTransactionId=" + PaymentTransactionId + ",BankTransactionId=" + PaymentTransactionId + ",BankName='Razorpay Collect Now'," +
                                                     "PaymentType='NB',CardNumber='',TransactionResponse='" + responseData + "' WHERE Id =" + PaymentTransactionId;
                                CF.GetDataset(SQLString);

                                ReceiptGeneratedFlag.Value = "ReceiptAlreadyGenerated";
                                PaymentStatus.Value = "success";
                            }
                            CommonHelper.LogWriter("Easebuzz Response ReceiptGeneratedFlag: " + ReceiptGeneratedFlag.Value, 1, "Razorpay Collect Now Webview", HttpContext.Current.Request.Url.AbsoluteUri);
                        }
                        else
                        {
                            PaymentStatus.Value = "fail";
                            string SQLString = "UPDATE sOp.tPaymentTransaction SET TransactionStatusId = 3," +
                                                "MerchantTransactionId=" + PaymentTransactionId + ",BankTransactionId=" + PaymentTransactionId + ",BankName='Razorpay Collect Now'," +
                                                "PaymentType='NB',CardNumber='',TransactionResponse='" + responseData + "' WHERE Id =" + PaymentTransactionId;
                            CommonFunctions CF = new CommonFunctions();
                            CF.GetDataset(SQLString);
                        }
                    }
                    else
                    {
                        string TransactionResponse = "OrderIdNotMatched";
                        if (string.IsNullOrEmpty(Orderid)) { TransactionResponse = "Transaction Failed or OrderId Is null"; }
                        PaymentStatus.Value = "fail";
                        string SQLString = "UPDATE sOp.tPaymentTransaction SET TransactionStatusId = 3," +
                                            "MerchantTransactionId=" + PaymentTransactionId + ",BankTransactionId=" + PaymentTransactionId + ",BankName='Razorpay Collect Now'," +
                                            "PaymentType='NB',CardNumber='',TransactionResponse='" + TransactionResponse + "' WHERE Id =" + PaymentTransactionId;
                        CommonFunctions CF = new CommonFunctions();
                        CF.GetDataset(SQLString);
                    }
                }
            }
        }
    }
    public string calculateRFC2104HMAC(String data, String secret)
    {
        string result = "";
        try
        {
            using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(secret)))
            {
                var payload = Encoding.ASCII.GetBytes(data);
                var rawHmac = hmac.ComputeHash(payload);
                result = HashEncode(rawHmac);
            }
        }
        catch (Exception e)
        {
        }
        return result;
    }
    private string HashEncode(byte[] hash)
    {
        return BitConverter.ToString(hash).Replace("-", "").ToLower();
    }
}