using Newtonsoft.Json;
using Sapphire.Ohu.BaseFramework.Utilities;
using Sapphire.Vidyalaya.BusinessEntity.Business.OnlinePaymentBE;
using Sapphire.Vidyalaya.BusinessLogic.Business.Common.CommonBL;
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_Hesabe_hesabeResponseHandler : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ReceiptGeneratedFlag.Value = "";
        if (!IsPostBack)
        {
            // Check if the 'data' parameter is present in the query string
            if (!string.IsNullOrEmpty(Request.QueryString["data"]))
            {
                string data = Request.QueryString["data"];
                string ReceiptBookId = Request.QueryString["ReceiptBookId"];
                CommonHelper.LogWriter("Hesabe Response : " + data, 1, "Hesabe Webview", HttpContext.Current.Request.Url.AbsoluteUri);

                CommonFunctions cf = new CommonFunctions();
                string SQL_String = string.Empty;
                DataSet DS = new DataSet();
                SQL_String = "SELECT ISNULL(GP.HesabeMerchantKey,'') AS HesabeMerchantKey,ISNULL(GP.HesabeMerchantIV,'') AS HesabeMerchantIV 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 = 17";
                DS = cf.GetDataset(SQL_String);
                if (DS != null && DS.Tables.Count > 0 && DS.Tables[0].Rows.Count > 0)
                {
                    string HesabeMerchantKey = DS.Tables[0].Rows[0]["HesabeMerchantKey"].ToString();
                    string HesabeMerchantIV = DS.Tables[0].Rows[0]["HesabeMerchantIV"].ToString();

                    // Initialize the HesabeCrypt encryption/decryption library using the KEY and IV from the configuration
                    var hesabeCrypt = new HesabeCrypt(HesabeMerchantKey, HesabeMerchantIV);

                    // Decrypt the response received in the data query string 
                    var dataDecrypted = hesabeCrypt.Decrypt(data);

                    // Trim the junk characters from the decrypted response if any.
                    dataDecrypted = dataDecrypted.Substring(0, dataDecrypted.LastIndexOf("}") + 1);

                    // Deserialize the decrypted response
                    var paymentResponse = JsonConvert.DeserializeObject<HesabePaymentResponse>(dataDecrypted);

                    CommonHelper.LogWriter("Hesabe Response status: " + paymentResponse.Status, 1, "Easebuzz Webview", HttpContext.Current.Request.Url.AbsoluteUri);
                    if (paymentResponse.Status && paymentResponse.Code == 1)
                    {
                        PaymentStatus.Value = "success";

                        string SQL_PaymentTransaction = "IF NOT EXISTS(SELECT 1 FROM [sFee].[tReceipt] WHERE [PaymentTransactionId] = " + paymentResponse.Response.OrderReferenceNumber + ") 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=" + paymentResponse.Response.OrderReferenceNumber + ",BankTransactionId=" + paymentResponse.Response.OrderReferenceNumber + ",BankName='Hesabe'," +
                                                 "PaymentType='NB',CardNumber='' WHERE Id =" + paymentResponse.Response.OrderReferenceNumber;
                            CF.GetDataset(SQLString);
                        }
                        else
                        {
                            ReceiptGeneratedFlag.Value = "ReceiptAlreadyGenerated";
                            PaymentStatus.Value = "success";
                        }
                        CommonHelper.LogWriter("Hesabe Response ReceiptGeneratedFlag: " + ReceiptGeneratedFlag.Value, 1, "Hesabe Webview", HttpContext.Current.Request.Url.AbsoluteUri);
                    }
                    else
                    {
                        PaymentStatus.Value = "fail";
                        string SQLString = "UPDATE sOp.tPaymentTransaction SET TransactionStatusId =3," +
                                           "MerchantTransactionId=" + paymentResponse.Response.OrderReferenceNumber + ",BankTransactionId=" + paymentResponse.Response.OrderReferenceNumber + ",BankName='Hesabe'," +
                                           "PaymentType='NB',CardNumber='' WHERE Id =" + paymentResponse.Response.OrderReferenceNumber;
                        CommonFunctions CF = new CommonFunctions();
                        CF.GetDataset(SQLString);
                    }

                }
                CommonHelper.LogWriter("Hesabe Payment Status : " + PaymentStatus.Value, 1, "Hesabe Webview", HttpContext.Current.Request.Url.AbsoluteUri);
            }
        }
    }
}