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_SenderRegPay : System.Web.UI.Page
{
    public static string Token = "WEFWRGDGDDSFSM333S";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lblmsg.Text = "Sender not found. Retry with different sender id Or Register Sender";
            txtSenderNo.Text = Convert.ToString(Session["sendernumber"]);
        }
    }
    protected void btnReg_Click(object sender, EventArgs e)
    {
        string Result = "";
        if (txtSenderNo.Text.Trim() != "" || txtSenderName.Text.Trim() != "" || txtBeniName.Text.Trim() != "" || txtBeniAccount.Text.Trim() != "" || txtBebiIFSC.Text.Trim() != "" || txtBeniMobile.Text.Trim() != "")
        {
            string url = "https://pwmr-api.payworldindia.com/associate/senderRegistration.json";
            var payload = new
            {
                data = new
                {
                    senderMobileNo = Convert.ToString(Session["sendernumber"]),
                    senderGender = ddlGender.SelectedValue,
                    senderName = txtSenderName.Text.Trim(),
                    merchantUserId = 1026,
                    senderBeneficiary = new
                    {
                        name = txtBeniName.Text,
                        accountNumber = txtBeniAccount.Text,
                        ifsc = txtBebiIFSC.Text,
                        accountType = ddlBeniAccountType.SelectedValue,
                        mobileNo = txtBeniMobile.Text,
                        emailId = txtBeniEmail.Text
                    }
                }
            };
            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(Convert.ToString(Session["sendernumber"]), Result+"_"+ Responsetoken, "RegistrationPay");

                JObject jsonResponse = JObject.Parse(Result);
               


                if (jsonResponse["responseCode"].ToString() == "0")
                {
                    string FinalResult = JWT_Token.Decode(jsonResponse["data"].ToString(), Token);
                    JObject jsonFinalResult = JObject.Parse(FinalResult);
                    lblmsg.Text = "Sender and Beneficiary added successfully OTP sent to registered Mobile.";
                    lblHeader.Text = "OTP Verification";
                   // JObject objData = (JObject)jsonResponse["data"];
                    Session["SenderId"] = jsonFinalResult["senderId"].ToString();
                    ViewState["senderMobileNo"] = jsonFinalResult["senderMobileNo"].ToString();
                    ViewState["BenificiaryID"] = jsonFinalResult["beneficiaryId"].ToString();
                    //url = "MoneyTransferPay.aspx";
                    //string script = "window.onload = function(){ alert('";
                    //script += message;
                    //script += "');";
                    //script += "window.location = '";
                    //script += url;
                    //script += "'; }";
                    //ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
                    mp1.Show();
                }
                else
                {
                    lblmsg.Text = jsonResponse["responseMessage"].ToString();
                }

            }
            else
            {
                lblmsg.Text = "Sender Registration process failed. Please try after some time.";
            }
        }
        else
        {
            lblmsg.Text = "Please enter all mandatory fields.";
        }
    }
    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 = "";
        if (txtOTP.Text.Trim() != "")
        {
            string url = "https://pwmr-api.payworldindia.com/associate/verifyOtp.json";
            var payload = new
            {
                data = new
                {
                    senderId = Convert.ToString(Session["sendernumber"]),
                    merchantUserId = 1026,
                    senderMobileNo = Convert.ToString(ViewState["senderMobileNo"]),
                    beneficiaryId = Convert.ToString(ViewState["beneficiaryId"]),
                    requestFor = "benVerification",
                    otp = txtOTP.Text,
                    referenceNumber = ""
                }
            };
            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(Convert.ToString(Session["sendernumber"]), Result + "_" + Responsetoken, "RegConfirmPay");
                JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
                JObject jsonResponse = JObject.Parse(Result);
                if (jsonResponse["responseCode"].ToString() == "0")
                {
                    url = "MoneyTransferPay.aspx";
                    string message = "OTP verification successfully.";
                    string script = "window.onload = function(){ alert('";
                    script += message;
                    script += "');";
                    script += "window.location = '";
                    script += url;
                    script += "'; }";
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
                }
                else
                {
                    url = "MoneyTransferPay.aspx";
                    string message = "OTP verification Failed.";
                    string script = "window.onload = function(){ alert('";
                    script += message;
                    script += "');";
                    script += "window.location = '";
                    script += url;
                    script += "'; }";
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
                }
            }
        }
        else
        {
         
        }
    }
}