using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
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 System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Collections.Specialized;


public partial class Admin_PendingTransactionVB : System.Web.UI.Page
{
    CommonFunction objcommonfun = new CommonFunction();
    string BalanceAfterTransaction, LoginID, sms, MobileNo, ReqAmount, AG_MobilNo, ServiceType;
    string vendor, OperatorId;
    string ErrorMessage = string.Empty;
    com.ezypayindia.ws.network RechargeEzpayObj = new com.ezypayindia.ws.network();
    WBMobile_Noverification _ObjWBMNverify = new WBMobile_Noverification();
    DataSet ds = new DataSet();

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["AdminEMAILID"] == null)
            {
                Response.Redirect("AdminLogin.aspx");
            }
            if (!IsPostBack)
            {
                fill.Visible = false;
            }
            btnRefund.Visible = false;
            btnsucess.Visible = false;
        }
        catch (Exception ex)
        {
            throw (ex);
        }  
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (ddlVendor.SelectedItem.Text.Equals("eGenApi"))
            {
                ViewState["vendor"] = "eGenApi";
            }
            if (ddlVendor.SelectedItem.Text.Equals("ExcelRecharge"))
            {
                ViewState["vendor"] = "ExcelRecharge";
            }
            if (ddlVendor.SelectedItem.Text.Equals("IWTApi"))
            {
                ViewState["vendor"] = "IWTApi";
            }
            else if (ddlVendor.SelectedItem.Text.Equals("ApiWorld"))
            {
                ViewState["vendor"] = "ApiWorld";
            }
            getdetails();
        }
        catch (Exception ex)
        {
            throw (ex);
        }  
    }

    private void getdetails()
    {
        try
        {
            SqlParameter[] param = new SqlParameter[] 
            {
                new SqlParameter("@vendor",ViewState["vendor"])
            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_GetPendingTxnAccVendorforVB", param);
            if (ds.Tables[0].Rows.Count > 0)
            {
                GridView1.Visible = true;
                GridView1.DataSource = ds;
                GridView1.DataBind();
                fill.Visible = true;
            }
            else
            {
                GridView1.Visible=false;
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('No Pending Transaction exists in the Data Base');"), true);
            }
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical problem.Please try again');"), true);
        }
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            GridView1.PageIndex = e.NewPageIndex;
            getdetails();
        }
        catch (Exception ex)
        {
            throw (ex);
        }  
    }

    protected void btnsucess_Click(object sender, EventArgs e)
    {
        try
        {
            bool flag = true;
            foreach (GridViewRow gvdr in this.GridView1.Rows)
            {
                if (((CheckBox)gvdr.FindControl("chkbox")).Checked)
                {
                    flag = false;
                    string ServiceName = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][0]);
                    string RefNo = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][1]);
                    string WLID = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][4]);
                    TextBox txt_commission = (TextBox)gvdr.FindControl("txtCommission");
                    SqlParameter[] param_del = new SqlParameter[]
                    {
                        new SqlParameter("@refrenceno",RefNo),
                        new SqlParameter("@lblServiceName",ServiceName),
                        new SqlParameter("@WLID",WLID)
                    };
                    SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_ChangeStatusToSuccessForVB", param_del);

                    GetTxnDetail(RefNo);
                    BalanceAfterTransaction = objcommonfun.userdetails(LoginID);
                    if (ServiceType == "MOBILE")
                    {
                        sms = "Final Status: TID- " + RefNo + " Mobile No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Success Current Balance is " + BalanceAfterTransaction + "";
                    }
                    else if (ServiceType == "DTH")
                    {
                        sms = "Final Status: TID- " + RefNo + " DTH No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Success Current Balance is " + BalanceAfterTransaction + "";
                    }
                    else
                    {
                        sms = "Final Status: TID- " + RefNo + " Data Card No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Success Current Balance is " + BalanceAfterTransaction + "";
                    }
                    objcommonfun.SendSMSByAdmin(AG_MobilNo, sms, RefNo, LoginID);
                }
            }
            if (flag)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Please select any check box');"), true);
            }
            else
            {
                getdetails();
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Record Approved Successfully');"), true);

            }
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical error, Please try after some time.');"), true);
            throw (ex);
        }
    }

    public void GetTxnDetail(string refrencenumber)
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@RefrenceNo",refrencenumber)
            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_GetTxnDetail", get_user_details);
            if (ds.Tables[0].Rows.Count > 0)
            {
                LoginID = ds.Tables[0].Rows[0]["COURENTLEVEL"].ToString();
                MobileNo = ds.Tables[0].Rows[0]["MobileDTHNumber"].ToString();
                ReqAmount = ds.Tables[0].Rows[0]["Amount"].ToString();
                AG_MobilNo = ds.Tables[0].Rows[0]["MOBILENO"].ToString();
                ServiceType = ds.Tables[0].Rows[0]["Type"].ToString();
            }
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical error, Please try after some time.');"), true);
        }
    }

    protected void btnRefund_Click(object sender, EventArgs e)
    {
        try
        {
            bool flag = true;
            foreach (GridViewRow gvdr in this.GridView1.Rows)
            {
                if (((CheckBox)gvdr.FindControl("chkbox")).Checked)
                {
                    flag = false;
                    string RefNo = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][1]);
                    string RequestAmount = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][2]);
                    string Agentid = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][3]);
                    string WLID = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][4]);
                    string OperatorMob = Convert.ToString(gvdr);
                    TextBox txt_commission = (TextBox)gvdr.FindControl("txtCommission");
                    SqlParameter[] param_del = new SqlParameter[]
                    {
                        new SqlParameter("@refrenceno",RefNo),
                        new SqlParameter("@AgentID",Agentid),
                        new SqlParameter("@REQUEST_AMOUNT",RequestAmount),
                        new SqlParameter("@WLID",WLID)
                    };
                    SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_UpdateStatus_Refund", param_del);

                    GetTxnDetail(RefNo);
                    BalanceAfterTransaction = objcommonfun.userdetails(LoginID);
                    if (ServiceType == "MOBILE")
                    {
                        sms = "Final Status: TID- " + RefNo + " Mobile No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Refunded Current Balance is " + BalanceAfterTransaction + "";
                    }
                    else if (ServiceType == "DTH")
                    {
                        sms = "Final Status: TID- " + RefNo + " DTH No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Refunded Current Balance is " + BalanceAfterTransaction + "";
                    }
                    else
                    {
                        sms = "Final Status: TID- " + RefNo + " Data Card No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Refunded Current Balance is " + BalanceAfterTransaction + "";
                    }
                    objcommonfun.SendSMSByAdmin(AG_MobilNo, sms, RefNo, LoginID);
                }
            }
            if (flag)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Please select any check box.');"), true);
            }
            else
            {
                getdetails();
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Transaction Refund Successfully.');"), true);
            }
        }
        catch (Exception ex)
        {
           // Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical error, Please try after some time.');"), true);
            throw (ex);
        }
    }

    protected void btnGetStatus_Click(object sender, EventArgs e)
    {
        try
        {
            bool flag = true;
            foreach (GridViewRow gvdr in this.GridView1.Rows)
            {
                if (((CheckBox)gvdr.FindControl("chkbox")).Checked)
                {
                    flag = false;
                    string ServiceName = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][0]);
                    string RefNo = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][1]);
                    string RequestAmount = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][2]);
                    string Agentid = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][3]);
                    string OperatorMob = Convert.ToString(gvdr);
                    string WLID = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][4]);
                    string OrderId = Convert.ToString(GridView1.DataKeys[gvdr.RowIndex][5]);
                    TextBox txt_commission = (TextBox)gvdr.FindControl("txtCommission");
                    if (ViewState["vendor"].Equals("eGenApi"))
                    {
                        string res = CommonFunction.eGenAPIRechargeGetStatus(RefNo);
                        ds.ReadXml(new StringReader(res));
                        if (ds.Tables["Response"].Rows.Count > 0)
                        {
                            //ViewState["resultCode"] = Convert.ToString(ds.Tables["Response"].Rows[0]["resultCode"]);
                            ViewState["Status"] = Convert.ToString(ds.Tables["Response"].Rows[0]["ResponseStatus"]);
                            //ds.Clear();
                            if (Convert.ToString(ViewState["Status"]).ToUpper()== "SUCCESS")
                            {
                                SqlParameter[] param_del = new SqlParameter[]
                                    {
                                        new SqlParameter("@refrenceno",RefNo),
                                        new SqlParameter("@lblServiceName",ServiceName),
                                        new SqlParameter("@WLID",WLID) ,
                                        new SqlParameter("@OperatorId",Convert.ToString(ds.Tables["Response"].Rows[0]["OperatorTxnID"]))
                                    };
                                SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_ChangeStatusToSuccessForVR", param_del);

                                GetTxnDetail(RefNo);
                                BalanceAfterTransaction = objcommonfun.userdetails(LoginID);
                                if (ServiceType == "MOBILE")
                                {
                                    sms = "Final Status: TID- " + RefNo + " Mobile No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Success Current Balance is " + BalanceAfterTransaction + "";
                                }
                                else if (ServiceType == "DTH")
                                {
                                    sms = "Final Status: TID- " + RefNo + " DTH No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Success Current Balance is " + BalanceAfterTransaction + "";
                                }
                                else
                                {
                                    sms = "Final Status: TID- " + RefNo + " Data Card No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Success Current Balance is " + BalanceAfterTransaction + "";
                                }
                                objcommonfun.SendSMSByAdmin(AG_MobilNo, sms, RefNo, LoginID);
                            }
                            else if (Convert.ToString(ViewState["Status"]).ToUpper() == "FAILED" || Convert.ToString(ViewState["Status"]).ToUpper() == "FAILURE")
                            {
                                SqlParameter[] param_del = new SqlParameter[]
                                    {
                                        new SqlParameter("@refrenceno",RefNo),
                                        new SqlParameter("@AgentID",Agentid),
                                        new SqlParameter("@REQUEST_AMOUNT",RequestAmount),
                                        new SqlParameter("@WLID",WLID)
                                    };
                                SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_UpdateStatus_Refund", param_del);

                                GetTxnDetail(RefNo);
                                BalanceAfterTransaction = objcommonfun.userdetails(LoginID);
                                if (ServiceType == "MOBILE")
                                {
                                    sms = "Final Status: TID- " + RefNo + " Mobile No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Refunded Current Balance is " + BalanceAfterTransaction + "";
                                }
                                else if (ServiceType == "DTH")
                                {
                                    sms = "Final Status: TID- " + RefNo + " DTH No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Refunded Current Balance is " + BalanceAfterTransaction + "";
                                }
                                else
                                {
                                    sms = "Final Status: TID- " + RefNo + " Data Card No " + MobileNo + " Amount " + ReqAmount + " status updated from Pending to Refunded Current Balance is " + BalanceAfterTransaction + "";
                                }
                                objcommonfun.SendSMSByAdmin(AG_MobilNo, sms, RefNo, LoginID);
                            }
                            else
                            {
                                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Process Complete Successfully');"), true);
                            }
                        }
                    }
                    else if (ViewState["vendor"].Equals("ExcelRecharge"))
                    {
                        ExcelRecharge(RefNo, Agentid, RequestAmount, OrderId, WLID, ServiceName);
                    }
                }
            }
            if (flag)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Please select any checkbox.');"), true);
            }
            else
            {
                getdetails();
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Process Completed.');"), true);
            }
        }
        catch (Exception ex)
        {
           // Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical error, Please try after some time.');"), true);
            throw (ex);
        }
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
    }
    public void ExcelRecharge(string ReferenceNo, string LoginID, string Amount, string OrderID, string WhiteLabelId, string Service)
    {
        string txn = CommonFunction.ExcelRechargeGetReResponse(ReferenceNo, OrderID);        
        string res = txn;
        if (!(res.Contains("ERROR") || res.Contains("error")))
        {
            ds.ReadXml(new StringReader(res));
            if (ds.Tables["RechargeStatus"].Rows.Count > 0)
            {
                string TxnID = Convert.ToString(ds.Tables["RechargeStatus"].Rows[0]["OrderId"]);
                ViewState["Status"] = Convert.ToString(ds.Tables["RechargeStatus"].Rows[0]["Status"]);
                //string refrenceno = Convert.ToString(ds.Tables["RechargeStatus"].Rows[0]["MerOid"]);
                //string OperatorTxnId = Convert.ToString(ds.Tables["RechargeStatus"].Rows[0]["OperatorTxnId"]);
                //string Description = Convert.ToString(ds.Tables["RechargeStatus"].Rows[0]["Description"]);
                ds.Clear();
                if (ViewState["Status"].Equals("SUCCESS") || ViewState["Status"].Equals("success"))
                {
                    SqlParameter[] param_del = new SqlParameter[]
                    {
                        new SqlParameter("@refrenceno",ReferenceNo),
                        new SqlParameter("@lblServiceName",Service),
                        new SqlParameter("@WLID",WhiteLabelId)  
                    };
                    SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_ChangeStatusToSuccessForVB", param_del);
                }
                else if (ViewState["Status"].Equals("Pending") || ViewState["Status"].Equals("PENDING"))
                {
                    
                }
                else
                {
                    SqlParameter[] param_del = new SqlParameter[]
                    {
                        new SqlParameter("@refrenceno",ReferenceNo),
                        new SqlParameter("@AgentID",LoginID),
                        new SqlParameter("@REQUEST_AMOUNT",Amount),
                        new SqlParameter("@WLID",WhiteLabelId)
                    };
                    SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_UpdateStatus_Refund", param_del);
                }
            }
            
        }
    }
}
