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

public partial class DigitalSignature : System.Web.UI.Page
{
    string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
    string refrenceno;
    decimal balance;
    int ReqBalance;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["LOGINID"] == null && Session["USERNAME"] == null)
            {
                Response.Redirect("../login.aspx");
            }
            if (!IsPostBack)
            {
                BindDropdown("select * from StateTable", ddlState, "StateID", "StateNAme", null, null);
            }
        }
        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[] deductmoney = new SqlParameter[]
            {
                
            };

            DataSet ds=SqlHelper.GetDataSet(SqlHelper.mainConnectionString,CommandType.Text, strQuery, deductmoney);
            //cmd = new SqlCommand(strQuery, cn);
            //dbDataReader = cmd.ExecuteReader();
            InputDropDown.DataSource = ds;
            InputDropDown.DataTextField = ColTextToBind;
            InputDropDown.DataValueField = ColValToBind;
            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 btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            userdetails();
            if (ddlTimeDuration.SelectedItem.Text == "One Year")
            {
                if (balance < 350)
                {
                    lblsucess.Text = "You don’t have enough balance to do this transaction. Please take balance in your login.";
                    lblsucess.ForeColor = Color.Red;
                }
                else
                {
                    ReqBalance = 350;
                    deductamount();
                }
            }
            else if (ddlTimeDuration.SelectedItem.Text == "Two Year")
            {

                if (balance < 500)
                {
                    lblsucess.Text = "You don’t have enough balance to do this transaction. Please take balance in your login.";
                    lblsucess.ForeColor = Color.Red;
                }
                else
                {
                    ReqBalance = 500;
                    deductamount();
                }
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }  
    }
    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"]);
            }
            //ViewState["leftbalance"]=Label5.Text;
        }
        catch (Exception ex)
        {
            Server.Transfer("Error.aspx?id=" + ex );
            //string st = ex.Message;
        }
    }
    private void deductamount()
    {
        string  vardate=txtDOB2.Text.Trim()+"-"+ txtDOB.Text.Trim()+"-"+txtDOB3.Text.Trim();
        try
        {
            Random rand = new Random();
            rand.Next(0, 1);
            for (int i = 0; i <= 1; i++)
            {
                refrenceno = RandomString(rand, 12);
               
            }
            SqlParameter[] deductmoney = new SqlParameter[]
            {
                new SqlParameter("@TimeDuration",ddlTimeDuration.SelectedItem.Text),
                new SqlParameter("@Amount",ReqBalance),
                new SqlParameter("@LOGINID",Session["LOGINID"].ToString()),
                new SqlParameter("@profession",ddlSelectPerson.SelectedItem.Text.Trim()),
                new SqlParameter("@name",ddlInitial.SelectedItem.Text.Trim() + " " + txtFullName.Text.Trim()),
                new SqlParameter("@address",txtAddress.Text.Trim()),
                new SqlParameter("@state",ddlState.SelectedItem.Text.Trim()),
                new SqlParameter("@city",ddlCity.SelectedItem.Text.Trim()),
                new SqlParameter("@pin",Convert.ToString(txtPinCode.Text.Trim())),
                new SqlParameter("@phoneno",txtPhoneNo1.Text.Trim() + "" + txtPhoneNo2.Text.Trim()),
                new SqlParameter("@mobileno",txtMobileNo2.Text.Trim()),
                new SqlParameter("@dateofbirth",Convert.ToDateTime(vardate)),
                new SqlParameter("@emailid",txtEMailID.Text.Trim()),
                new SqlParameter("@panno",txtPanNo.Text.Trim()),
                new SqlParameter("@referenceno",refrenceno),
                new SqlParameter("@IPAddress",IPAddress),                
                new SqlParameter("@ResidencePf",ddlResidencePF.SelectedItem.Text),
                new SqlParameter("@ResidencePfNo",txt_ResidenceNO.Text),
                new SqlParameter("@ErrorMessage",SqlDbType.Int)
            };
            deductmoney[18].Direction = ParameterDirection.Output;
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_deductamount_digitalsignaturefinal", deductmoney);
            int result = Convert.ToInt32(deductmoney[18].Value);
            if (result == 1)
            {
                lblsucess.Text = "There is some technical problem .Please try again";
                lblsucess.ForeColor = Color.Red;
            }
            else
            {
                sendmail();
            }                       
        }
        catch (Exception ex)
        {
            //Server.Transfer("Error.aspx?id=" + ex + "");
            lblsucess.Text = "" + ex;
        }
    }
    private void sendmail()
    {
        if (txtEMailID.Text != "" && txtAddress.Text != "" && txtMobileNo1.Text != "" && txtMobileNo2.Text != "" && txtFullName.Text != "" && txtPanNo.Text != "" && txtPinCode.Text != "")
        {
            try
            {
                MailMessage message = new MailMessage();
                message.Body = mailmsg();
                message.IsBodyHtml = true;
                message.To.Add("shalendra.egen@gmail.com");
                message.Bcc.Add("admin@refillsindia.com");
                //message.To.Add("neeraj.egen@gmail.com");
                message.From = new System.Net.Mail.MailAddress(txtEMailID.Text.Trim());
                message.Subject = "Refills India DSC(Digital Signature) Application Form";
                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("services.refillsindia@gmail.com ", "services.refillsindia@gmail");
                    SmtpMail.Send(message);
                }
                message = null;
                lblsucess.Text = "You have successfully submitted Request for DSC.Ref.No. " + refrenceno;
                lblsucess.ForeColor = Color.Blue;
   
                CommonFunction.ClearControlValues(DigitalSignatureDiv);
            }
            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%>Digital Signature Form</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>DSC Period</b></td><td width=70% align=left>" +ddlTimeDuration.SelectedItem. Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20%><b>Email Id</b></td><td width=80%>" + Session["EMAILID"].ToString() + "</td></tr>");
        strHTML.Append("<tr><td width=20%><b>Login id</b></td><td width=80%>" + Session["LOGINID"].ToString() + "</td></tr>");
        strHTML.Append("<tr><td width=20%><b>User Type</b></td><td width=80%>" + Session["USERNAME"].ToString() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Profession</b></td><td width=70% align=left>" + ddlSelectPerson.SelectedItem.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Name</b></td><td width=70% align=left>" + ddlInitial.SelectedItem.Text.Trim() + " " + txtFullName.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Address</b></td><td width=70% align=left>" + txtAddress.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>State</b></td><td width=70% align=left>" + ddlState.SelectedItem.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>City</b></td><td width=70% align=left>" + ddlCity.SelectedItem.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Pin</b></td><td width=70% align=left>" + txtPinCode.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Phone No</b></td><td width=70% align=left>" + txtPhoneNo1.Text.Trim() + " " + txtPhoneNo2.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Mobile No.</b></td><td width=70% align=left>" + txtMobileNo2.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Pan No.</b></td><td width=70% align=left>" + txtPanNo.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>DOB</b></td><td width=70% align=left>" + txtDOB.Text.Trim() + ""+txtDOB2.Text.Trim()+""+txtDOB3.Text.Trim()+"</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Email Id</b></td><td width=70% align=left>" + txtEMailID.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Residence Proof</b></td><td width=70% align=left>" +ddlResidencePF.SelectedItem.Text.Trim() + "</td></tr>");
        strHTML.Append("<tr><td width=20% align=left>Residence Proof Number</b></td><td width=70% align=left>" +txt_ResidenceNO.Text.Trim() + "</td></tr>");
        strHTML.Append("</table>");
        return strHTML.ToString();
    }
    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();
    }
    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            BindDropdown("select * from DistrictName where StateID='" + ddlState.SelectedValue + "'", ddlCity, "CityId", "CityName", null, null);
            //BindDropdown("select * from DistrictName where StateID='" + ddl_State_OA.SelectedValue + "'", ddl_Distric_OA, "CityId", "CityName", null, null);
        }
        catch (Exception ex)
        {
            throw (ex);
        }  
    }
}
