using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.Net;
using System.Net.Mail;
using CLS_BL;
using CLS_DL;
using CLS_PL;
using System.Security.Cryptography;



namespace SUNWEB
{
    public partial class ForgetPasswords : System.Web.UI.Page
    {

        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        BL_USER ObjUserBL = new BL_USER(); //This Object for All User and Page Related fuctions included 
        PLCUSTOMER ObjCustPL = new PLCUSTOMER();
        Int32 K = 0;
        Int32 L = 0;
        Int32 S = 0;
        string connectionstring = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        DateTime MonthstartDt;
        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        string REmail;
        string RPass, NewPass;
        string UserPassword = string.Empty;
        string userid = string.Empty;


        protected void Page_Load(object sender, EventArgs e)
        {

        }



        protected void btnSend_Click(object sender, EventArgs e)
        {

            string Get_Cm_ID = string.Empty;
            DataTable DtMailResult = new DataTable();
            string Query = "SELECT MailId,Password FROM  portaldb.MAILMASTER WHERE id=1";
            DtMailResult = ObjCloudMain.GetData_DT(Query);

            if (DtMailResult.Rows.Count > 0)
            {

                REmail = DtMailResult.Rows[0]["MAILID"].ToString();
                RPass = DtMailResult.Rows[0]["PASSWORD"].ToString();
            }


            // SQL Injection Prevention : 29-09-21  

            using (MySqlConnection con = new MySqlConnection(connectionstring))
            {

                try
                {
                    string command = "select cm_id from  portaldb.usermaster  where username=@username;";
                    MySqlCommand cmd = new MySqlCommand(command, con);
                    cmd.Parameters.AddWithValue("@username", txtUserid.Text.ToString().Trim());
                    con.Open();
                    Get_Cm_ID = Convert.ToString(cmd.ExecuteScalar());



                }
                catch (Exception ex)
                {
                    BL_ErrorLog bL_Error = new BL_ErrorLog();
                    bL_Error.Write(ex);
                }
                finally
                {
                    con.Close();
                    con.Dispose();
                }



            }
            // Existing Code   
            //string Get_Cm_ID = ObjCloudMain.ExecuteScalar("select cm_id from  portaldb.usermaster  where username='" + Microsoft.Security.Application.Encoder.HtmlEncode(txtUserid.Text.ToString().Trim()) + "';");

            string toAddress = ObjCloudMain.ExecuteScalar("select cm_email from  portaldb.companymaster where cm_id= " + Get_Cm_ID + " ;");

            if (txtEmaild.Text.ToString().Trim() == toAddress)
            {


                string from = REmail;
                string subject = "testx";
                string body = " testcx";
                string Mob = string.Empty;

                using (MailMessage mm = new MailMessage(from, toAddress))
                {

                    // SQL Injection Prevention : 29-09-21  
                    // Parameterized Approach 


                    // Getting UserPassword 
                    using (MySqlConnection con = new MySqlConnection(connectionstring))
                    {

                        try
                        {
                            string command = "select Password from  portaldb.usermaster  where username=@username;";
                            MySqlCommand cmd = new MySqlCommand(command, con);
                            cmd.Parameters.AddWithValue("@username", txtUserid.Text.ToString().Trim());
                            con.Open();
                            UserPassword = Convert.ToString(cmd.ExecuteScalar());



                        }
                        catch (Exception ex)
                        {
                            BL_ErrorLog bL_Error = new BL_ErrorLog();
                            bL_Error.Write(ex);
                        }
                        finally
                        {
                            con.Close();
                            con.Dispose();
                        }

                    }
                    // Getting  userid
                    using (MySqlConnection con = new MySqlConnection(connectionstring))
                    {

                        try
                        {
                            string command = "select userid from  portaldb.usermaster  where username=@username;";
                            MySqlCommand cmd = new MySqlCommand(command, con);
                            cmd.Parameters.AddWithValue("@username", txtUserid.Text.ToString().Trim());
                            con.Open();
                            userid = Convert.ToString(cmd.ExecuteScalar());



                        }
                        catch (Exception ex)
                        {
                            BL_ErrorLog bL_Error = new BL_ErrorLog();
                            bL_Error.Write(ex);
                        }
                        finally
                        {
                            con.Close();
                            con.Dispose();
                        }


                    }



                    // Exiting Code 
                    //UserPassword = ObjCloudMain.ExecuteScalar("select Password from portaldb.usermaster  where username='" + Microsoft.Security.Application.Encoder.HtmlEncode(txtUserid.Text.ToString().Trim()) + "'");
                    // userid = ObjCloudMain.ExecuteScalar("select userid from portaldb.usermaster  where username='" + Microsoft.Security.Application.Encoder.HtmlEncode(txtUserid.Text.ToString().Trim()) + "'");


                    MailMessage Msg = new MailMessage();
                    Msg.From = new MailAddress("suntoyocloud@suntoyo.com.sg", "Suntoyo Cloud");
                    Msg.To.Add(txtEmaild.Text.ToString().Trim());
                    Msg.Subject = "Suntoyo Password  Recovery";



                    //Cloud Baseurl 
                    string Baseurl = "https://www.suntoyocloud.com/PasswordReset.aspx";
                    //Local Baseurl 
                    // string Baseurl = "http://localhost:57386/PasswordReset.aspx";
                    string Userid = HttpUtility.UrlEncode(Encrypt(userid.ToString().Trim()));
                    string cm_idd = HttpUtility.UrlEncode(Encrypt(Get_Cm_ID.ToString().Trim()));
                    string Resetlink = string.Format("" + Baseurl + "?userid={0}&Cm_id={1}", Userid, cm_idd);

                    StringBuilder sb = new StringBuilder();
                    sb.Append("We received your request to reset your Suntoyo cloud portal password");
                    sb.Append(Environment.NewLine);
                    sb.Append("To reset your  password, please click the following link :");
                    sb.Append(Environment.NewLine);
                    sb.Append(Resetlink);
                    sb.Append(Environment.NewLine);
                    sb.Append("If you did not initiate this request, you may safely ignore this message. The request will expire shortly.");

                    Msg.Body = "" + sb + "";

                    SmtpClient client = new SmtpClient();
                    client.Host = "mail.suntoyo.com.sg";
                    client.Port = 25;
                    client.Credentials = new NetworkCredential(REmail, RPass);
                    client.Send(Msg);
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' An email has been sent to " + Microsoft.Security.Application.Encoder.HtmlEncode(txtEmaild.Text.ToString().Trim()) + " with instructions for resetting your password.\\n\\ This email may take a few minutes to arrive in your inbox.');location.href='Login.aspx'", true);

                }



            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Emailid is  wrong with our Records ');", true);
            }



        }


        // Encrypt Function 
        private string Encrypt(string clearText)
        {
            string EncryptionKey = "MAKV2SPBNI9921205";
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return clearText;
        }


        // Decrypt Function
        private string Decrypt(string cipherText)
        {
            string EncryptionKey = "MAKV2SPBNI9921205";
            cipherText = cipherText.Replace(" ", "+");
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }






    }
}