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;

public partial class Agent_MoneyTransferNew : System.Web.UI.Page
{
    AirEpointSupport _objTransaction = new AirEpointSupport();
    public static string Token = "9f180b1b2a49d42aed015564fca83ef8";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Convert.ToString(Session["LOGINID"])) && string.IsNullOrEmpty(Convert.ToString(Session["USERNAME"])))
        {
            Response.Redirect("../login.aspx");
        }
        else
        {
            if (!IsPostBack)
            {
                BindBank();

            }
        }
        // mp1.Show();
    }
    public class Beneficiary
    {
        public string BeneficiaryCode { get; set; }
        public string BeneficiaryName { get; set; }
        public string AccountNumber { get; set; }
        public string Bankname { get; set; }
        public string IFSC { get; set; }

    }
    public bool isExistsSenderDetails()
    {
        bool result = false;
        string RefID = _objTransaction.Generate_TID();
        string url = "https://www.apibox.xyz/api/Fetch/WalletDetail?token=" + Token + "&skey=DMP&reqid=" + RefID + "&p1=walexist&p2=" + Convert.ToString(Session["sendernumber"]) + "&format=json";
        string Response = GetResponseUsingGetMethod(url);
        InsertLog(RefID, Response,"IsExists");
        JObject joResponse = JObject.Parse(Response);
        JObject Response_JObj = (JObject)joResponse["response"];
        JValue ResponseCode = (JValue)Response_JObj["status_code"];
        JValue Description = (JValue)Response_JObj["desc"];
        JValue WalletExist = (JValue)Response_JObj["WalletExist"];
        if (Convert.ToString(ResponseCode) == "RCS")
        {
            if (Convert.ToString(WalletExist) == "Y")
                result = true;
            else
                result = false;
        }
        return result;
    }
    public string GetResponseUsingGetMethod(string URL)
    {
        try
        {
           // objBal.vendorinputoutputResponce(apiId, reqid, ServiceType, "Request", URL, "APIBOX");
            WebRequest request = HttpWebRequest.Create(URL);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream s = (Stream)response.GetResponseStream();
            StreamReader readStream = new StreamReader(s);
            string dataString = readStream.ReadToEnd();
            response.Close();
            s.Close();
            readStream.Close();
            //objBal.vendorinputoutputResponce(apiId, reqid, ServiceType, "Response", dataString, "APIBOX");
            return dataString;
        }
        catch
        {
            return "";
        }
    }
    public void FetchBeneficiary(string reqid, string mobile, string apiId)
    {

        string URl = "https://www.apibox.xyz/api/Fetch/WalletDetail?token=" + Token + "&skey=DMP&reqid=" + reqid + "&p1=benef&p2=" + mobile + "&format=json";
        string Response = GetResponseUsingGetMethod(URl);
        InsertLog(reqid, Response,"Fetch");
        JObject joResponse = JObject.Parse(Response);
        JObject Response_JObj = (JObject)joResponse["response"];
        JValue ResponseCode = (JValue)Response_JObj["status_code"];
        JValue Description = (JValue)Response_JObj["desc"];
        JValue RefID = (JValue)Response_JObj["reqid"];
        JArray Beneficiary = (JArray)Response_JObj["Beneficiary"];
        if (Convert.ToString(ResponseCode)=="RCS")
        {
            List<Beneficiary> OBene = Beneficiary.ToObject<List<Beneficiary>>();
            divSender.Visible = true;
            txtSenderId.Text = Convert.ToString(Session["sendernumber"]);
            Session["SenderId"] = Convert.ToString(Session["sendernumber"]);
            lblsenderId.Text = Convert.ToString(Session["sendernumber"]);
            ViewState["SenderName"] =  "";
            //lblKYCStatus.Text = "";
            //lblsenderLimit.Text = "";
            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.";
        }
       
    }
    protected void btnsubmit_Click(object sender, EventArgs e)
    {
        try
        {
            string sendernumber = txtMobileNo.Text.Trim();
            Session["sendernumber"] = sendernumber;
            if (IsInteger(sendernumber))
            {
                if (isExistsSenderDetails())
                {
                    //Fetch Benificiary
                    FetchBeneficiary(_objTransaction.Generate_TID(), sendernumber,"");
                }
                else
                {
                    divSender.Visible = false;
                    gvBeni.Visible = false;
                    lblmsg.Text = "";
                    string message = "Sender not found. Retry with different sender id Or Register Sender";
                    string url = "SenderRegistrationNew.aspx";
                    string script = "window.onload = function(){ alert('";
                    script += message;
                    script += "');";
                    script += "window.location = '";
                    script += url;
                    script += "'; }";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", script, true);
                }
                
            }
            else
            {
                lblmsg.Text = "Invalid Customer Mobile Number.";
            }
        }
        catch (Exception ex)
        {
        }
        finally
        {
            ResetBene();
        }
    }  
    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()
    {
        try
        {
            DataSet ds_banklist = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.Text, "select * from DMTBankList");
            if (ds_banklist.Tables[0].Rows.Count > 0)
            {
                ddlBank.DataSource = ds_banklist.Tables[0];
                ddlBank.DataTextField = "BankName";
                ddlBank.DataValueField = "Code";
                ddlBank.DataBind();
                ddlBank.Items.Insert(0, new ListItem("--Select Bank--", "0"));
                ddlBank.SelectedIndex = 0;
            }
        }
        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;
    }
    public void AddBeneficiary(string reqid, string mobile, string apiId, string BeneName, string BeneAccountNo, string IFSC)
    {
        
        string URl = "https://www.apibox.xyz/api/ManageUser/Benef?token=" + Token + "&skey=DMP&reqid=" + reqid + "&p1=addbenef&p2="+ Convert.ToString(Session["sendernumber"]) + "&p3=" + BeneName + "&p4=" + BeneAccountNo + "&p5=" + IFSC + "&format=json";
        string Response = GetResponseUsingGetMethod(URl);
        InsertLog(reqid, Response,"AddBene");
        if (Response != "")
        {
            JObject joResponse1 = JObject.Parse(Response);
            JObject jsonResponse = (JObject)joResponse1["response"];
            if (jsonResponse["status_code"].ToString() == "RCS")
            {
                lblmsg.Visible = true;
                lblmsg.Text = "Add Beneficiary have been done.";
                FetchBeneficiary(_objTransaction.Generate_TID(), Convert.ToString(Session["sendernumber"]),"");  
            }
            else
            {
                lblmsg.Visible = true;
                lblmsg.Text = jsonResponse["desc"].ToString();
            }
        }
        else
        {
            lblmsg.Visible = true;
            lblmsg.Text = "Add New Beneficiary process failed. Please try after some time.";
        }
    }
    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
                {
                    AddBeneficiary(_objTransaction.Generate_TID(), txtBeneMobile.Text.Trim(), Convert.ToString(Session["LOGINID"]), txtBeneName.Text.Trim(), txtBankAccount.Text.Trim(), txtIFSC.Text.Trim());
                    //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("http://api.softsolutionzone.in/resources/SKIPDMR/AccountVerifyByBankAccountIFSC");
        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 = SenderMobile,
                SenderId = SenderId,
                BankAccount = BankAccount,
                BankCode = "222",
                IFSC = IFSC,
                REQUEST_ID = REQUEST_ID,
                BankName = Bank
            });
            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["statuscode"].ToString() == "TXN")
            {

                UpdateVerificationStatus("Success", REQUEST_ID);
                //Add Beneficiary Process
               // AddBeneficiaryAfterVerify(BankAccount, IFSC, REQUEST_ID, BeneName, BeneMobile);

            }
            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 reqid = _objTransaction.Generate_TID();
            string URl = "https://www.apibox.xyz/api/ManageUser/Benef?token=" + Token + "&skey=DMP&reqid=" + reqid + "&p1=delbenef&p2=" + Convert.ToString(Session["sendernumber"]) + "&p3=" + BeneID + "&format=json";
            string Response = GetResponseUsingGetMethod(URl);
            if (Response != "")
            {
                JObject joResponse1 = JObject.Parse(Response);
                JObject jsonResponse = (JObject)joResponse1["response"];
                if (jsonResponse["status_code"].ToString() == "RCS")
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = "Request Completed Successfully, Beneficiary Deleted Successfully";
                    FetchBeneficiary(_objTransaction.Generate_TID(), Convert.ToString(Session["sendernumber"]), "");
                }
                else
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = jsonResponse["desc"].ToString();
                }
            }
            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;
            hdfPayMode.Value = pay_mode;
            hdfIFSC.Value = ((HiddenField)row.FindControl("hdfBLIfsc")).Value;
            mp_Txn.Show();

        }
    }
    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
        {
            string json = new JavaScriptSerializer().Serialize(new
            {
                Key = "7ef37a4185480cebda9430277939c47ce93b4183",
                AgentID = "3890",
                SenderId = Convert.ToString(Session["SenderId"]),
                BeneficiaryId = Convert.ToString(ViewState["BeneId"]),
                OTP = txtOTP.Text.Trim()
            });
            string Response = CommanPostFunction("http://api.softsolutionzone.in/resources/SKIPDMR/VerifyBene", json);
            if (Response != "")
            {
                JObject jsonResponse = JObject.Parse(Response);
                if (jsonResponse["statuscode"].ToString() == "TXN")
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = "Verification of Add Beneficiary have been done.";
                    // btnsubmit_Click(new object(), new EventArgs());
                    GetBeneList();
                }
                else
                {
                    lblmsg.Visible = true;
                    lblmsg.Text = jsonResponse["status"].ToString();
                }
            }
            else
            {
                lblmsg.Visible = true;
                lblmsg.Text = "Confirm Add 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 = "";
    }
    protected void btnTxnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (Convert.ToDecimal(txtTxnReqAmount.Text.Trim()) > 0)
            {
                decimal ReqAmount = Convert.ToDecimal(txtTxnReqAmount.Text.Trim());
                decimal AgentBal = AgentBalance();
                decimal[] fare = getfinalamount(ReqAmount, 0, 0);
                decimal RemainingBalance = ReqAmount;
                decimal LowerLimit = 5000;
                decimal FRqAmt = 0;
                if (AgentBal >= fare[0])
                {
                    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 joResponse1 = JObject.Parse(Status);
                                JObject jsonResponse = (JObject)joResponse1["response"];
                                    if (jsonResponse["status_code"].ToString() == "TXN")
                                    {
                                        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, hdfIFSC.Value.ToString(), IPAddress, lblTxnBeneName.Text, "0", "0", Convert.ToString(ViewState["BeneId"]), Convert.ToString(jsonResponse["TransferType"]), Convert.ToString(jsonResponse["UTR"]), Convert.ToString(lblTxnAccountNo.Text), Convert.ToString(""), Convert.ToString(jsonResponse["Wallet"]), Convert.ToString(jsonResponse["OrderId"]));
                                        lblmsg.Visible = true;
                                        lblmsg.Text = jsonResponse["desc"].ToString();
                                    }
                                    else if (jsonResponse["status_code"].ToString() == "TUP" || jsonResponse["status_code"].ToString() == "SAC" || jsonResponse["status_code"].ToString() == "RCS")
                                    {
                                        lblmsg.Visible = true;
                                        lblmsg.Text = jsonResponse["desc"].ToString();
                                    }
                                    else
                                    {
                                        UpdateTransaxtionStatus(RefID, "Fail", Convert.ToString(Session["WhitelabelId"]), Convert.ToString(Session["LOGINID"]));
                                        lblmsg.Visible = true;
                                        lblmsg.Text = jsonResponse["desc"].ToString();
                                    }
                            }
                            else
                            {
                                lblmsg.Visible = true;
                                lblmsg.Text = "Transaction failed due to Low Network Connection.";
                            }
                        }
                        RemainingBalance = RemainingBalance - FRqAmt;
                    }
                }
                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 URl = "https://www.apibox.xyz/api/Action/transact?token=" + Token + "&skey=DMP&reqid=" + RefId + "&p1=new&p2=" + Convert.ToString(Session["sendernumber"]) + "&p3=" + BeneId + "&p4=" + Amount + "&p5=IMPS&p6=11137&format=json";
        string Response = GetResponseUsingGetMethod(URl);
        InsertLog(RefId, Response, "IniciateTxn");
        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","APIBOX"),
            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 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[1] = Convert.ToDecimal(b) * 11;
        fare[2] = b;
        fare[3] = 11;
        return fare;
    }
    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;
            }
            else
            {
                lnkbtnStatus.Text = "Verified";
                lnkbtnStatus.Enabled = false;
            }

        }
    }
    public void GetBeneList()
    {
        string json = new JavaScriptSerializer().Serialize(new
        {
            Key = "7ef37a4185480cebda9430277939c47ce93b4183",
            AgentID = "3890",
            SenderMobile = txtMobileNo.Text.Trim()
        });
        string Response = CommanPostFunction("http://api.softsolutionzone.in/resources/SKIPDMR/FindSender", json);
        if (Response != "")
        {
            JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
            JObject jsonResponse = JObject.Parse(Response);
            if (jsonResponse["statuscode"].ToString() == "TXN")
            {
                JObject objResponse = (JObject)jsonResponse["data"];
                if (objResponse.Count > 0)
                {
                    JArray objBane = (JArray)objResponse["beneficiary"];
                    List<DMR.Beneficiary> OBene = objBane.ToObject<List<DMR.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
            {
                Key = "7ef37a4185480cebda9430277939c47ce93b4183",
                AgentID = "3890",
                SenderId = Convert.ToString(Session["SenderId"]),
                BeneficiaryId = Convert.ToString(ViewState["BeneId"]),
                Otp = txtOTP.Text.Trim()
            });
            string Response = CommanPostFunction("http://api.softsolutionzone.in/resources/SKIPDMR/ConfirmDeleteBene", json);
            if (Response != "")
            {
                JObject jsonResponse = JObject.Parse(Response);
                if (jsonResponse["statuscode"].ToString() == "TXN")
                {
                    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["status"].ToString();
                }
            }
            else
            {
                lblmsg.Visible = true;
                lblmsg.Text = "Confirm delete Beneficiary process failed. Please try after some time.";
            }
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {

            ResetBene();
        }
    }
}