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.Drawing;
using System.IO;
using System.Collections.Specialized;

public partial class DataCardAmount : System.Web.UI.Page
{
    CommonFunction objcom = new CommonFunction();
    Random rand = new Random();
    string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
    WBMobile_Noverification _ObjWBMNverify = new WBMobile_Noverification();
    private string _loginID;
    string errormessage = string.Empty;
    string txn, respmessage, TxnID,RefNumber;
    DataSet ds = new DataSet();
    static double BlanceInApi;
    static double ReqBalance;
    float balance, WLbalance, cutoffBalance;
    #region Declare private variable
    private double _balance;
    #endregion
    string varCircle;
    public string LoginID
    {
        get
        {
            return _loginID;
        }
        set
        {
            _loginID = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrEmpty(Convert.ToString(Session["LOGINID"])) && string.IsNullOrEmpty(Convert.ToString(Session["USERNAME"])))
            {
                Response.Redirect("../login.aspx");
            }
            LoginID = Convert.ToString(Session["LOGINID"]);
            if (!Page.IsPostBack)
            {
                lblOperator.Text = Session["operator"].ToString();
                ViewState["operatorValue"] = Session["operatorValue"].ToString();
                ViewState["ServiceProvider"] = Session["serviceprovider"].ToString();
                GetOperatorID(lblOperator.Text);
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }  
    }
    private void GetOperatorID(string mobileOperator)
    {
        SqlParameter[] ONLINEOFFLINEOPERATOR = new SqlParameter[]
        {
            new SqlParameter("@opname", mobileOperator),
            new SqlParameter("@OperatorType","Data Card")
        };
        DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UDP_GETONLINEOFFLINEOPERATOR", ONLINEOFFLINEOPERATOR);
        if (ds.Tables[0].Rows.Count != 0)
        {
            ViewState["OperatorID"] = ds.Tables[0].Rows[0]["MobileDthOperatorDetailsID"];
            ViewState["ServiceType"] = ds.Tables[0].Rows[0]["ServiceType"];
            ViewState["IWTOpID"] = ds.Tables[0].Rows[0]["IWTOpID"];
        }     
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            ReqBalance = Convert.ToDouble(txtAmount.Text);
            WLAmount();
            UserCutOffDetails();
            if (ViewState["ServiceProvider"].Equals("eGenApi"))
            {
                eGenApi();
            }
            else if (ViewState["ServiceProvider"].Equals("IWTApi"))
            {
                IWTApi();
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }  
    }

    public void UserCutOffDetails()
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",LoginID)
            };

            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getcutoffbalance", get_user_details);
            if (dr.Read())
            {
                cutoffBalance = Convert.ToInt32(dr["CuttOffAmount"]);
            }
        }
        catch (Exception ex)
        {
            string st = ex.Message;
        }
    }

    public void userdetails()
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",LoginID)
            };

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

    public static string TID_GEN()
    {
        string new_tid = System.Guid.NewGuid().ToString();
        new_tid = new_tid.Replace("-", string.Empty).ToLower();
        new_tid = new_tid.Substring(0, 14).Replace("a", "1");
        new_tid = new_tid.Substring(0, 14).Replace("b", "2");
        new_tid = new_tid.Substring(0, 14).Replace("c", "3");
        new_tid = new_tid.Substring(0, 14).Replace("d", "4");
        new_tid = new_tid.Substring(0, 14).Replace("e", "5");
        new_tid = new_tid.Substring(0, 14).Replace("f", "6");
        new_tid = new_tid.Substring(0, 14).Replace("g", "7");
        new_tid = new_tid.Substring(0, 14).Replace("h", "8");
        new_tid = new_tid.Substring(0, 14).Replace("i", "9");
        new_tid = new_tid.Substring(0, 14).Replace("j", "0");
        new_tid = new_tid.Substring(0, 14).Replace("k", "1");
        new_tid = new_tid.Substring(0, 14).Replace("l", "2");
        new_tid = new_tid.Substring(0, 14).Replace("m", "3");
        new_tid = new_tid.Substring(0, 14).Replace("n", "4");
        new_tid = new_tid.Substring(0, 14).Replace("o", "5");
        new_tid = new_tid.Substring(0, 14).Replace("p", "0");
        new_tid = new_tid.Substring(0, 14).Replace("q", "9");
        new_tid = new_tid.Substring(0, 14).Replace("r", "8");
        new_tid = new_tid.Substring(0, 14).Replace("s", "7");
        new_tid = new_tid.Substring(0, 14).Replace("t", "6");
        new_tid = new_tid.Substring(0, 14).Replace("u", "5");
        new_tid = new_tid.Substring(0, 14).Replace("v", "4");
        new_tid = new_tid.Substring(0, 14).Replace("w", "3");
        new_tid = new_tid.Substring(0, 14).Replace("x", "2");
        new_tid = new_tid.Substring(0, 14).Replace("y", "1");
        new_tid = new_tid.Substring(0, 14).Replace("z", "0");
        return new_tid;
    }

    public void WLAmount()
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",Session["WhitelabelId"].ToString())
            };

            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getavailablebalance", get_user_details);
            if (dr.Read())
            {
                WLbalance = Convert.ToInt32(dr["balance"]);
            }
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some problem please try after some time');"), true);
        }
    }

    public void eGenApi()
    {
        if (WLbalance > ReqBalance)
        {
            userdetails();
            if (balance > cutoffBalance)
            {
                if (balance > ReqBalance)
                {
                    RefNumber = TID_GEN();
                    int status1 = CommonFunction.InsertTransactionWithPendingStatus(Session["WhitelabelId"].ToString(), IPAddress.ToUpper(), RefNumber, LoginID, "Data Card", lblOperator.Text,
                            ViewState["OperatorID"].ToString(), "ALL", txtDataCardAcN.Text, txtAmount.Text, " ", "eGenApi", Session["PortalName"].ToString(), "Data Card Recharge");

                    if (status1 == 1)
                    {
                        Response.Redirect("MobileRecharge.aspx?error=There is some technical problem .Please try again");
                    }
                    else if (status1 == 2)
                    {
                        txn = CommonFunction.eGenAPIRecharge("datacard", ViewState["operatorValue"].ToString(), "ALL", txtDataCardAcN.Text, txtAmount.Text, RefNumber, Session["MobileNo"].ToString(), Session["LOGINID"].ToString());
                        SqlParameter[] TxnResponce = new SqlParameter[]
                    {
                         new SqlParameter("@TXNRESPONCE",txn),
                        new SqlParameter("@REFRENCENO",RefNumber)
                    };
                        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "USP_INSERTTXNRESPONCEFIRSTTIME", TxnResponce);

                        string res = txn;
                        if (!(res.Contains("error") || res.Contains("Error")))
                        {
                            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]["resultValue"]);
                                TxnID = Convert.ToString(ds.Tables["Response"].Rows[0]["operatorId"]);
                                if (ViewState["resultCode"].Equals("125") || ViewState["resultCode"].Equals("121") || ViewState["resultCode"].Equals("122"))
                                {
                                    if (ViewState["resultCode"].Equals("125"))
                                    {
                                        _ObjWBMNverify.FinalUpdate(Session["WhitelabelId"].ToString(), LoginID.ToString(), RefNumber, Convert.ToString(ReqBalance), "Success", ViewState["Status"].ToString(), txn, TxnID, "");
                                        Response.Redirect("DataCard.aspx?error=" + ViewState["Status"].ToString() + "");
                                    }
                                    else if (ViewState["resultCode"].Equals("121") || ViewState["resultCode"].Equals("122"))
                                    {
                                        _ObjWBMNverify.FinalUpdate(Session["WhitelabelId"].ToString(), LoginID.ToString(), RefNumber, Convert.ToString(ReqBalance), "Pending", ViewState["Status"].ToString(), txn, TxnID, "");
                                        Response.Redirect("DataCard.aspx?error=" + ViewState["Status"].ToString() + "");
                                    }
                                }
                                else
                                {
                                    _ObjWBMNverify.FinalUpdate(Session["WhitelabelId"].ToString(), LoginID.ToString(), RefNumber, Convert.ToString(ReqBalance), "Fail", ViewState["Status"].ToString(), txn, RefNumber, "");
                                    Response.Redirect("DataCard.aspx?error=" + ViewState["Status"].ToString() + "");
                                }
                            }
                        }
                        else
                        {
                            _ObjWBMNverify.FinalUpdate(Session["WhitelabelId"].ToString(), LoginID.ToString(), RefNumber, Convert.ToString(ReqBalance), "Fail", ViewState["Status"].ToString(), txn, RefNumber, "");
                            Response.Redirect("DataCard.aspx?error=" + ViewState["Status"].ToString() + "");
                        }
                    }
                }
                else
                {
                    lblerror.Text = "You don’t have enough balance to do this transaction. Please take balance in your login.";
                    Response.Redirect("DataCard.aspx?error=" + lblerror.Text + "");
                }
            }
            else
            {
                lblerror.Text = "Your balance is low from cutoff balance. Please take balance in your login.";
                Response.Redirect("DataCard.aspx?error=" + lblerror.Text + "");
            }
        }
        else
        {
            lblerror.Text = "Your Administrator don’t have enough balance to do this transaction.";
            Response.Redirect("DataCard.aspx?error=" + lblerror.Text + "");
        }
    }

    public void IWTApi()
    {
        if (WLbalance > ReqBalance)
        {
            userdetails();
            if (balance > cutoffBalance)
            {
                if (balance > ReqBalance)
                {
                    RefNumber = TID_GEN1();
                    int status1 = CommonFunction.InsertTransactionWithPendingStatus(Session["WhitelabelId"].ToString(), IPAddress.ToUpper(), RefNumber, LoginID, "Data Card", lblOperator.Text,
                            ViewState["OperatorID"].ToString(), "All CIRCLE", txtDataCardAcN.Text.Trim(), txtAmount.Text.Trim(), " ", "IWTApi", Session["PortalName"].ToString(), "Data Card Recharge");


                    if (status1 == 1)
                    {
                        Response.Redirect("DataCard.aspx?error=There is some technical problem .Please try again");
                    }
                    else if (status1 == 2)
                    {
                        txn = CommonFunction.IWTApiRecharge(LoginID, txtAmount.Text.Trim(), txtDataCardAcN.Text.Trim(), ViewState["IWTOpID"].ToString(), RefNumber, "", "", "Data Card-WEB");
                        SqlParameter[] TxnResponce = new SqlParameter[]
                        {
                            new SqlParameter("@TXNRESPONCE",txn),
                            new SqlParameter("@REFRENCENO",RefNumber)
                        };
                        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "USP_INSERTTXNRESPONCEFIRSTTIME", TxnResponce);
                        string res = txn;
                        ds.ReadXml(new StringReader(res));
                        if (ds.Tables["RechargeResponse"].Rows.Count > 0)
                        {
                            ViewState["ErrorCode"] = Convert.ToString(ds.Tables["RechargeResponse"].Rows[0]["ErrorCode"]);
                            ViewState["Desc"] = Convert.ToString(ds.Tables["RechargeResponse"].Rows[0]["Desc"]);
                            if (ViewState["ErrorCode"].Equals("00000"))
                            {
                                TxnID = Convert.ToString(ds.Tables["RechargeResponse"].Rows[0]["TxnID"]);
                                _ObjWBMNverify.FinalUpdate(Session["WhitelabelId"].ToString(), LoginID.ToString(), RefNumber, Convert.ToString(ReqBalance), "Success", ViewState["Desc"].ToString(), txn, TxnID, "");
                                Response.Redirect("DataCard.aspx?error=" + ViewState["Desc"].ToString() + "");
                            }
                            else
                            {
                                _ObjWBMNverify.FinalUpdate(Session["WhitelabelId"].ToString(), LoginID.ToString(), RefNumber, Convert.ToString(ReqBalance), "Fail", ViewState["Desc"].ToString(), txn, RefNumber, "");
                                Response.Redirect("DataCard.aspx?error=" + ViewState["Desc"].ToString() + "");
                            }
                        }
                        else
                        {
                            _ObjWBMNverify.FinalUpdate(Session["WhitelabelId"].ToString(), LoginID.ToString(), RefNumber, Convert.ToString(ReqBalance), "Fail", "Fail", txn, RefNumber, "");
                            Response.Redirect("DataCard.aspx?error=" + "Failed" + "");
                        }
                    }
                    else
                    {
                        lblerror.Text = "You don’t have enough balance to do this transaction. Please take balance in your login.";
                        Response.Redirect("DataCard.aspx?error=" + lblerror.Text + "");
                    }
                }
            }
            else
            {
                lblerror.Text = "Your balance is low from cutoff balance. Please take balance in your login.";
                Response.Redirect("DataCard.aspx?error=" + lblerror.Text + "");
            }
        }
        else
        {
            lblerror.Text = "Your Administrator don’t have enough balance to do this transaction.";
            Response.Redirect("DataCard.aspx?error=" + lblerror.Text + "");
        }
    }

    public static string TID_GEN1()
    {
        string new_tid = System.Guid.NewGuid().ToString();
        new_tid = new_tid.Replace("-", string.Empty).ToLower();
        new_tid = new_tid.Substring(0, 16).Replace("a", "1");
        new_tid = new_tid.Substring(0, 16).Replace("b", "2");
        new_tid = new_tid.Substring(0, 16).Replace("c", "3");
        new_tid = new_tid.Substring(0, 16).Replace("d", "4");
        new_tid = new_tid.Substring(0, 16).Replace("e", "5");
        new_tid = new_tid.Substring(0, 16).Replace("f", "6");
        new_tid = new_tid.Substring(0, 16).Replace("g", "7");
        new_tid = new_tid.Substring(0, 16).Replace("h", "8");
        new_tid = new_tid.Substring(0, 16).Replace("i", "9");
        new_tid = new_tid.Substring(0, 16).Replace("j", "0");
        new_tid = new_tid.Substring(0, 16).Replace("k", "1");
        new_tid = new_tid.Substring(0, 16).Replace("l", "2");
        new_tid = new_tid.Substring(0, 16).Replace("m", "3");
        new_tid = new_tid.Substring(0, 16).Replace("n", "4");
        new_tid = new_tid.Substring(0, 16).Replace("o", "5");
        new_tid = new_tid.Substring(0, 16).Replace("p", "0");
        new_tid = new_tid.Substring(0, 16).Replace("q", "9");
        new_tid = new_tid.Substring(0, 16).Replace("r", "8");
        new_tid = new_tid.Substring(0, 16).Replace("s", "7");
        new_tid = new_tid.Substring(0, 16).Replace("t", "6");
        new_tid = new_tid.Substring(0, 16).Replace("u", "5");
        new_tid = new_tid.Substring(0, 16).Replace("v", "4");
        new_tid = new_tid.Substring(0, 16).Replace("w", "3");
        new_tid = new_tid.Substring(0, 16).Replace("x", "2");
        new_tid = new_tid.Substring(0, 16).Replace("y", "1");
        new_tid = new_tid.Substring(0, 16).Replace("z", "0");
        return new_tid;
    }
}
