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

public partial class Admin_ChangeMpin : System.Web.UI.Page
{
    string Mpin;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["AdminEMAILID"] == null)
            {
                Response.Redirect("AdminLogin.aspx");
            }
            if (!IsPostBack)
            {
                GetUserName();
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }    
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (ddlUserName.SelectedItem.Text == "Select User Name" && txtMobileNo.Text == "")
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Please Select User Name And Enter Mobile Number');"), true);
            }
            else
            {
                Random rand = new Random();
                rand.Next(0, 1);
                for (int i = 0; i <= 1; i++)
                {
                    Mpin = RandomString(rand, 4);
                }
                try
                {
                    SqlParameter[] ParamSetMpin = new SqlParameter[]
                    {
                        new SqlParameter("@Mpin",Mpin),
                        new SqlParameter("@LoginId",Convert.ToInt32(ddlUserName.SelectedValue)),
                        new SqlParameter("@MobileNo",txtMobileNo.Text.Trim()),
                    };
                    int NoOfRowsEffected = Convert.ToInt32(SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_SetMpin", ParamSetMpin));
                    if (NoOfRowsEffected > 0)
                    {
                        SendSMS(txtMobileNo.Text.Trim(), "You MPIN is successfully reset and current MPIN is " + Mpin + " Delete MPIN containing SMS for security of your account. Venus Recharge");
                        SaveSms(ddlUserName.SelectedValue, "You MPIN is successfully reset and current MPIN is " + Mpin + " Delete MPIN containing SMS for security of your account. Venus Recharge");
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Mpin Successfully Set');"), true);
                        ddlUserName.SelectedIndex = 0;
                        txtMobileNo.Text = "";
                    }
                    else
                    {
                        ddlUserName.SelectedIndex = 0;
                        txtMobileNo.Text = "";
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Mpin Not Set Please Enter Correct Detail');"), true);
                    }
                }
                catch (Exception ex)
                {
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical problem. Please try again');"), true);
                }
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }  
    }

    private void GetUserName()
    {
        try
        {
            SqlParameter[] param = new SqlParameter[]
            {
            };

            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_login_details", param);
            if (ds.Tables[0].Rows.Count != 0)
            {
                ddlUserName.DataSource = ds;
                ddlUserName.DataTextField = "USERNAME";
                ddlUserName.DataValueField = "LOGINID";
                ddlUserName.Items.Clear();
                ddlUserName.Items.Insert(0, new ListItem("Select User Name", "Select User Name"));
                ddlUserName.DataBind();
            }
            else
            {
                ddlUserName.Items.Clear();
                ddlUserName.Items.Insert(0, new ListItem("No User Name Available", "No User Name Available"));
                ddlUserName.DataBind();
            }
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical problem. Please try again');"), true);
        }
    }

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

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

        return sb.ToString();
    }
    private void SendSMS(string MobileNo, string sms)
    {
        string strUrl = "http://sms.igenservices.in/api/web2sms.php?workingkey=A0c8f3938f877b4a46175dfa15e04b064&sender=RECHRG&to=" + MobileNo + "&message=" + sms + "";
        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();
    }

    private void SaveSms(string loginid, string sms)
    {
        try
        {
            SqlParameter[] paramSaveSms = new SqlParameter[] 
            {
                new SqlParameter("@Sms",sms),
                new SqlParameter("@UserId",loginid),
            };
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_InsertSmsUsedByAdmin", paramSaveSms);
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical problem. Please try again');"), true);
            throw (ex);
        }
    }
}
