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 Distributor_AddAgent : System.Web.UI.Page
{
    static string Mpin;
    string refrenceno;
    string username;
    string UNAME;
    string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
    string sms;
    string month = DateTime.Now.ToString("MM");
    CommonFunction objcommonfun = new CommonFunction();
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {

				Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('This service has been stopped. Please contact to Support.');window.location ='Index.aspx';"), true);
                    return;
                if (GetAgentLimit())
                {
                    BindDropdown("select * from StateTable", ddl_State_OA, "StateID", "StateNAme", null, null);
                }
                else
                {

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Your Agent creation limit exceeded. Please contact to Support.');window.location ='Index.aspx';"), true);
                    return;
                   
                }


               
            }
            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)
    {
        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
        {
            if (Session["USERTYPE"].Equals("Distributor"))
            {
                
                    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);
                Mpin = TID_GEN();
                username = "AG" + res;
                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, txt_EMail_ID.Text, txt_Authorized_Mobile_No.Text, "USERNAME");
            if (CheckStatusUserName == 0)
            {
                int CheckStatusEmail = checkuseravailability(username, txt_EMail_ID.Text, txt_Authorized_Mobile_No.Text, "EMAIL");
                if (0 == 0) //if (CheckStatusEmail == 0)
                {
                    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","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",Session["LOGINID"].ToString()),
                            new SqlParameter("@WLloginid",Session["WhitelabelId"].ToString()),
                            new SqlParameter("@Tital",ddl_Sir_Name.SelectedItem.Text),
                            new SqlParameter("@FIRSTNAME",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"," "),                            
                            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),
                            new SqlParameter("@Result",SqlDbType.Int),
                            new SqlParameter("@Subdiv",txtsubdiv.Text)
                        };
                        parampartnerregistration[37].Direction = ParameterDirection.Output;
                        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UDP_INSERT_USER_INFORMATION_AND_AMOUNT", parampartnerregistration);
                        int result = Convert.ToInt32(parampartnerregistration[37].Value);
                        if (result == 0)
                        {
                            sendmail();
                            lblsucess.Text = "Your Agent has been registered successfully. And login details has been sent to agent registered e-mail address.";
                            lblsucess.ForeColor = Color.Blue;
                            objcommonfun.SendSMSByAdmin(txt_Authorized_Mobile_No.Text, sms, Mpin, UNAME);
                            //SendSMS(txt_Authorized_Mobile_No.Text, sms);
                            CommonFunction.ClearControlValues(IdtblAgent);
                        }
                        else
                        {
                            lblsucess.Text = "Insufficient balance to create new agent.";
                            lblsucess.ForeColor = Color.Red;
                        }

                    }
                    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)
        {
            lblsucess.Text = "" + ex;
        }
    }

    private bool GetAgentLimit()
    {
        
        SqlParameter[] warlock = new SqlParameter[]
            { 
                 new SqlParameter("@LoginId",Convert.ToString(Session["LOGINID"].ToString()))
            };
        DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "sp_get_AgentLimitStatus", warlock);
        if (ds.Tables[0].Rows[0][0].ToString() == "True")
        {
            return true;
        }
        else
            return false;
            
    }

    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(Session["helpdeskemailid"].ToString());
                message.Bcc.Add("aloksingh17.88@gmai.com");
                message.From = new System.Net.Mail.MailAddress("accounts@orangepay.in");
                message.Subject = Session["CompanyName"] + " Partner RegistrationForm";
                message.Priority = MailPriority.High;
                SmtpClient SmtpMail = new SmtpClient();
                {
                    SmtpMail.Host = "smtp.orangepay.in";
                    SmtpMail.Port = 465;
                    SmtpMail.EnableSsl = true;
                    SmtpMail.UseDefaultCredentials = true;
                    SmtpMail.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    SmtpMail.Credentials = new System.Net.NetworkCredential("accounts@orangepay.in", "Qd74va#7");
                    SmtpMail.Send(message);
                }
                message = null;
            }
            catch (Exception ex)
            {
                lblsucess.Text = "Send Email Failed.<br>" + ex.Message;
                lblsucess.ForeColor = Color.Red;
            }
        }
    }
    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 <b>" + ddl_Sir_Name.SelectedItem.Text.Trim() + " " + txt_Auth_Pers_Name.Text + "</b> </td></tr>");
        strHTML.Append("<tr><td width=100% colspan=2 align=left >Have a Good Day!!</td></tr>");
        strHTML.Append("<tr><td width=100%>Welcome to <b>" + Session["CompanyName"] + "</b>, thank you for registering with us.</td></tr>");
        strHTML.Append("<tr><td width=100%>Please find below your User Type,User Id and Password</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>User Type</b></td><td width=70% ><b>Agent</b></td></tr>");
        strHTML.Append("<tr><td width=20% align=left>User Id</b></td><td width=70% ><b>" + username + "</b></td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Password</b></td><td width=70% ><b>" + refrenceno + "</b></td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Created By</b></td><td width=70% ><b>" + Session["USERNAME"].ToString() + "</b></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)
    //    {

    //    }
    //}
    private void SendSMS(string MobileNo, string sms)
    {
        string strUrl = "http://api.mVaayoo.com/mvaayooapi/MessageCompose?user=alliance@egenservices.com:8430082781&senderID=ACTVTE&receipientno=" + MobileNo + "&msgtxt=" + sms + "&state=4";
        WebRequest request = HttpWebRequest.Create(strUrl);
        request.Method = "GET";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream s = (Stream)response.GetResponseStream();
        StreamReader readStream = new StreamReader(s);
        string dataString = readStream.ReadToEnd();
        response.Close();
        s.Close();
        readStream.Close();
    }

    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;
    }


}

