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.Text;
using System.Drawing;
using System.Net;
using System.Net.Mail;
using System.IO;

public partial class BillPaymentMode : 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();
    string status;
    private string _loginID;
    string Operator, RefNumber,Account;
    string errormessage = string.Empty;
    string txn, respmessage, TxnID;
    static string type;
    DataSet ds = new DataSet();
    static double BlanceInApi;
    static double ReqBalance;
    float balance, WLbalance, cutoffBalance;
    public string LoginID
    {
        get
        {
            return _loginID;
        }
        set
        {
            _loginID = value;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["LOGINID"].Equals(null))
            {
                Response.Redirect("../login.aspx", false);
            }
            LoginID = Session["LOGINID"].ToString();
            if (!Page.IsPostBack)
            {
                ViewState["operatorValue"] = Session["operatorValue"].ToString();
                ViewState["mobileoperator"] = Session["Operator"].ToString();
                ViewState["ServiceProvider"] = Session["serviceprovider"].ToString();
                lblOperator.Text = ViewState["mobileoperator"].ToString();
                GetOperatorID(lblOperator.Text);
                if (ViewState["mobileoperator"].Equals("Airtel Landline") || ViewState["mobileoperator"].Equals("MTNL Landline-Delhi"))
                {
                    divstdcode.Visible = true;
                    type = "landline";
                }
                else
                {
                    divstdcode.Visible = false;
                    type = "mobile";
                }
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }  
    }

    protected void btnNext_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;
        }
    }

    private void GetOperatorID(string mobileOperator)
    {
        SqlParameter[] ONLINEOFFLINEOPERATOR = new SqlParameter[]
        {
            new SqlParameter("@opname", mobileOperator),
            new SqlParameter("@OperatorType","Bill Payment")
        };
        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 btbBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("Billpayment.aspx");
    }

    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, "MOBILE", lblOperator.Text,
                            ViewState["OperatorID"].ToString(), "ALL", txtMobile.Text, txtAmount.Text, " ", "eGenApi", Session["PortalName"].ToString(), "Bill Payment");

                    if (status1 == 1)
                    {
                        Response.Redirect("Billpayment.aspx?error=There is some technical problem .Please try again");
                    }
                    else if (status1 == 2)
                    {
                        if (ViewState["operatorValue"].Equals("Airtel Landline") || ViewState["operatorValue"].Equals("MTNL Landline-Delhi"))
                        {
                            Account = TxtuserAccNo.Text;
                        }
                        else
                        {
                            Account = txtMobile.Text;
                        }
                        txn = CommonFunction.eGenAPIPostPaidRecharge("billpay", ViewState["operatorValue"].ToString(), "ALL", txtMobile.Text, Account, type, txt_stdcode.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("Billpayment.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("Billpayment.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("Billpayment.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("Billpayment.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("Billpayment.aspx?error=" + lblerror.Text + "");
                }
            }
            else
            {
                lblerror.Text = "Your balance is low from cutoff balance. Please take balance in your login.";
                Response.Redirect("Billpayment.aspx?error=" + lblerror.Text + "");
            }
        }
        else
        {
            lblerror.Text = "Your Administrator don’t have enough balance to do this transaction.";
            Response.Redirect("Billpayment.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, "MOBILE", lblOperator.Text,
                            ViewState["OperatorID"].ToString(), "All CIRCLE", txtMobile.Text.Trim(), txtAmount.Text.Trim(), " ", "IWTApi", Session["PortalName"].ToString(), "Bill Payment");


                    if (status1 == 1)
                    {
                        Response.Redirect("Billpayment.aspx?error=There is some technical problem .Please try again");
                    }
                    else if (status1 == 2)
                    {
                        txn = CommonFunction.IWTApiRecharge(LoginID, txtAmount.Text.Trim(), txtMobile.Text.Trim(), ViewState["IWTOpID"].ToString(), RefNumber, "", "", "BillPay-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("Billpayment.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("Billpayment.aspx?error=" + ViewState["Desc"].ToString() + "");
                            }
                        }
                        else
                        {
                            _ObjWBMNverify.FinalUpdate(Session["WhitelabelId"].ToString(), LoginID.ToString(), RefNumber, Convert.ToString(ReqBalance), "Fail", "Fail", txn, RefNumber, "");
                            Response.Redirect("Billpayment.aspx?error=" + "Failed" + "");
                        }
                    }
                    else
                    {
                        lblerror.Text = "You don’t have enough balance to do this transaction. Please take balance in your login.";
                        Response.Redirect("Billpayment.aspx?error=" + lblerror.Text + "");
                    }
                }
                else
                {
                    lblerror.Text = "You don’t have enough balance to do this transaction. Please take balance in your login.";
                    Response.Redirect("Billpayment.aspx?error=" + lblerror.Text + "");
                }
            }
            else
            {
                lblerror.Text = "Your balance is low from cutoff balance. Please take balance in your login.";
                Response.Redirect("Billpayment.aspx?error=" + lblerror.Text + "");
            }
        }
        else
        {
            lblerror.Text = "Your Administrator don’t have enough balance to do this transaction.";
            Response.Redirect("Billpayment.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;
    }
    
}
