using System;
using System.Collections;
using System.Collections.Specialized;
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.Text;
using System.Net;
using System.Net.Mail;
using System.IO;
using System.ComponentModel;
using System.Web.UI.WebControls.Adapters;
using NLog.Internal;

public partial class Admin_AddAgent : System.Web.UI.Page
{
    static string MPIN;
    string refrenceno;
    decimal balance;
    string username;
    static string UNAME, MobileNo;
    CommonFunction objcommonfun = new CommonFunction();
    string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
    string sms;
    string month = DateTime.Now.ToString("MM"); 
   
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["AdminEMAILID"] == null)
            {
                Response.Redirect("AdminLogin.aspx");
            }
            if (!IsPostBack)
            {
                NameValueCollection queryString = StringHelpers.DecryptQueryString(Request.QueryString.ToString());
                if (queryString != null)
                {
                    if (queryString["var"].Equals("Agent"))
                    {
                        DropDownList3.SelectedIndex = 4;
                    }
                }
                BindDropdown("select * from StateTable", ddl_State_OA, "StateID", "StateNAme", null, null);
                getdistributorID();
                SqlParameter[] param_profile = new SqlParameter[]
                { };
                SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.Text, "select max(LoginId)+1+9000000000 as USERNAME from LOGIN_DETAIL", null);
                if (dr.Read())
                {
                    txt_Authorized_Mobile_No.Text = dr["USERNAME"].ToString();
                  
                }
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }    
    }

    public void BindDropdown(string sql, DropDownList InputDropDown, string ColValToBind, string ColTextToBind, string DropdownSelItem, string DropdownSelValue)
    {
        string ReturnString;
        string strQuery;
        strQuery = sql;
        try
        {
            SqlParameter[] state = new SqlParameter[]
            {

            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.Text, strQuery, state);
            InputDropDown.DataSource = ds;
            InputDropDown.DataTextField = ColTextToBind;
            InputDropDown.DataValueField = ColValToBind;
            InputDropDown.Items.Clear();
            InputDropDown.Items.Insert(0, "Select");

            InputDropDown.DataBind();
            if (DropdownSelValue != "")
            {
                foreach (ListItem LstItem in InputDropDown.Items)
                {
                    if (DropdownSelItem == LstItem.Value)
                    {
                        LstItem.Selected = true;
                    }
                }
            }

        }
        catch (Exception objException)
        {
            ReturnString = "Error " + objException;
            throw (objException);
        }
    }

    protected void ddl_State_OA_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindDropdown("select * from DistrictName where StateID='" + ddl_State_OA.SelectedValue + "'", ddl_Distric_OA, "CityId", "CityName", null, null);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            MobileNo = txt_EMail_ID.Text;
            registration();
        }
        catch (Exception ex)
        {
            throw (ex);
        }    
    }

    private void registration()
    {
        try
        {           
            SqlParameter[] param_profile = new SqlParameter[]
            { };
            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.Text, "select max(LOGINID)+1 as USERNAME from LOGIN_DETAIL", null);

            if (dr.Read())
            {
                UNAME = dr["USERNAME"].ToString();
                string mystring = UNAME;
                string res = mystring;// mystring.Substring(mystring.Length - 5);                                
                username = "AG" + res;
                MPIN = TID_GEN();
                //sms = "Your ID is created MPIN is " + MPIN + " Use Format as VUS<space>(M for Mobile D for DTH)M<space>OP Code<space>Mob No<space>Amount<space>MPIN send to 8082556631";
                
            }
            int CheckStatusUserName = checkuseravailability(username, txtEmail.Text, txt_EMail_ID.Text, "USERNAME");
            if (CheckStatusUserName == 0)
            {
                //AVAILABIL EGENAG00649
                int CheckStatusEmail = checkuseravailability(username, txtEmail.Text, txt_EMail_ID.Text, "EMAIL");
                if (CheckStatusEmail == 0)
                {
                    //AVAILABIL
                    int CheckStatusMobileNo = checkuseravailability(username, txtEmail.Text, txt_EMail_ID.Text, "MOBILENO");
                    if (CheckStatusMobileNo == 0)
                    {
                        // UploadFile();

                        Random rand = new Random();
                        rand.Next(0, 1);
                        for (int i = 0; i <= 1; i++)
                        {
                            refrenceno = RandomString(rand, 10);
                        }
                        SqlParameter[] parampartnerregistration = new SqlParameter[]
                        {
                            new SqlParameter("@INITIAL","AG"),//1
                            new SqlParameter("@USERTYPE","Agent"),//2
                            new SqlParameter("@USERNAME",username),//3
                            new SqlParameter("@PASSWORD",refrenceno),//7
                            new SqlParameter("@Mpin",MPIN),
                            new SqlParameter("@Month",month),
                            new SqlParameter("@Domainname",ConfigurationManager.AppSettings["WebsiteUrl"].ToString()),
                            new SqlParameter("@UPPERLEVEL",ddl_Distributor.SelectedValue),

                            new SqlParameter("@FIRSTNAME",ddl_Sir_Name.SelectedItem.Text.Trim()+" "+txt_Auth_Pers_Name.Text),
                            new SqlParameter("@MIDDLENAME",txt_Middlename.Text.Trim()),
                            new SqlParameter("@LASTNAME",txt_Lastname.Text.Trim()),
                            new SqlParameter("@Companyfirmname",txt_companyfirmname.Text.Trim()) ,
                            new SqlParameter("@DATEOFBIRTH",""),
                            new SqlParameter("@GENDER",ddlGender.SelectedValue),//16
                            new SqlParameter("@MARITALSTATUS",""),                            

                            new SqlParameter("@OFFICEADDRESSLINE1",txt_Office_Address.Text),//23
                            new SqlParameter("@OFFICEADDRESSLINE2",""),//24
                            new SqlParameter("@OFFICECOUNTRY",lblcountry.Text.Trim()),
                            new SqlParameter("@OFFICESTATE",ddl_State_OA.SelectedItem.Text.Trim()),//14
                            new SqlParameter("@OFFICEDISTRIC",ddl_Distric_OA.SelectedItem.Text.Trim()),//13
                            new SqlParameter("@OFFICECITY",txt_City_OA.Text),
                            new SqlParameter("@OFFICEPIN",txt_Pin_Code_OA.Text.Trim()),
                            new SqlParameter("@NEARBYLANDMARKOA",""),
                            new SqlParameter("@OFFICEMOBILE",""),                            
                            new SqlParameter("@OFFICEPHONE",0),//29
                            new SqlParameter("@OFFICEFAX",0),                           

                            new SqlParameter("@RESIDADDRESSLINE1"," "),                            
                            new SqlParameter("@RESIDCOUNTRY",""),
                            new SqlParameter("@RESIDSTATE",""),//36                            
                            new SqlParameter("@RESIDCITY",""),                            

                            new SqlParameter("@PRIMARYPANTINNUMBER",txt_Pan_Tin_Number.Text),
                            new SqlParameter("@PRIMARYEMAILID",txt_EMail_ID.Text),
                            new SqlParameter("@PRIMARYALTERNATEEMAILID",txtEmail.Text),
                            new SqlParameter("@PRIMARYAUTHORIZEDMOBILENO",Convert.ToInt64(txt_Authorized_Mobile_No.Text)),                            
                            new SqlParameter("@IPAddress",IPAddress),
                            new SqlParameter("@Board",ddlBoard.SelectedItem.Text),
                            new SqlParameter("@DeviceId",txtDeviceId.Text.Trim()),
                            new SqlParameter("@Aadhaar",txtAadhaar.Text),
                            new SqlParameter("@FatherName",txtFatname.Text),
                            new SqlParameter("@BankName",txtBankName.Text),
                            new SqlParameter("@IFSC",txtIfsc.Text),
                            new SqlParameter("@AccountNo",txtAccountNo.Text)
                        };
                        int a=  SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UDP_INSERT_USER_INFORMATION_AND_AMOUNT_Air", parampartnerregistration);
                        
                            sms = "Thank You for registration. Welcome to OrangePay. Your login details username:" + username + ", Password: " + refrenceno;
                            //sendmail();
                            objcommonfun.SendSMSByAdmin(txt_EMail_ID.Text, sms, MPIN, UNAME);
                            lblsucess.Text = "Your Agent has been registered successfully. And login details has been sent to Agent registered e-mail address.";
                            lblsucess.ForeColor = Color.Blue;
                        Response.Redirect("AddAgent.aspx" + stringhelpers.EncryptQueryString("var=Agent") + "");
                        //CommonFunction.ClearControlValues(IdtblAgent);
                        
                    }
                    else
                    {
                        lblsucess.Text = "This Mobile Number is Already available";
                        lblsucess.ForeColor = Color.Red;
                    }
                }
                else
                {
                    lblsucess.Text = "This Email Id is Already available";//NOT AVAILABIL(Duplicate)
                    lblsucess.ForeColor = Color.Red;
                }
            }
            else
            {
                lblsucess.Text = "This UserName is Already available";//NOT AVAILABIL(Duplicate)
                lblsucess.ForeColor = Color.Red;
            }
        }

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

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

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

    private int checkuseravailability(string username, string emailid, string mobileno, string uniquekey)
    {
        try
        {
            SqlParameter[] param_checkavailibility = new SqlParameter[]
            {  
                new SqlParameter("@Username",username),   
                new SqlParameter("@Email",emailid),
                new SqlParameter("@MobileNo",mobileno),
                new SqlParameter("@Unique_Key_Name",uniquekey),
                new SqlParameter("@ReturnMessage",SqlDbType.Int),
                //new SqlParameter("@ErrorResult",SqlDbType.Int),
            };
            param_checkavailibility[4].Direction = ParameterDirection.Output;
            //param_checkavailibility[5].Direction = ParameterDirection.Output;
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UDP_CHECK_USERNAME_ETC_AVAILABILITY", param_checkavailibility);
            int Resultregstatus = Convert.ToInt32(param_checkavailibility[4].Value);           
            if (Resultregstatus == 0)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }
        catch (Exception EX)
        {
            return 2;
        }
    }

    public string RandomString(Random r, int len)
    {
        string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        StringBuilder sb = new StringBuilder();

        while ((len--) > 0)
            sb.Append(str[(int)(r.NextDouble() * str.Length)]);

        return sb.ToString();
    }

    private void sendmail()
    {
        if (username != "" && txt_EMail_ID.Text != "" && txt_Authorized_Mobile_No.Text != "")
        {
            try
            {
                MailMessage message = new MailMessage();
                message.Body = mailmsg();
                message.IsBodyHtml = true;
                message.To.Add(txt_EMail_ID.Text.Trim());
                message.Bcc.Add("customercare@venusrecharge.com");
                message.Bcc.Add("acvenus27@gmail.com");
                message.Bcc.Add("venushelp@yahoo.com");
                message.From = new System.Net.Mail.MailAddress("customercare@venusrecharge.com");
                message.Subject = "Venus Utility Services Partner Account Confirmation";
                message.Priority = MailPriority.High;
                SmtpClient SmtpMail = new SmtpClient();
                {
                    SmtpMail.Host = "smtp.gmail.com";
                    SmtpMail.Port = 587;
                    SmtpMail.EnableSsl = true;
                    SmtpMail.UseDefaultCredentials = true;
                    SmtpMail.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    SmtpMail.Credentials = new System.Net.NetworkCredential("venusutilityservices@gmail.com", "Venus@123");
                    SmtpMail.Send(message);
                }
                message = null;
            }
            catch (Exception ex)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Send Email Faild');"), true);
            }
        }
    }

    private string mailmsg()
    {
        StringBuilder strHTML = new StringBuilder();
        strHTML.Append("<table width=70% style='font-family:Trebuchet MS'>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >Hi</td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >Good Day!!</td></tr>");
        strHTML.Append("<tr><td width=100%>Welcome to Venus Utility Services, thank you for registering with us.</td></tr>");
        strHTML.Append("<tr><td width=100%>Here is Your User Id and Password</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>User Type</b></td><td width=70% align=Right>Agent</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>UserId</b></td><td width=70% align=Right>" + username + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Password</b></td><td width=70% align=Right>" + refrenceno + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Created By</b></td><td width=70% >" + ddl_Distributor.SelectedItem.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >You may now log on to <a href=http://www.venusrecharge.com/login.aspx target='_blank'>http://www.venusrecharge.com/login.aspx</a></td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >Some Important Points:</td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >1. Please Login into your account to use services</td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >2. We request you to change your password immediately for security reasons and keep it confidential.</td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >3. Please do not keep your user id & password at one place</b></td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >4. We recommend you to memorize the password and destroy any physical copy of the same</td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >5. For more details mail on to <a href='mailto:customercare@venusrecharge.com' target='_blank'>customercare@venusrecharge.com</a></td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >Regards</td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >Support Team</td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >Venus Utility Services</td></tr>");
        strHTML.Append("</table>");
        return strHTML.ToString();
    }

    private void getdistributorID()
    {
        try
        {
            SqlParameter[] getdistdetail = new SqlParameter[]
        {
            
        };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_AllDistributorID", getdistdetail);
            if (ds.Tables[0].Rows.Count > 0)
            {
                ddl_Distributor.DataSource = ds;
                ddl_Distributor.DataTextField = "USERNAME";
                ddl_Distributor.DataValueField = "LOGINID";
                ddl_Distributor.Items.Clear();
                ddl_Distributor.Items.Insert(0, new ListItem("Select User Name", "Select User Name"));
                ddl_Distributor.DataBind();
            }
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical problem. Please try again');"), true);
        }
    }

    protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList3.SelectedItem.Text.Equals("White Label"))
        {
            Response.Redirect("AddUsers.aspx" + stringhelpers.EncryptQueryString("var=White Label") + "");
        }
        else if (DropDownList3.SelectedItem.Text.Equals("Master Distributor"))
        {
            Response.Redirect("AddMDS.aspx" + stringhelpers.EncryptQueryString("var=Master Distributor") + "");
        }
        else if (DropDownList3.SelectedItem.Text.Equals("Distributor"))
        {
            Response.Redirect("AddDistributor.aspx" + stringhelpers.EncryptQueryString("var=Distributor") + "");
        }
        else if (DropDownList3.SelectedItem.Text.Equals("Agent"))
        {
            Response.Redirect("AddAgent.aspx" + stringhelpers.EncryptQueryString("var=Agent") + "");
        }
    }

    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, 4).Replace("a", "1");
        new_tid = new_tid.Substring(0, 4).Replace("b", "2");
        new_tid = new_tid.Substring(0, 4).Replace("c", "3");
        new_tid = new_tid.Substring(0, 4).Replace("d", "4");
        new_tid = new_tid.Substring(0, 4).Replace("e", "5");
        new_tid = new_tid.Substring(0, 4).Replace("f", "6");
        new_tid = new_tid.Substring(0, 4).Replace("g", "7");
        new_tid = new_tid.Substring(0, 4).Replace("h", "8");
        new_tid = new_tid.Substring(0, 4).Replace("i", "9");
        new_tid = new_tid.Substring(0, 4).Replace("j", "0");
        new_tid = new_tid.Substring(0, 4).Replace("k", "1");
        new_tid = new_tid.Substring(0, 4).Replace("l", "2");
        new_tid = new_tid.Substring(0, 4).Replace("m", "3");
        new_tid = new_tid.Substring(0, 4).Replace("n", "4");
        new_tid = new_tid.Substring(0, 4).Replace("o", "5");
        new_tid = new_tid.Substring(0, 4).Replace("p", "0");
        new_tid = new_tid.Substring(0, 4).Replace("q", "9");
        new_tid = new_tid.Substring(0, 4).Replace("r", "8");
        new_tid = new_tid.Substring(0, 4).Replace("s", "7");
        new_tid = new_tid.Substring(0, 4).Replace("t", "6");
        new_tid = new_tid.Substring(0, 4).Replace("u", "5");
        new_tid = new_tid.Substring(0, 4).Replace("v", "4");
        new_tid = new_tid.Substring(0, 4).Replace("w", "3");
        new_tid = new_tid.Substring(0, 4).Replace("x", "2");
        new_tid = new_tid.Substring(0, 4).Replace("y", "1");
        new_tid = new_tid.Substring(0, 4).Replace("z", "0");
        return new_tid;
    }
}
