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

public partial class AddDistributor : System.Web.UI.Page
{
    string refrenceno;
    decimal balance;
    string username;
    string UNAME;
    string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
    string sms="Your Master Distributor Account Create Successfully.Login detail has been send to your registered EmailID";
    string month = DateTime.Now.ToString("MM");
    CommonFunction comonobj = new CommonFunction();
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                BindDropdown("select * from StateTable", ddl_State_OA, "StateID", "StateNAme", null, null);
            }
            txt_Date_Of_Birth.Attributes.Add("readonly", "readonly");
        }
        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();

            //ObjConn.Close();
            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)
    {
        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 Button1_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session["USERTYPE"].Equals("Master Admin"))
            {
                //MobileNo = txt_Authorized_Mobile_No.Text;
                registration();
            }
            else
            {
                lblsucess.Text = "Please log out other account";
                lblsucess.ForeColor = Color.Red;
            }
        }
        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.Substring(mystring.Length - 5);                
                username = "MDS" + res;                
            }
            int CheckStatusUserName = checkuseravailability(username, txt_EMail_ID.Text, txt_Authorized_Mobile_No.Text, "USERNAME");
            if (CheckStatusUserName == 0)
            {
                //AVAILABIL EGENAG00649
                int CheckStatusEmail = checkuseravailability(username, txt_EMail_ID.Text, txt_Authorized_Mobile_No.Text, "EMAIL");
                if (CheckStatusEmail == 0)
                {
                    //AVAILABIL
                    int CheckStatusMobileNo = checkuseravailability(username, txt_EMail_ID.Text, txt_Authorized_Mobile_No.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","MDS"),//1
                            new SqlParameter("@USERTYPE","Master Distributor"),//2
                            new SqlParameter("@USERNAME",username),//3
                            new SqlParameter("@PASSWORD",refrenceno),//7
                            new SqlParameter("@Mpin","1234"),                            
                            new SqlParameter("@Month",month),
                            new SqlParameter("@Domainname",ConfigurationManager.AppSettings["WebsiteUrl"].ToString()),
                            new SqlParameter("@UPPERLEVEL",Session["LOGINID"].ToString()),

                            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",txt_Date_Of_Birth.Text.Trim()),
                            new SqlParameter("@GENDER",ddl_Gender_MF.SelectedItem.Text.Trim()),//16
                            new SqlParameter("@MARITALSTATUS",ddl_Gender_MU.SelectedItem.Text.Trim()),                            

                            new SqlParameter("@OFFICEADDRESSLINE1",txt_Office_Address1.Text),//23
                            new SqlParameter("@OFFICEADDRESSLINE2",txt_Office_Address2.Text.Trim()),//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",txt_Nearby_Land_Mark_OA.Text),
                            new SqlParameter("@OFFICEMOBILE","00"),                            
                            new SqlParameter("@OFFICEPHONE",txt_Phone_Fax_OA1.Text+""+txt_Phone_Fax_OA2.Text),//29
                            new SqlParameter("@OFFICEFAX",txt_Phone_Fax_OA3.Text),
                           
                            new SqlParameter("@RESIDADDRESSLINE1"," "),                            
                            new SqlParameter("@RESIDCOUNTRY"," "),
                            new SqlParameter("@RESIDSTATE"," "),                            
                            new SqlParameter("@RESIDCITY"," "),                            

                            new SqlParameter("@PRIMARYPANTINNUMBER",txt_Pan_Tin_Number.Text),
                            new SqlParameter("@PRIMARYEMAILID",txt_EMail_ID.Text),
                            new SqlParameter("@PRIMARYALTERNATEEMAILID",txt_Alternate_Email_ID.Text),
                            new SqlParameter("@PRIMARYAUTHORIZEDMOBILENO",txt_Authorized_Mobile_No.Text),                          
                            
                            new SqlParameter("@IPAddress",IPAddress),
                        };
                        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UDP_INSERT_USER_INFORMATION_AND_AMOUNTMDS", parampartnerregistration);
                        comonobj.SendSMSByAdmin(txt_Authorized_Mobile_No.Text, sms, refrenceno, UNAME);
                        lblsucess.Text = "Your Master Distributor has been registered successfully. And login details has been sent to Master Distributor registered e-mail address.";
                        lblsucess.ForeColor = Color.Blue;
                        sendmail();
                        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)
        {
            string st = ex.Message;
        }
    }

    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;
            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(Session["helpdeskemailid"].ToString());
                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 = Session["CompanyName"] + "Partner RegistrationForm";
                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 >Dear " + ddl_Sir_Name.SelectedItem.Text.Trim() + " " + txt_Auth_Pers_Name.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 " + Session["CompanyName"] + ", thank you for registering with us.</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 Distributor</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=20% align=left>Created By</b></td><td width=70% >" + Session["USERNAME"].ToString() + "</td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >You may now log on to <a href=" + ConfigurationManager.AppSettings["WebsiteUrl"] + "/login.aspx target='_blank'>" + ConfigurationManager.AppSettings["WebsiteUrl"] + "/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='" + Session["helpdeskemailid"].ToString() + "' target='_blank'>" + Session["helpdeskemailid"].ToString() + "</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 >" + Session["CompanyName"] + "</td></tr>");
        strHTML.Append("</table>");
        return strHTML.ToString();
    }

    private void deductamount()
    {
        try
        {
            SqlParameter[] deductmoney = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",Session["LOGINID"].ToString())
                
            };
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_deductamount", deductmoney);
        }
        catch (Exception ex)
        {

        }
    }
    
}
