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 MoneyTransfer : 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 sendernumber = txtMobileNo.Text.Trim();
            Session["sendernumber"] = sendernumber;
            if (IsInteger(sendernumber))
            {
                string Response = PostRequest("http://api.softsolutionzone.in/resources/SKIPDMR/FindSender", sendernumber);
                if (Response != "")
                {
                    JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
                    // DMR OEmployeeInfo = JsonSerializer.Deserialize<DMR>(Response);
                    JObject jsonResponse = JObject.Parse(Response);
                    if (jsonResponse["statuscode"].ToString() == "TXN")
                    {
                        JObject objResponse = (JObject)jsonResponse["data"];
                        if (objResponse.Count > 0)
                        {
                            divSender.Visible = true;
                            
                            JObject objRemitter = (JObject)objResponse["remitter"];
                            DMR.Remitter ORemitter = JsonSerializer.Deserialize<DMR.Remitter>(objRemitter.ToString());
                            Session["SenderId"] = ORemitter.id;
                            if (ORemitter.is_verified == "1")
                            {
                                JArray objBane = (JArray)objResponse["beneficiary"];
                                List<DMR.Beneficiary> OBene = objBane.ToObject<List<DMR.Beneficiary>>();
                                txtSenderId.Text = Convert.ToString(Session["sendernumber"]);
                                //Session["SenderId"] = ORemitter.id;
                                lblsenderId.Text = ORemitter.mobile;
                                ViewState["SenderName"] = lblsendername.Text = ORemitter.name;
                                lblKYCStatus.Text = ORemitter.kycstatus;
                                lblsenderLimit.Text = ORemitter.remaininglimit;
                                if (OBene.Count > 0)
                                {
                                    gvBeni.Visible = true;
                                    gvBeni.DataSource = OBene;
                                    gvBeni.DataBind();
                                }
                                else
                                {
                                    gvBeni.DataSource = null;
                                    gvBeni.DataBind();
                                }
                            }
                            else if (ORemitter.is_verified == "0")
                            {
                                mpOTP.Show();
                            }
                        }
                    }
                    else if (jsonResponse["statuscode"].ToString() == "RNF")
                    {
                        divSender.Visible = false;
                        gvBeni.Visible = false;
                        lblmsg.Text = "";

                        //   Response.write("<script language='javascript'>window.alert('Sender not found. Retry with different sender id Or Register Sender');window.location='SenderRegistration.aspx';</script>");

                        string message = "Sender not found. Retry with different sender id Or Register Sender";
                        string url = "SenderRegistration.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 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
        {
// http://api.softsolutionzone.in/resources/SKIPDMR/FindSender 
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.softsolutionzone.in/resources/SKIPDMR/GetBankDetailsByAccount");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    Key = "7ef37a4185480cebda9430277939c47ce93b4183",
                    AgentID = "3890",
                    AccountNo = ""
                });
                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["statuscode"].ToString() == "TXN")
                {
                    JArray objResponse = (JArray)jsonResponse["data"];
                    if (objResponse.Count > 0)
                    {
                        List<Bank> _objBank = objResponse.ToObject<List<Bank>>();
                        foreach (Bank p in _objBank)
                        {
                            ListItem item = new ListItem(p.bank_name, p.branch_ifsc);
                            ddlBank.Items.Add(item);
                        }
                     
                        ddlBank.Items.Insert(0, new ListItem("Select Bank", "0"));
                    }
                }
                else if (jsonResponse["statuscode"].ToString() == "RNF")
                {
                    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("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 json = new JavaScriptSerializer().Serialize(new
            {
                Key = "7ef37a4185480cebda9430277939c47ce93b4183",
                AgentID = "3890",
                SenderId = Convert.ToString(Session["SenderId"]),
                BeneficiaryId = BeneID
            });
            string Response = CommanPostFunction("http://api.softsolutionzone.in/resources/SKIPDMR/DeleteBene", json);
            if (Response != "")
            {
                JObject jsonResponse = JObject.Parse(Response);
                if (jsonResponse["statuscode"].ToString() == "TXN")
                {
                    //Confirm Add Beneficiary
                  //  mp1.Show(); 
                    //btnsubmit_Click(new object(), new EventArgs());
                    lblHeader.Text = "Confirm Delete Beneficiary";
                    btnDeleteConfirm.Visible = true;
                    btnAddConfirm.Visible = false;
                    mp1.Show();
                    //GetBeneList();
                }
                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
        {
            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 AddBeneficiaryAfterVerify(string BankAccount,string ifsc,string txnid,string benename,string benemobile)
    {

        try
        {
            string json = new JavaScriptSerializer().Serialize(new
            {
                Key = "7ef37a4185480cebda9430277939c47ce93b4183",
                AgentID = "3890",
                SenderId = Convert.ToString(Session["SenderId"]),
                BankAccount = BankAccount,
                IFSC = ifsc,
                REQUEST_ID = txnid,
                BeneName = benename,
                BeneMobile = benemobile

            });
            string Response = CommanPostFunction("http://api.softsolutionzone.in/resources/SKIPDMR/AddBeneAfterVerify", 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 = jsonResponse["status"].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)
            {
                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["statuscode"]) == "TXN")
                                {
                                    //update success status and credit amount to distributor

                                    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, Convert.ToString(jsonResponse["ifsc"]), IPAddress, Convert.ToString(jsonResponse["BeneName"]), Convert.ToString(jsonResponse["BeneMobile"]), Convert.ToString(jsonResponse["BeneMobile"]), "BeneID", hdfPayMode.Value.ToString(), Convert.ToString(jsonResponse["BankRRN"]), Convert.ToString(jsonResponse["BeneAccount"]), Convert.ToString(jsonResponse["SenderName"]), Convert.ToString(jsonResponse["SenderId"]), Convert.ToString(jsonResponse["apiTid"]));
                                    lblmsg.Visible = true;
                                    lblmsg.Text = jsonResponse["status"].ToString();
                                }
                                else if (Convert.ToString(jsonResponse["statuscode"]) == "TUP" || Convert.ToString(jsonResponse["statuscode"]) == "SPE")
                                {
                                    lblmsg.Visible = true;
                                    lblmsg.Text = jsonResponse["status"].ToString();
                                }
                              else if (Convert.ToString(jsonResponse["statuscode"]) == "ITI" || Convert.ToString(jsonResponse["statuscode"]) == "IAB" || Convert.ToString(jsonResponse["statuscode"]) == "DID"
                                    || Convert.ToString(jsonResponse["statuscode"]) == "SPD" || Convert.ToString(jsonResponse["statuscode"]) == "TRP" || Convert.ToString(jsonResponse["statuscode"]) == "SNA"
                                    || Convert.ToString(jsonResponse["statuscode"]) == "FAB" || Convert.ToString(jsonResponse["statuscode"]) == "IAN" || Convert.ToString(jsonResponse["statuscode"]) == "DTX"
                                    || Convert.ToString(jsonResponse["statuscode"]) == "ERR")
                                {
                                    UpdateTransaxtionStatus(RefID, "Fail", Convert.ToString(Session["WhitelabelId"]), Convert.ToString(Session["LOGINID"]));
                                    lblmsg.Visible = true;
                                    lblmsg.Text = jsonResponse["status"].ToString();
                                }
                                else
                                {
                                    lblmsg.Visible = true;
                                    lblmsg.Text = "Transaction is successfully processed but the final response is awaited";
                                }
                            }
                            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 json = new JavaScriptSerializer().Serialize(new
        {
            Key = "7ef37a4185480cebda9430277939c47ce93b4183",
            AgentID = "3890",
            SenderMobile = SenderMobile,
            SenderId = SenderId,
            BankAccount = AccountNo,
            BankCode = "222",
            IFSC = IFSCCode,
            REQUEST_ID = RefId,
            BankName = BankName,
            RecipientId=BeneId,
            BeneMobile=BeneMobile,
            SenderName=SenderName,
            BeneName=BeneName,
            TxnAmount=Amount,
            Remark=Remark,
            TxnType=PayMode
        });
        string Response = CommanPostFunction("http://api.softsolutionzone.in/resources/SKIPDMR/InitiateTransaction", json);
        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","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;
            }
            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();
        }
    }
    protected void btnOTPSenderVerification_Click(object sender, EventArgs e)
    {
        string json = new JavaScriptSerializer().Serialize(new
        {
            Key = "7ef37a4185480cebda9430277939c47ce93b4183",
            AgentID = "3890",
            SenderMobile = Convert.ToString(Session["sendernumber"]),
            SenderId = Convert.ToString(Session["SenderId"]),
            OTP = txtSenderOTP.Text.Trim()
        });
        string Response = CommanPostFunction("http://api.softsolutionzone.in/resources/SKIPDMR/VerifySender", 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)
                {
                    divSender.Visible = true;

                    JObject objRemitter = (JObject)objResponse["remitter"];
                    DMR.Remitter ORemitter = JsonSerializer.Deserialize<DMR.Remitter>(objRemitter.ToString());
                    Session["SenderId"] = ORemitter.id;
                    if (ORemitter.is_verified == "1")
                    {
                        JArray objBane = (JArray)objResponse["beneficiary"];
                        List<DMR.Beneficiary> OBene = objBane.ToObject<List<DMR.Beneficiary>>();
                        txtSenderId.Text = Convert.ToString(Session["sendernumber"]);
                        //Session["SenderId"] = ORemitter.id;
                        lblsenderId.Text = ORemitter.mobile;
                        ViewState["SenderName"] = lblsendername.Text = ORemitter.name;
                        lblKYCStatus.Text = ORemitter.kycstatus;
                        lblsenderLimit.Text = ORemitter.remaininglimit;
                        if (OBene.Count > 0)
                        {
                            gvBeni.Visible = true;
                            gvBeni.DataSource = OBene;
                            gvBeni.DataBind();
                        }
                        else
                        {
                            gvBeni.DataSource = null;
                            gvBeni.DataBind();
                        }
                    }
                    else if (ORemitter.is_verified == "0")
                    {
                        mpOTP.Show();
                    }
                }
            }
            else if (jsonResponse["statuscode"].ToString() == "RNF")
            {
                divSender.Visible = false;
                gvBeni.Visible = false;
                lblmsg.Text = "";

                //   Response.write("<script language='javascript'>window.alert('Sender not found. Retry with different sender id Or Register Sender');window.location='SenderRegistration.aspx';</script>");

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

    }
}
