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

public partial class AddUsers : System.Web.UI.Page
{
    string refrenceno;
    string username;
    string UNAME;
    string filepath;
    string SavePathHL = "~/WhiteLabelLogo/";
    string Ipaddress = HttpContext.Current.Request.UserHostAddress.ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["AdminEMAILID"] == null)
            {
                Response.Redirect("AdminLogin.aspx");
            }
            if (!IsPostBack)
            {
                c1.Visible = false;
                NameValueCollection queryString = stringhelpers.DecryptQueryString(Request.QueryString.ToString());
                if (queryString != null)
                {
                    if (queryString["var"].Equals("White Label"))
                    {
                        DropDownList3.SelectedIndex = 1;
                    }
                }
                BindDropdown("select * from StateTable", ddl_State_OA, "StateID", "StateName", null, null);
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }    
    }
    protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (DropDownList3.SelectedItem.Text.Equals("White Label"))
            {
                c1.Visible = true;
            }
            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") + "");
            }
            else if (DropDownList3.SelectedItem.Text.Equals("API"))
            {
                Response.Redirect("APIRegistration.aspx" + stringhelpers.EncryptQueryString("var=API") + "");
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }    
    }
    protected void ddl_State_OA_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            BindDropdown("select * from DistrictName where StateID='" + ddl_State_OA.SelectedValue + "'", ddl_Distric_OA, "CityId", "CityName", null, null);
        }
        catch (Exception ex)
        {
            throw (ex);
        }    
    }
    protected void btnWlReg_Click(object sender, EventArgs e)
    {
        try
        {
            registration();
        }
        catch (Exception ex)
        {
            throw (ex);
        }    
    }
    public void BindDropdown(string sql, DropDownList InputDropDown, string ColValToBind, string ColTextToBind, string DropdownSelItem, string DropdownSelValue)
    {
        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, new ListItem("Select", "Select"));

            InputDropDown.DataBind();

            //ObjConn.Close();
            if (DropdownSelValue != "")
            {
                foreach (ListItem LstItem in InputDropDown.Items)
                {
                    if (DropdownSelItem == LstItem.Value)
                    {
                        LstItem.Selected = true;
                    }
                }
            }
        }
        catch (Exception objException)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Error=" + objException +"');"), true);
            throw (objException);
        }
    }

    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.Substring(mystring.Length - 5);
                username = "WL" + res;
            }
            int CheckStatusUserName = checkuseravailability(username, txtEmailId.Text, txtAuthorizePersonMobileNo.Text, "USERNAME");
            if (CheckStatusUserName == 0)
            {
                //AVAILABIL
                int CheckStatusEmail = checkuseravailability(username, txtEmailId.Text, txtAuthorizePersonMobileNo.Text, "EMAIL");
                if (CheckStatusEmail == 0)
                {
                    //AVAILABIL
                    int CheckStatusMobileNo = checkuseravailability(username, txtEmailId.Text, txtAuthorizePersonMobileNo.Text, "MOBILENO");
                    if (CheckStatusMobileNo == 0)
                    {
                        UploadFile();
                        //AVAILABIL
                        Random rand = new Random();
                        rand.Next(0, 1);
                        for (int i = 0; i <= 1; i++)
                        {
                            refrenceno = RandomString(rand, 10);
                        }
                        SqlParameter[] whiteLabelDetail = new SqlParameter[]
                        {
                            new SqlParameter("@INITIAL","WL"),//1
                            new SqlParameter("@USERTYPE","Master Admin"),//2
                            new SqlParameter("@USERNAME",username),//3
                            new SqlParameter("@PASSWORD",refrenceno),//7
                            new SqlParameter ("@EMAILID","customercare@venusrecharge.com"),                    

                            new SqlParameter ("@CategoryUC",ddlCategory.SelectedItem.Text.Trim()),
                            new SqlParameter ("@CategoryUI",ddlCategory.SelectedValue.ToString()),
                            new SqlParameter ("@CompanyName",txtCompanyName.Text.Trim()),
                            new SqlParameter ("@HeaderLogo",ViewState["FilenameId"].ToString()),
                            new SqlParameter ("@HelpDeskMobileNo1",txtHelpDeskMobileNo1.Text.Trim()),
                            new SqlParameter ("@HelpDeskMobileNo2",txtHelpDeskMobileNo2.Text.Trim()),
                            new SqlParameter ("@HelpDeskEmailId",txtHelpDeskEMailID.Text.Trim()),
                            new SqlParameter ("@DomaimName",txtDomainName.Text.Trim()),
                            new SqlParameter ("@Copyright",txtCopyright.Text.Trim()),
                            new SqlParameter ("@AgentPanelTital",txtAgentPanelTitle.Text.Trim()),
                            new SqlParameter ("@DistributorPanelTitle",""),
                            new SqlParameter ("@PortalName",txtPortalName.Text.Trim()),
                                                        
                            new SqlParameter ("@SelectName",ddl_Authorize_Person_Name.SelectedItem.Text.Trim()),
                            new SqlParameter ("@FirstName",txtAuthorizePersonName1.Text.Trim()),
                            new SqlParameter ("@MiddleName",txtAuthorizePersonName2.Text.Trim()),
                            new SqlParameter ("@LastName",txtAuthorizePersonName3.Text.Trim()),
                            new SqlParameter ("@DATEOFBIRTH",""),
                            new SqlParameter ("@GENDER",""),
                            new SqlParameter ("@MARITALSTATUS",""),
                            new SqlParameter ("@FATHERSNAME",""),
                            new SqlParameter ("@MOTHERSNAME",""),
                            new SqlParameter ("@OCCUPATION",""),
                            new SqlParameter ("@CORPORATENAME",""),
                            new SqlParameter ("@DESIGNATION",""),

                            new SqlParameter ("@OFFICEADDRESSLINE1",txtAddressLineOF1.Text.Trim()),
                            new SqlParameter ("@OFFICEADDRESSLINE2",""),
                            new SqlParameter ("@OFFICECOUNTRY","India"),
                            new SqlParameter ("@OFFICESTATE",ddl_State_OA.SelectedItem.Text.Trim()),
                            new SqlParameter ("@OFFICEDISTRIC",ddl_Distric_OA.SelectedItem.Text.Trim()),
                            new SqlParameter ("@OFFICECITY",txt_City_OA.Text.Trim()),
                            new SqlParameter ("@NEARBYLANDMARKOA",""),
                            new SqlParameter ("@OFFICEPIN",""),
                            new SqlParameter ("@OFFICEMOBILE",""),
                            new SqlParameter ("@OFFICEMOBILENOALTER",""),
                            new SqlParameter ("@OFFICEPHONE",""),
                            new SqlParameter ("@OFFICEFAX",""),
                            new SqlParameter ("@WEBSITE",""),

                            new SqlParameter ("@RESIDADDRESSLINE1",""),
                            new SqlParameter ("@RESIDADDRESSLINE2",""),
                            new SqlParameter ("@RESIDCOUNTRY",""),
                            new SqlParameter ("@RESIDSTATE",""),
                            new SqlParameter ("@RESIDDISTRIC",""),
                            new SqlParameter ("@RESIDCITY",""),
                            new SqlParameter ("@NEARBYLANDMARKRA",""),
                            new SqlParameter ("@RESIDPIN",""),

                            new SqlParameter ("@PRIMARYPANTINNUMBER",txtPansTaxTinNumber.Text.Trim()),
                            new SqlParameter ("@PRIMARYEMAILID",txtEmailId.Text.Trim()),
                            new SqlParameter ("@PRIMARYALTERNATEEMAILID",""),
                            new SqlParameter ("@PRIMARYAUTHORIZEDMOBILENO",txtAuthorizePersonMobileNo.Text.Trim()),
                            new SqlParameter ("@PRIMARYAUTHORIZEDMOBILENOALTER"," "),

                            new SqlParameter("@IPAddress",Ipaddress),
                        };
                        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UDP_INSERT_WHITELABEL_INFORMATION", whiteLabelDetail);                        
                        sendmail();
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Whitelabel Registration Successfull');"), true);                        
                        CommonFunction.ClearControlValues(tblRegFrm);
                    }
                    else
                    {
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('This Mobile No is already  Exist');"), true);
                    }
                }
                else
                {
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('This Email Id is already  Exist');"), true);
                }
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical problem. Please try again');"), true);
            }

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

    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),
            };
            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);
            //int errorresult = Convert.ToInt32(param_checkavailibility[5].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();
    }

    public void UploadFile()
    {
        try
        {
            HttpPostedFile myFile4 = FileUpload_Img_Header.PostedFile;
            int FileLen4 = myFile4.ContentLength;
            if (FileUpload_Img_Header.FileName != "")
            {
                byte[] myData = new Byte[FileLen4];
                if (FileUpload_Img_Header.HasFile)
                {
                    myFile4.InputStream.Read(myData, 0, FileLen4);
                    ViewState["FilenameId"] = Path.GetFileName(myFile4.FileName);
                    //int file_append = 0;
                    //while (File.Exists(Server.MapPath(SavePathHL + ViewState["FilenameId"])))
                    //{
                    //    file_append++;
                    //    ViewState["FilenameId"] = Path.GetFileNameWithoutExtension(myFile4.FileName) + file_append.ToString();
                    //    ViewState["FilenameId"] = ViewState["Filename"] + Path.GetExtension(myFile4.FileName);
                    //}
                    if (FileUpload_Img_Header.PostedFile.ContentLength > 105944)
                    {
                        lblsucess.Text = "Too large Image. This image is not allowed";
                    }
                    else
                    {
                        filepath = SavePathHL + ViewState["FilenameId"];

                        FileUpload_Img_Header.SaveAs(MapPath(filepath));
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('" + ex + "');"), true);
            throw (ex);
        }
    }

    private void sendmail()
    {
        try
        {
            MailMessage message = new MailMessage();
            message.Body = mailmsg();
            message.IsBodyHtml = true;
            message.To.Add(txtEmailId.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("enquiry@egenservices.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('Sen 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 >Dear " + ddl_Authorize_Person_Name.SelectedItem.Text.Trim() + " " + txtAuthorizePersonName1.Text + " </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 </td></tr>");
        strHTML.Append("<tr><td width=100%>Here is Your User Type,User Id and Password</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>User Type</b></td><td width=70% >Master Admin</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>User Id</b></td><td width=70% >" + username + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Password</b></td><td width=70% >" + refrenceno + "</td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >You may now log on to <a href=" + txtDomainName.Text + "/login.aspx target='_blank'>" + txtDomainName.Text + "/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();
    }
    
}
