using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Agent_DMTRefundRequest : System.Web.UI.Page
{
    public static string Token = "WEFWRGDGDDSFSM333S";
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["LOGINID"] == null && Session["USERNAME"] == null)
            {
                Response.Redirect("../login.aspx");
            }
            if (!IsPostBack)
            {
                BindDataPendind();
            }
            
        }
        catch (Exception ex)
        {
            
        }
    }
    private void BindDataPendind()
    {
        
        try
        {
            SqlParameter[] warlock = new SqlParameter[2];
            warlock[0] = new SqlParameter("@LoginId", Convert.ToInt64(Session["LOGINID"]));
            if(txtTxnNo.Text.Trim()!="")
            {
                warlock[1] = new SqlParameter("@TxnNo", txtTxnNo.Text.Trim());
            }
            else
            {
                warlock[1]= new SqlParameter("@TxnNo", null);
            }
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_Get_Pending_DMTTransaction", warlock);
            if(ds.Tables[0].Rows.Count>0)
            {
                GvTransactionReport.DataSource = ds.Tables[0];
                GvTransactionReport.DataBind();
            }
            else
            {
                lblerror.Text = "No Pending Transaction Exists.";
            }
        }
        catch (Exception ev)
        {
            lblerror.Text = "erroe=" + ev.Message;
           
        }
    }
    protected void GvTransactionReport_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try {
            if(e.CommandName== "Status")
            {
                string Result=GetStatus(e.CommandArgument.ToString());
                lblerror.Text = Result;
                BindDataPendind();
            }
            else if(e.CommandName == "Refund")
            {
                string Result = GetStatus(e.CommandArgument.ToString());
                GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer;
                int rowIndex = gvr.RowIndex;
                if (Result== "SUCCESS")
                {
                    lblerror.Text = "Sorry! Unable to accept refund process for Success transaction";
                }
                else
                {
                    HiddenField hdnBeneID = (HiddenField)gvr.FindControl("hdnBeneID");
                    string SenderID = GvTransactionReport.DataKeys[rowIndex].Values["SenderId"].ToString();
                    string SenderMobile = GvTransactionReport.DataKeys[rowIndex].Values["SenderName"].ToString();
                    string beneId = GvTransactionReport.DataKeys[rowIndex].Values["Benificiary_ID"].ToString();
                    ViewState["SenderID"] = SenderID;
                    ViewState["SenderMobile"] = SenderMobile;
                    ViewState["beneId"] = beneId;
                    ViewState["RefNo"] = e.CommandArgument.ToString();
                    GenrateOTP(hdnBeneID.Value.ToString(), "transRefund", e.CommandArgument.ToString());
                }
                //BindDataPendind();
            }
        }
        catch(Exception ex)
        {
            lblerror.Text = "erroe=" + ex.Message;
        }
    }
    public void GenrateOTP(string BeniID, string ForRequest,string RefNo)
    {
        string Result = "";
        string url = "https://pwmr-api.payworldindia.com/associate/generateOtp.json";
        var payload = new
        {
            data = new
            {
                senderId = Convert.ToString(ViewState["SenderID"]),
                merchantUserId = 1026,
                senderMobileNo = Convert.ToString(ViewState["SenderMobile"]),
                beneficiaryId = BeniID,
                requestFor = ForRequest,
                referenceNumber = RefNo
            }
        };
        string Responsetoken = JWT_Token.Encode(payload, Token, JWT_Token.JwtHashAlgorithm.HS256);
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";
        httpWebRequest.Headers.Add("x-merchant-id", "8");
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = new JavaScriptSerializer().Serialize(new
            {
                requestToken = Responsetoken
            });
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            Result = streamReader.ReadToEnd();
        }
        if (Result != "")
        {
            InsertLog(RefNo, Result + "_" + Responsetoken, "GenerateOTPPay");
            JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
            JObject jsonResponse = JObject.Parse(Result);
            if (jsonResponse["responseCode"].ToString() == "0")
            {
                string finalResponse = JWT_Token.Decode(jsonResponse["data"].ToString(), Token);
                InsertLog(RefNo, finalResponse, "GenerateOTPPay2");
                btnAddConfirm.Visible = true;
                lblHeader.Text = "Refund OTP Verification";
                mp1.Show();
            }
        }
    }

    public string GetStatus(string RefNumber)
    {
        string Result = "";
        string FinalResult = "";
        string url = "https://pwmr-api.payworldindia.com/associate/reQuery.json";
        var payload = new
        {
            data = new
            {
                referenceNumber = RefNumber,
                merchantUserId = 1026
            }
        };
        string Responsetoken = JWT_Token.Encode(payload, Token, JWT_Token.JwtHashAlgorithm.HS256);
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";
        httpWebRequest.Headers.Add("x-merchant-id", "8");
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = new JavaScriptSerializer().Serialize(new
            {
                requestToken = Responsetoken
            });
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            Result = streamReader.ReadToEnd();
        }
        if (Result != "")
        {
            InsertLog(RefNumber, Result + "_" + Responsetoken, "GetStatus");
            JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
            JObject jsonResponse = JObject.Parse(Result);
	    //string finalResponse = JWT_Token.Decode(jsonResponse["data"].ToString(), Token);
            //InsertLog(RefNumber, finalResponse, "GetStatus2");
            if (jsonResponse["responseCode"].ToString() == "0" || jsonResponse["responseCode"].ToString() == "1018")
            {
                string finalResponse = JWT_Token.Decode(jsonResponse["data"].ToString(), Token);
                InsertLog(RefNumber, finalResponse, "GetStatus2");
                JObject objData = JObject.Parse(finalResponse);
                if (Convert.ToString(objData["status"]).ToUpper() == "SUCCESS")
                {
                    UpdateTransaxtionStatus(RefNumber, "Success", Convert.ToString(Session["WhitelabelId"]), Convert.ToString(Session["LOGINID"]));
                    //Agent_Card_Transaction_Insertin_ATT("Success", Convert.ToString(Session["LOGINID"]), FRqAmt, fare[3], 0, (FRqAmt + fare[3]), RefID, "", IPAddress, Convert.ToString(objData["benename"]), "", Convert.ToString(objData["beneficiaryId"]), txtTxnRemark.Text, Convert.ToString(objData["transferType"]), Convert.ToString(objData["bankReferenceNumber"]), lblTxnAccountNo.Text, Convert.ToString(Session["sendernumber"]), Convert.ToString(objData["senderId"]), Convert.ToString(objData["transactionId"]));
                }
                else if (Convert.ToString(objData["status"]).ToUpper() == "PENDING" || Convert.ToString(objData["status"]).ToUpper() == "INITIATED")
                {
                    
                }
                else if (Convert.ToString(objData["status"]).ToUpper() == "FAILED" || Convert.ToString(objData["status"]).ToUpper() == "FAILURE")
                {
                    UpdateTransaxtionStatus(RefNumber, "Fail", Convert.ToString(Session["WhitelabelId"]), Convert.ToString(Session["LOGINID"]));
                }
                FinalResult = Convert.ToString(objData["status"]).ToUpper();
            }
            else
            {
                FinalResult = jsonResponse["responseMessage"].ToString();
            }
            
        }
        return FinalResult;
    }
    public void UpdateTransaxtionStatus(string RefID, string Status, string WLID, string AgentID)
    {
        try
        {
            SqlParameter[] warlock = new SqlParameter[]
            {
                new SqlParameter("@RefId",RefID),
                new SqlParameter("@Status",Status),
                new SqlParameter("@WLID",WLID),
                new SqlParameter("@AgentID",AgentID)
            };
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UpdateTransactionStatus_Payworld", warlock);
        }
        catch (Exception ex)
        {
        }
    }
    public void InsertLog(string RefId, string Response, string ServiceName)
    {
        try
        {
            SqlParameter[] warlock = new SqlParameter[]
            {
                new SqlParameter("@RefId",RefId),
                new SqlParameter("@LogData",Response),
                new SqlParameter("@Service",ServiceName)
            };
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "InsertLog", warlock);
        }
        catch (Exception ex)
        {
        }
    }

    protected void btnAddConfirm_Click(object sender, EventArgs e)
    {
        string result = "";
        try
        {
            
                var payload = new
                {
                    data = new
                    {
                        senderId = Convert.ToString(ViewState["SenderID"]),
                        merchantUserId = 1026,
                        senderMobileNo = Convert.ToString(ViewState["SenderMobile"]),
                        beneficiaryId = Convert.ToString(ViewState["beneId"]),
                        requestFor = "transRefund",
                        otp = txtOTP.Text.Trim(),
                        referenceNumber = Convert.ToString(ViewState["RefNo"])
                    }
                };
                string Responsetoken = JWT_Token.Encode(payload, Token, JWT_Token.JwtHashAlgorithm.HS256);
                string url = "https://pwmr-api.payworldindia.com/associate/verifyOtp.json";


                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";
                httpWebRequest.Headers.Add("x-merchant-id", "8");
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = new JavaScriptSerializer().Serialize(new
                    {
                        requestToken = Responsetoken
                    });
                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();
                }

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }

                if (result != "")
                {
                    InsertLog(Convert.ToString(ViewState["RefNo"]), result + "_" + Responsetoken, "VerifyOTPPay");
                    JObject jsonResponse = JObject.Parse(result);
                    if (jsonResponse["responseCode"].ToString() == "0")
                    {
                         //GetStatus(Convert.ToString(ViewState["RefNo"]));
		UpdateTransaxtionStatus(Convert.ToString(ViewState["RefNo"]), "Fail", Convert.ToString(Session["WhitelabelId"]), Convert.ToString(Session["LOGINID"]));
                    }
                    else
                    {
                        lblerror.Text = jsonResponse["responseMessage"].ToString();
                    }
                }
                else
                {
                    lblerror.Text = " OTP verification process failed. Please try after some time.";
                }
        }
        catch (Exception ex)
        {
           
        }
        

    }

    protected void BtnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if(txtTxnNo.Text.Trim()=="")
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Please enter Transaction Reference No.');"), true);
                return;

            }
            else
            {
                BindDataPendind();
            }
        }
        catch(Exception ex)
        {

        }
    }
}