using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DMROBJECT;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data.SqlClient;
using DMRGOPROCESSING;

public partial class Agent_MoneyTransferGo : System.Web.UI.Page
{
    AirEpointSupport _objTransaction = new AirEpointSupport();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindBank();

        }
        // mp1.Show();
    }
    protected void btnsubmit_Click(object sender, EventArgs e)
    {
        try
        {
            string result = "";
            string sendernumber = txtMobileNo.Text.Trim();
            Session["sendernumber"] = sendernumber;
            if (IsInteger(sendernumber))
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.goprocessing.in/dmt/moneyGetDetails.go");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = new JavaScriptSerializer().Serialize(new
                    {
                        goid = "5201078519",
                        apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
                        rtype = "json",
                        apimode = "live",
                        service_family = "25",
                        agent_id = "Venus001",
                        msisdn = sendernumber
                                    

                    });
                    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("5201078520", result, "GoProGetDetails");
                    JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
                    JObject jsonResponse = JObject.Parse(result);
                    if (jsonResponse["status"].ToString() == "2")
                    {
                        if (jsonResponse["error_code"].ToString() == "981")
                        {
                            divSender.Visible = false;
                            gvBeni.Visible = false;
                            lblmsg.Text = "";



                            string message = "Sender not found. Retry with different sender id Or Register Sender";
                            string url = "SenderRegistrationGo.aspx";
                            string script = "window.onload = function(){ alert('";
                            script += message;
                            script += "');";
                            script += "window.location = '";
                            script += url;
                            script += "'; }";
                            ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", script, true);

                        }
                    
                       
                    }
                    if (jsonResponse["status"].ToString() == "1")
                    {
                        if (jsonResponse["otp_status"].ToString() == "1")
                        {
                            //Open popup for OTP
                            lblHeader.Text = "Confirm Customer Verification";
                            btnDeleteConfirm.Visible = true;
                            ViewState["flag"] = "customer";
                            ViewState["trans_id"] = Convert.ToString(jsonResponse["trans_id"]);
                            btnAddConfirm.Visible = false;
                            mp1.Show();


                        }
                        else
                        {
                            divSender.Visible = true;
                            txtSenderId.Text = Convert.ToString(Session["sendernumber"]);
                            Session["SenderId"] = jsonResponse["msisdn"].ToString();
                            lblsenderId.Text = jsonResponse["msisdn"].ToString();
                            ViewState["SenderName"] = lblsendername.Text = jsonResponse["user_name"].ToString();
                            if (jsonResponse["is_kyc"].ToString() == "0")
                                lblKYCStatus.Text = "Not Updated";
                            else
                                lblKYCStatus.Text = "Updated";
                            lblsenderLimit.Text = jsonResponse["remaining_limit"].ToString();

                            JArray objResponse = (JArray)jsonResponse["beneficiary"];
                            if (objResponse.Count > 0)
                            {
                                
                                List<Beneficiary> OBene = objResponse.ToObject<List<Beneficiary>>();
                                if (OBene.Count > 0)
                                {
                                    gvBeni.Visible = true;
                                    gvBeni.DataSource = OBene;
                                    gvBeni.DataBind();
                                }
                                else
                                {
                                    gvBeni.DataSource = null;
                                    gvBeni.DataBind();
                                }
                            }

                        }
                    }
                    
                }
            }
            else
            {
                lblmsg.Text = "Invalid Customer Mobile Number.";
            }
        }
        catch (Exception ex)
        {
        }
        finally
        {
            ResetBene();
        }
    }

    private string PostRequest(string url, string senderno)
    {
        string result = "";
        try
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    Key = "7ef37a4185480cebda9430277939c47ce93b4183",
                    AgentID = "3890",
                    SenderMobile = senderno
                });
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }
            return result;
        }
        catch (Exception ex)
        {
            return result;
        }
    }
    private bool IsInteger(string str)
    {
        Regex regex = new Regex(@"^[0-9]+$");
        try
        {
            if (String.IsNullOrWhiteSpace(str))
            {
                return false;
            }
            if (!regex.IsMatch(str))
            {
                return false;
            }
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    public void BindBank()
    {
        string result = "";
        try
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.goprocessing.in/getServiceData.go");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    goid = "5201078519",
                    apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
                    type = "bank",
                    rtype = "json"
                });
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }
            if (result != "")
            {
                JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
                JObject jsonResponse = JObject.Parse(result);
                if (jsonResponse["status"].ToString() == "1")
                {
                    JArray objResponse = (JArray)jsonResponse["result"];
                    if (objResponse.Count > 0)
                    {
                        List<DMRGOPROCESSING.Bank> _objBank = objResponse.ToObject<List<DMRGOPROCESSING.Bank>>();
                        foreach (DMRGOPROCESSING.Bank p in _objBank.OrderBy(s => s.bank_name))
                        {
                            string listvalue = p.bank_id + "/" + p.bank_code + "/" + p.is_without_ifsc;
                            ListItem item = new ListItem(p.bank_name, listvalue);
                            ddlBank.Items.Add(item);
                        }

                        ddlBank.Items.Insert(0, new ListItem("Select Bank", "0"));
                    }
                }
                else if (jsonResponse["status"].ToString() == "2")
                {
                    divSender.Visible = false;
                    lblmsg.Text = "Remitter Not Found.";
                }
            }
        }
        catch (Exception ex)
        {
        }
    }
    public decimal AgentBalance()
    {
        decimal balance = 0;
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",Convert.ToString(Session["LOGINID"]))
            };

            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getavailablebalance", get_user_details);
            if (dr.Read())
            {
                balance = Convert.ToDecimal(dr["balance"]);
            }
            return balance;
        }
        catch (Exception ex)
        {
            return balance;
        }
    }

    public int InsertDMRVerificationTxn(string RefID, string LoginId, string Service, decimal ReqAmount, string Vendor, string BeneMobile, string IPAddress)
    {
        SqlParameter[] InsertWithPendingStatusParam = new SqlParameter[]
        {
            new SqlParameter("@RefId",RefID),
            new SqlParameter("@LoginId",Convert.ToInt64(LoginId)),
            new SqlParameter("@Service",Service),
            new SqlParameter("@ReqAmount",ReqAmount),
            new SqlParameter("@Vendor",Vendor),
            new SqlParameter("@BeneMobile",BeneMobile),
            new SqlParameter("@IpAddress",IPAddress),
            new SqlParameter("@ErrorMessage",SqlDbType.Int)
        };
        InsertWithPendingStatusParam[7].Direction = ParameterDirection.Output;
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "InsertDMRVerificationTxn", InsertWithPendingStatusParam);
        int result = Convert.ToInt32(InsertWithPendingStatusParam[7].Value);
        return result;
    }
    protected void btnAddBeneSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtSenderId.Text.Trim() != "" && ddlBank.SelectedValue != "0" && txtBankAccount.Text.Trim() != "" && txtBeneName.Text.Trim() != "" && txtBeneMobile.Text.Trim() != "")
            {
                if (chkboxverify.Checked)
                {
                    string RefId = _objTransaction.Generate_TID();
                    decimal AgentBal = AgentBalance();
                    string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
                    if (AgentBal > 5)
                    {
                        int status1 = InsertDMRVerificationTxn(RefId, Convert.ToString(Session["LOGINID"]), "Account Verify", 4, "SoftZone", txtBeneMobile.Text.Trim(), IPAddress);
                        if (status1 == 1)
                        {
                            SendVerificationRequest(Convert.ToString(Session["sendernumber"]), Convert.ToString(Session["SenderId"]), txtBankAccount.Text.Trim(), txtIFSC.Text.Trim(), RefId, ddlBank.SelectedItem.Text, txtBeneName.Text.Trim(), txtBeneMobile.Text.Trim());
                        }
                    }
                    else
                    {
                        lblmsg.Visible = true;
                        lblmsg.Text = "You have not sufficient balance for Account Verification.";
                    }
                }
                else
                {
                    AddBeneficiaryAfterVerify(txtBankAccount.Text.Trim(), txtIFSC.Text.Trim(), "", txtBeneName.Text.Trim(), txtBeneMobile.Text.Trim());
                }


            }
            else
            {
                lblmsg.Visible = true;
                lblmsg.Text = "Please enter all mandatory fields.";
            }
        }
        catch (Exception ex)
        {
        }
        finally
        {
            ResetBene();
        }
    }

    public void SendVerificationRequest(string SenderMobile, string SenderId, string BankAccount, string IFSC, string REQUEST_ID, string Bank, string BeneName, string BeneMobile)
    {
        string Result = "";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.goprocessing.in/dmt/moneyVerification.go");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = new JavaScriptSerializer().Serialize(new
            {
                goid = "5201078519",
                apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
                rtype = "json",
                apimode = "live",
                service_family = "25",
                agent_id = "Venus001",
                verification_type="ANY",
                msisdn = Convert.ToString(Session["SenderId"]),
                client_trans_id=REQUEST_ID,
                beneficiary_account_no = BankAccount,
                beneficiary_ifsc_code = IFSC
            });
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            Result = streamReader.ReadToEnd();
        }
        if (Result != "")
        {
            JObject jsonResponse = JObject.Parse(Result);
            if (jsonResponse["status"].ToString() == "1")
            {
                if (jsonResponse["otp_status"].ToString() == "1")
                {
                    lblHeader.Text = "Confirm Account Verification";
                    btnDeleteConfirm.Visible = true;
                    ViewState["flag"] = "account";
                    ViewState["trans_id"] = Convert.ToString(jsonResponse["trans_id"]);
                    btnAddConfirm.Visible = false;
                    mp1.Show();

                }
                else
                {
                    //bank_trans_id
                    //trans_status
                    UpdateVerificationStatus("Success", REQUEST_ID);
                    //Add Beneficiary Process
                  //  AddBeneficiaryAfterVerify(BankAccount, IFSC, REQUEST_ID, BeneName, BeneMobile);
                    lblmsg.Visible = true;
                    lblmsg.Text = "Account Verification Process Successfully Done.";
                }

            }
            else
            {
                UpdateVerificationStatus("Fail", REQUEST_ID);
                lblmsg.Visible = true;
                lblmsg.Text = "Account Verification Process failed. Please check all Beneficiary details.";
            }
        }

    }
    protected void ddlBank_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlBank.SelectedValue != "0")
        {
           // txtIFSC.Text = ddlBank.SelectedValue.ToString();
        }
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
    }
    public void UpdateVerificationStatus(string Status, string RefID)
    {
        SqlParameter[] InsertWithPendingStatusParam = new SqlParameter[]
        {
            new SqlParameter("@RefId",RefID),
            new SqlParameter("@Status",Status)
        };

        int a = SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UpdateDMRVerificationTxn", InsertWithPendingStatusParam);

    }
    protected void gvBeni_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Remove")
        {
            string BeneID = Convert.ToString(e.CommandArgument);
            ViewState["BeneId"] = BeneID;
            string json = new JavaScriptSerializer().Serialize(new
            {
                goid = "5201078519",
                apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
                rtype = "json",
                apimode = "live",
                service_family = "25",
                agent_id = "Venus001",
                msisdn = Convert.ToString(Session["SenderId"]),
                type = "delete",
                beneficiary_id = BeneID
            });
            string Response = CommanPostFunction("https://api.goprocessing.in/dmt/moneyBeneficiary.go", json);
            if (Response != "")
            {
                JObject jsonResponse = JObject.Parse(Response);
                if (jsonResponse["status"].ToString() == "1")
                {
                    if (jsonResponse["otp_status"].ToString() == "1")
                    {
                        ViewState["trans_id"] = jsonResponse["trans_id"].ToString();
                        lblHeader.Text = "Confirm Delete Beneficiary";
                        btnDeleteConfirm.Visible = true;
                        btnAddConfirm.Visible = false;
                        mp1.Show();
                        //GetBeneList();
                    }
                    else
                    {
                        lblmsg.Visible = true;
                        lblmsg.Text = "Beneficiary has been deleted successfully.";
                    }
                }
                else
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = "Delete Beneficiary process failed. Please try after some time.";
                }
            }
        }
        if (e.CommandName.Contains("PAY"))
        {
            string pay_mode = e.CommandName.Split('_')[1].ToString();
            string BeneID = Convert.ToString(e.CommandArgument);
            ViewState["BeneId"] = BeneID;
            GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
            int RowIndex = row.RowIndex; // this find the index of row

            lblTxnBeneName.Text = ((Label)row.FindControl("lblBLName")).Text;
            lblTxnAccountNo.Text = ((Label)row.FindControl("lblBLAccount")).Text;
            lblTxnBankName.Text = ((Label)row.FindControl("lblBLBankName")).Text;
           // lblTxnBeneMobile.Text = ((Label)row.FindControl("lblBLMobile")).Text.Replace(".", "");
            hdfPayMode.Value = pay_mode;
            hdfIFSC.Value = ((HiddenField)row.FindControl("hdfBLIfsc")).Value;
            mp_Txn.Show();

        }
        if (e.CommandName == "Resend")
        {
            string BeneID = Convert.ToString(e.CommandArgument);
            ViewState["BeneId"] = BeneID;
            string json = new JavaScriptSerializer().Serialize(new
            {
                Key = "21b8d575871379e74ae336f3cb5a8561a5dfb5bf",
                AgentID = "2002",
                SenderId = Convert.ToString(Session["SenderId"]),
                BeneficiaryId = BeneID
            });
            string Response = CommanPostFunction("http://api.softsolutionzone.in/resources/SKIPDMR/ReSendOTPRegisterBene", json);
            if (Response != "")
            {
                JObject jsonResponse = JObject.Parse(Response);
                if (jsonResponse["statuscode"].ToString() == "TXN")
                {
                    lblHeader.Text = "Confirm Add Beneficiary";
                    btnDeleteConfirm.Visible = false;
                    btnAddConfirm.Visible = true;
                    mp1.Show();
                }
                else
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = "Resend Beneficiary Verify OTP process failed.Please try after some time. ";
                }
            }
        }
    }
    public string CommanPostFunction(string url, string Json)
    {
        string Result = "";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {

            streamWriter.Write(Json);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            Result = streamReader.ReadToEnd();
        }
        return Result;
    }
    protected void btnAddConfirm_Click(object sender, EventArgs e)
    {

        try
        {
            if (Convert.ToString(ViewState["flag"]) == "bene")
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    goid = "5201078519",
                    apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
                    rtype = "json",
                    apimode = "live",
                    service_family = "25",
                    agent_id = "Venus001",
                    msisdn = Convert.ToString(Session["SenderId"]),
                    trans_id = Convert.ToString(ViewState["AddBeneTxnID"]),
                    otp = txtOTP.Text.Trim()
                });
                string Response = CommanPostFunction("https://api.goprocessing.in/dmt/moneyBeneficiaryOTP.go", json);
                if (Response != "")
                {
                    JObject jsonResponse = JObject.Parse(Response);
                    if (jsonResponse["status"].ToString() == "1")
                    {
                        lblmsg.Visible = true;
                        lblmsg.Text = "Beneficiary has been added successfully.";
                        // btnsubmit_Click(new object(), new EventArgs());
                        GetBeneList();
                    }
                    else
                    {
                        lblmsg.Visible = true;
                        lblmsg.Text = jsonResponse["message"].ToString();
                    }
                }
                else
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = "Confirm Add Beneficiary process failed. Please try after some time.";
                }
            }
            else if(Convert.ToString(ViewState["flag"])== "customer")
            {
                
                string json = new JavaScriptSerializer().Serialize(new
                {
                    goid = "5201078519",
                    apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
                    rtype = "json",
                    apimode = "live",
                    service_family = "25",
                    agent_id = "Venus001",
                    msisdn = Convert.ToString(Session["SenderId"]),
                    trans_id = Convert.ToString(ViewState["trans_id"]),
                    otp = txtOTP.Text.Trim()
                });
                string Response = CommanPostFunction("https://api.goprocessing.in/dmt/moneyGetDetailsOTP.go", json);
                if (Response != "")
                {
                    JObject jsonResponse = JObject.Parse(Response);
                    if (jsonResponse["status"].ToString() == "1")
                    {
                        divSender.Visible = true;
                        txtSenderId.Text = Convert.ToString(Session["sendernumber"]);
                        Session["SenderId"] = jsonResponse["msisdn"].ToString();
                        lblsenderId.Text = jsonResponse["msisdn"].ToString();
                        ViewState["SenderName"] = lblsendername.Text = jsonResponse["user_name"].ToString();
                        if (jsonResponse["is_kyc"].ToString() == "0")
                            lblKYCStatus.Text = "Not Updated";
                        else
                            lblKYCStatus.Text = "Updated";
                        lblsenderLimit.Text = jsonResponse["remaining_limit"].ToString();

                        JArray objResponse = (JArray)jsonResponse["beneficiary"];
                        if (objResponse.Count > 0)
                        {

                            List<Beneficiary> OBene = objResponse.ToObject<List<Beneficiary>>();
                            if (OBene.Count > 0)
                            {
                                gvBeni.Visible = true;
                                gvBeni.DataSource = OBene;
                                gvBeni.DataBind();
                            }
                            else
                            {
                                gvBeni.DataSource = null;
                                gvBeni.DataBind();
                            }
                        }
                    }
                    else
                    {
                        lblmsg.Visible = true;
                        lblmsg.Text = jsonResponse["message"].ToString();
                    }
                }
                else
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = "Confirmation of Customer process failed. Please try after some time.";
                }
            }
            else if (Convert.ToString(ViewState["flag"]) == "account")
            {

                string json = new JavaScriptSerializer().Serialize(new
                {
                    goid = "5201078519",
                    apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
                    rtype = "json",
                    apimode = "live",
                    service_family = "25",
                    agent_id = "Venus001",
                    msisdn = Convert.ToString(Session["SenderId"]),
                    trans_id = Convert.ToString(ViewState["trans_id"]),
                    otp = txtOTP.Text.Trim()
                });
                string Response = CommanPostFunction("https://api.goprocessing.in/dmt/moneyVerificationOTP.go", json);
                if (Response != "")
                {
                    JObject jsonResponse = JObject.Parse(Response);
                    if (jsonResponse["status"].ToString() == "1")
                    {
                        //bank_trans_id
                        //trans_status
                        UpdateVerificationStatus("Success", jsonResponse["client_trans_id"].ToString());
                        //Add Beneficiary Process
                        //  AddBeneficiaryAfterVerify(BankAccount, IFSC, REQUEST_ID, BeneName, BeneMobile);
                        lblmsg.Visible = true;
                        lblmsg.Text = "Account Verification Process Successfully Done.";
                    }
                    else
                    {
                        lblmsg.Visible = true;
                        lblmsg.Text = jsonResponse["message"].ToString();
                    }
                }
                else
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = "Account Verification Process failed. Please try after some time.";
                }
            }
            else if (Convert.ToString(ViewState["flag"]) == "txn")
            {
                string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
                string json = new JavaScriptSerializer().Serialize(new
                {
                    goid = "5201078519",
                    apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
                    rtype = "json",
                    apimode = "live",
                    service_family = "25",
                    agent_id = "Venus001",
                    msisdn = Convert.ToString(Session["SenderId"]),
                    trans_id = Convert.ToString(ViewState["trans_id"]),
                    otp = txtOTP.Text.Trim()
                });
                string Response = CommanPostFunction("https://api.goprocessing.in/dmt/moneyTransferOTP.go", json);
                if (Response != "")
                {
                    JObject jsonResponse = JObject.Parse(Response);
                    if (jsonResponse["status"].ToString() == "1")
                    {
                        if (Convert.ToString(jsonResponse["trans_status"]) == "Success" || Convert.ToString(jsonResponse["trans_status"]) == "InProcess" || Convert.ToString(jsonResponse["trans_status"]) == "Scheduled")
                        {
                            UpdateTransaxtionStatus(Convert.ToString(jsonResponse["client_trans_id"]), "Success", Convert.ToString(Session["WhitelabelId"]), Convert.ToString(Session["LOGINID"]));
                            Agent_Card_Transaction_Insertin_ATT(Convert.ToString(Session["LOGINID"]), Convert.ToDecimal(jsonResponse["amount"]), Convert.ToDecimal(jsonResponse["customer_fee"]), Convert.ToDecimal(jsonResponse["commission"]), Convert.ToDecimal(jsonResponse["charged_amount"]), Convert.ToString(jsonResponse["client_trans_id"]), "", IPAddress, Convert.ToString(jsonResponse["beneficiary_name"]), "", "", Convert.ToString(ViewState["BeneId"]), Convert.ToString(jsonResponse["transfer_type"]), Convert.ToString(jsonResponse["bank_trans_id"]), lblTxnAccountNo.Text, Convert.ToString(Session["sendernumber"]), Convert.ToString(jsonResponse["msisdn"]), Convert.ToString(jsonResponse["trans_id"]));
                            lblmsg.Visible = true;
                            lblmsg.Text = jsonResponse["message"].ToString();
                        }
                        else if (Convert.ToString(jsonResponse["trans_status"]) == "Pending")
                        {
                        
                            lblmsg.Visible = true;
                            lblmsg.Text = jsonResponse["message"].ToString();
                        }
                    }
                    else
                    {
                        lblmsg.Visible = true;
                        lblmsg.Text = jsonResponse["message"].ToString();
                    }
                }
                else
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = "Account Verification Process failed. Please try after some time.";
                }
            }
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {

            ResetBene();
        }

    }
    public void AddBeneficiaryAfterVerify(string BankAccount, string ifsc, string txnid, string benename, string benemobile)
    {

        try
        {
            string json = new JavaScriptSerializer().Serialize(new
            {
                goid = "5201078519",
                apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
                rtype = "json",
                apimode = "live",
                service_family = "25",
                agent_id = "Venus001",
                msisdn = Convert.ToString(Session["SenderId"]),
                type="new",
                beneficiary_account_no = BankAccount,
                beneficiary_ifsc_code = ifsc

            });
            string Response = CommanPostFunction("https://api.goprocessing.in/dmt/moneyBeneficiary.go", json);
            if (Response != "")
            {
                JObject jsonResponse = JObject.Parse(Response);
                if (jsonResponse["status"].ToString() == "1")
                {
                    if (jsonResponse["otp_status"].ToString() == "1")
                    {
                        lblHeader.Text = "Confirm Add Beneficiary";
                        ViewState["flag"] = "bene";
                        ViewState["AddBeneTxnID"] = jsonResponse["trans_id"].ToString();
                        btnDeleteConfirm.Visible = false;
                        btnAddConfirm.Visible = true;
                        mp1.Show();
                    }
                    else
                    {
                        lblmsg.Visible = true;
                        lblmsg.Text = jsonResponse["remarks"].ToString();
                    }
                }
                else if (jsonResponse["status"].ToString() == "2")
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = jsonResponse["message"].ToString();
                }
                
            }
            else
            {
                lblmsg.Visible = true;
                lblmsg.Text = "Add New Beneficiary process failed. Please try after some time.";
            }
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {
            ResetBene();
        }

    }
    public void ResetBene()
    {
        ddlBank.SelectedValue = "0";
        txtBankAccount.Text = "";
        txtCBankAccount.Text = "";
        txtBeneName.Text = "";
        txtBeneMobile.Text = "";
        txtIFSC.Text = "";
        chkboxverify.Checked = false;
        lblTxnBeneMobile.Text = "";
        txtTxnRemark.Text = "";
        txtOTP.Text = "";
    }
    public decimal UserCutOffDetails()
    {
        decimal cutoffBalance = 0;
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",Convert.ToString(Session["LOGINID"]))
            };

            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getcutoffbalance", get_user_details);
            if (dr.Read())
            {
                cutoffBalance = Convert.ToInt32(dr["CuttOffAmount"]);
            }
            return cutoffBalance;
        }
        catch (Exception ex)
        {
            return cutoffBalance;
        }
    }
    protected void btnTxnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (Convert.ToDecimal(txtTxnReqAmount.Text.Trim()) > 0)
            {
                int S = 0, F = 0, P = 0;
                decimal ReqAmount = Convert.ToDecimal(txtTxnReqAmount.Text.Trim());
                decimal AgentBal = AgentBalance();
                decimal cutoffBalance = UserCutOffDetails();
                decimal[] fare = getfinalamount(ReqAmount, 0, 0);
                decimal RemainingBalance = ReqAmount;
                decimal LowerLimit = 5000;
                decimal FRqAmt = 0;
                if (AgentBal >= fare[0] + cutoffBalance)
                {
                    InsertLog(Convert.ToString(Session["LOGINID"]), ReqAmount.ToString() + "-" + lblTxnBeneMobile.Text, "Transaction");
                    string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
                    for (int i = 0; i < fare[2]; i++)
                    {
                        if (RemainingBalance >= LowerLimit)
                        {
                            // RemainingBalance = RemainingBalance - LowerLimit;
                            FRqAmt = LowerLimit;
                        }
                        else
                        {
                            FRqAmt = RemainingBalance;
                        }
                        string RefID = _objTransaction.Generate_TID();
                        if (Debit_Agent_Card_Amount_Insertin_ATT(Convert.ToString(Session["WhitelabelId"]), Convert.ToString(Session["LOGINID"]), FRqAmt, RefID, IPAddress, lblTxnBeneMobile.Text, lblTxnAccountNo.Text) > 1)
                        {
                            string Status = SentRequestForTransaction(Convert.ToString(Session["sendernumber"]), Convert.ToString(Session["SenderId"]), lblTxnAccountNo.Text, hdfIFSC.Value.ToString(), RefID, lblTxnBankName.Text, Convert.ToString(ViewState["BeneId"]), lblTxnBeneMobile.Text, Convert.ToString(ViewState["SenderName"]), lblTxnBeneName.Text, FRqAmt, txtTxnRemark.Text.Trim(), hdfPayMode.Value.ToString());
                            if (Status != "")
                            {
                                JObject jsonResponse = JObject.Parse(Status);
                                if (Convert.ToString(jsonResponse["status"]) == "1")
                                {
                                    if (Convert.ToString(jsonResponse["otp_status"]) == "1")
                                    {
                                        ViewState["trans_id"] = jsonResponse["trans_id"].ToString();
                                        lblHeader.Text = "Confirm Transaction";
                                        ViewState["flag"]="txn";
                                        btnDeleteConfirm.Visible = false;
                                        btnAddConfirm.Visible = true;
                                        mp1.Show();
                                    }
                                    else if (Convert.ToString(jsonResponse["otp_status"]) == "0")
                                    {
                                        if (Convert.ToString(jsonResponse["trans_status"]) == "Success" || Convert.ToString(jsonResponse["trans_status"]) == "InProcess" || Convert.ToString(jsonResponse["trans_status"]) == "Scheduled")
                                        {
                                            UpdateTransaxtionStatus(RefID, "Success", Convert.ToString(Session["WhitelabelId"]), Convert.ToString(Session["LOGINID"]));
                                            Agent_Card_Transaction_Insertin_ATT(Convert.ToString(Session["LOGINID"]), FRqAmt, fare[3], 0, (FRqAmt + fare[3]), RefID, "", IPAddress, Convert.ToString(jsonResponse["beneficiary_name"]), "", "", Convert.ToString(ViewState["BeneId"]), Convert.ToString(jsonResponse["transfer_type"]), Convert.ToString(jsonResponse["bank_trans_id"]), lblTxnAccountNo.Text, Convert.ToString(Session["sendernumber"]), Convert.ToString(jsonResponse["msisdn"]), Convert.ToString(jsonResponse["trans_id"]));
                                            lblmsg.Visible = true;
                                            lblmsg.Text = jsonResponse["message"].ToString();
                                        }
                                        else if (Convert.ToString(jsonResponse["trans_status"]) == "Pending")
                                        {
                                            P++;
                                            lblmsg.Visible = true;
                                            lblmsg.Text = jsonResponse["message"].ToString();
                                        }
                                    }
                                }
                                else if (Convert.ToString(jsonResponse["status"]) == "0" || Convert.ToString(jsonResponse["status"]) == "2")
                                {
                                    UpdateTransaxtionStatus(RefID, "Fail", Convert.ToString(Session["WhitelabelId"]), Convert.ToString(Session["LOGINID"]));
                                    lblmsg.Visible = true;
                                    lblmsg.Text = jsonResponse["message"].ToString();

                                }
                                else
                                {
                                   
                                    lblmsg.Visible = true;
                                    lblmsg.Text = jsonResponse["message"].ToString();
                                }
                        
                            }
                            else
                            {
                                F++;
                                lblmsg.Visible = true;
                                lblmsg.Text = "Transaction failed due to Low Network Connection.";
                            }
                        }
                        RemainingBalance = RemainingBalance - FRqAmt;
                    }
                    //string Msg = "";
                    //if (S > 0)
                    //{
                    //    Msg = "Total " + Convert.ToString(S) + " SUCCESS Transaction ";
                    //}
                    //if (F > 0)
                    //{
                    //    Msg += "Total " + Convert.ToString(F) + " FAILED Transaction ";
                    //}
                    //if (P > 0)
                    //{
                    //    Msg += "Total " + Convert.ToString(P) + " PENDING Transaction ";
                    //}
                    //lblmsg.Visible = true;
                    //lblmsg.Text = Msg + " Out of " + Convert.ToString(fare[2]) + " Transaction.";
                }
                else
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = "Insufficient Balance.";
                }
            }
            else
            {

            }
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {

            ResetBene();
        }
    }
    public string SentRequestForTransaction(string SenderMobile, string SenderId, string AccountNo, string IFSCCode, string RefId, string BankName, string BeneId, string BeneMobile, string SenderName, string BeneName, decimal Amount, string Remark, string PayMode)
    {
        string json = new JavaScriptSerializer().Serialize(new
        {
            goid = "5201078519",
            apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
            rtype = "json",
            apimode = "live",
            service_family = "25",
            agent_id = "Venus001",
            msisdn = Convert.ToString(Session["SenderId"]),
            client_trans_id = RefId,
            transfer_type = "ANY",
            amount = Amount,
            beneficiary_account_no = AccountNo,
            beneficiary_ifsc_code = IFSCCode
        });
        string Response = CommanPostFunction("https://api.goprocessing.in/dmt/moneyTransfer.go", json);
        InsertLog(RefId, Response, "GoProcessingTxn");
        return Response;
    }
    public int Debit_Agent_Card_Amount_Insertin_ATT(string whitelableid, string loginid, decimal requestamt, string txnid, string Ipaddress, string mobile, string AccountNo)
    {

        SqlParameter[] InsertWithPendingStatusParam = new SqlParameter[]
        {
            new SqlParameter("@WLID",Convert.ToInt64(whitelableid)),
            new SqlParameter("@IPAddress",Ipaddress),
            new SqlParameter("@ReferenceNumber",txnid),
            new SqlParameter("@AgentID",Convert.ToInt64(loginid)),
            new SqlParameter("@Type","DMR"),
            new SqlParameter("@Operater","Money Transfer"),
            new SqlParameter("@operatorID",58),
            new SqlParameter("@Circle","All"),
            new SqlParameter("@Mobileno",Convert.ToInt64(mobile)),
            new SqlParameter("@Amount",Convert.ToDecimal(requestamt)),
            new SqlParameter("@cptransactionid",""),
            new SqlParameter("@ServiceVendor","SoftZone"),
            new SqlParameter("@PortalName",""),
            new SqlParameter("@SERVICE_NAME","DMR Payment"),
            new SqlParameter("@AccountNo",Convert.ToString(AccountNo)),
            new SqlParameter("@ErrorMessage",SqlDbType.Int)
        };
        InsertWithPendingStatusParam[15].Direction = ParameterDirection.Output;
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "Insert_DMR_CardPayment__Status_SoftDMR", InsertWithPendingStatusParam);
        int result = Convert.ToInt32(InsertWithPendingStatusParam[15].Value);
        return result;
    }
    //public void Credit_Agent_Card_Amount_Insertin_ATT_After_Failure(string whitelableid, string loginid, string txnid)
    //{

    //    SqlParameter[] InsertWithPendingStatusParam = new SqlParameter[]
    //    {
    //        new SqlParameter("@WLID",Convert.ToInt64(whitelableid)),
    //        new SqlParameter("@refrenceno",txnid),
    //        new SqlParameter("@AgentID",Convert.ToInt64(loginid))

    //    };
    //    SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_updatestatus_fail_DMR_New", InsertWithPendingStatusParam);

    //}
    public int Agent_Card_Transaction_Insertin_ATT(string agentid, decimal requestamt, decimal service, decimal agentcommission, decimal deducamt, string txnid, string Ifsc, string Ip, string Bname, string Bmobile, string BId, string remark, string mode, string mode_desc, string BeneAccount, string SenderName, string senderId, string ApiTxnId)
    {


        SqlParameter[] p = new SqlParameter[]
       {
           new SqlParameter("@AgentID",agentid),
           new SqlParameter("@Card_No ",ApiTxnId),
            new SqlParameter("@TransactionNo",txnid),
            new SqlParameter("@RequestAmount",requestamt),
            new SqlParameter("@Commission",agentcommission),
             new SqlParameter("@Service_Charge",service),
             new SqlParameter("@DeductedAmount",deducamt),
              new SqlParameter("@Status","Success"), 
           new SqlParameter("@Request_IP",Ip),
           new SqlParameter("@Benificiary_Name",Bname),  
           new SqlParameter("@Benificiary_Mobile",Bmobile),
           new SqlParameter("@IFSC",Ifsc),
           new SqlParameter("@Benificiary_ID",BId),
            new SqlParameter("@Transaction_Remark",remark),
            new SqlParameter("@Transaction_Mode",mode),
            new SqlParameter("@Mode_Description",mode_desc),
            new SqlParameter("@BeneAccount",BeneAccount),
            new SqlParameter("@SenderName",SenderName),
            new SqlParameter("@SenderId",senderId)

       };
        return SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "sp_agent_card_transaction_SoftDMR", p);

    }

    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_SoftDMR", warlock);
        }
        catch (Exception ex)
        {
        }
    }
    protected decimal[] getfinalamount(decimal amount, decimal service, decimal agentcom)
    {
        decimal[] fare = new decimal[4];
        decimal a = amount / 5000;
        decimal b = (decimal)Math.Ceiling(a);


        // fare[0] = amount + Convert.ToDecimal(b) * 11;
        //fare[0] = amount + (amount * Convert.ToDecimal(0.60)) / 100;
        fare[0] = GetDMTCharge(Convert.ToString(Session["WhitelabelId"]), amount);
        fare[1] = Convert.ToDecimal(b) * 11;
        fare[2] = b;
        fare[3] = 11;
        return fare;
    }

    public decimal GetDMTCharge(string WLID, decimal Amount)
    {
        try
        {
            SqlParameter[] warlock = new SqlParameter[]
            {
                new SqlParameter("@WLID",WLID),
                new SqlParameter("@Amount",Amount),
                new SqlParameter("@TotalCharge",SqlDbType.Decimal)
            };
            warlock[2].Direction = ParameterDirection.Output;
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_calculateDMTCharge", warlock);
            return Convert.ToDecimal(warlock[2].Value);
        }
        catch (Exception ex)
        {
            return Amount;
        }
    }
    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 gvBeni_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HiddenField hdfVStatus = (HiddenField)e.Row.FindControl("hdfVStatus");
            LinkButton lnkbtnStatus = (LinkButton)e.Row.FindControl("lnkbtnStatus");
            LinkButton lnkbtnImps = (LinkButton)e.Row.FindControl("lnkbtnImps");
            LinkButton lnkbtnNEFT = (LinkButton)e.Row.FindControl("lnkbtnNEFT");
            if (hdfVStatus.Value.ToString() == "0")
            {
                //lnkbtnStatus.Text = "Non Verify";
                //lnkbtnStatus.Enabled = true;
                //lnkbtnNEFT.Enabled = false;
                //lnkbtnImps.Enabled = false;
                lnkbtnStatus.Text = "Verified";
                lnkbtnStatus.Enabled = false;
            }
            else
            {
                lnkbtnStatus.Text = "Verified";
                lnkbtnStatus.Enabled = false;
            }

        }
    }

    public void GetBeneList()
    {
        string json = new JavaScriptSerializer().Serialize(new
        {
            goid = "5201078519",
            apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
            rtype = "json",
            apimode = "live",
            service_family = "25",
            agent_id = "Venus001",
            msisdn = Convert.ToString(Session["SenderId"])
                                    
        });
        string Response = CommanPostFunction("https://api.goprocessing.in/dmt/moneyGetDetails.go", json);
        if (Response != "")
        {
            JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
            JObject jsonResponse = JObject.Parse(Response);
            if (jsonResponse["status"].ToString() == "1")
            {

                JArray objResponse = (JArray)jsonResponse["beneficiary"];
                    if (objResponse.Count > 0)
                    {

                        List<Beneficiary> OBene = objResponse.ToObject<List<Beneficiary>>();
                        if (OBene.Count > 0)
                        {
                            gvBeni.Visible = true;
                            gvBeni.DataSource = OBene;
                            gvBeni.DataBind();
                        }
                        else
                        {
                            gvBeni.DataSource = null;
                            gvBeni.DataBind();
                        }
                    }

               
            }
        }
    }
    protected void btnDeleteConfirm_Click(object sender, EventArgs e)
    {
        try
        {
            string json = new JavaScriptSerializer().Serialize(new
            {
                goid = "5201078519",
                apikey = "5r4BH2HEsDaHcRw",//"CI4QN7ALHFL6SWM",
                rtype = "json",
                apimode = "live",
                service_family = "25",
                agent_id = "Venus001",
                msisdn = Convert.ToString(Session["SenderId"]),
                trans_id=Convert.ToString(ViewState["trans_id"]),
                otp=txtOTP.Text.Trim()
               
            });
            string Response = CommanPostFunction("https://api.goprocessing.in/dmt/moneyBeneficiaryOTP.go", json);
            if (Response != "")
            {
                JObject jsonResponse = JObject.Parse(Response);
                if (jsonResponse["status"].ToString() == "1")
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = "Deletion of Beneficiary have been done.";
                    // btnsubmit_Click(new object(), new EventArgs());
                    GetBeneList();
                }
                else
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = jsonResponse["message"].ToString();
                }
            }
            else
            {
                lblmsg.Visible = true;
                lblmsg.Text = "Confirm delete Beneficiary process failed. Please try after some time.";
            }
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {

            ResetBene();
        }
    }
}