using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Security.Cryptography;
namespace Project_management_system
{
    public partial class EmployeeDetails : Form
    {
        
        
        DataTable dtable = new DataTable();

        SqlDataReader rdr = null;
        SqlConnection con = null;
        SqlCommand cmd = null;
        ConnectionString cs = new ConnectionString();
        SqlDataAdapter adp;
        DataSet ds;
        clsFunc cf = new clsFunc();
        string st1;
        string st2;
        public EmployeeDetails()
        {
            InitializeComponent();
        }
        public static string GetUniqueKey(int maxSize)
        {
            char[] chars = new char[62];
            chars = "123456789".ToCharArray();
            byte[] data = new byte[1];
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            data = new byte[maxSize];
            crypto.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder(maxSize);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < 26; i++)
            {
                Years.Items.Add(i);
            }
            for (int j = 0; j <= 11; j++)
            {
                Months.Items.Add(j);
            }
            FillDepartment();
            FillDesignation();

        }

        private void Browse_Click(object sender, EventArgs e)
        {
            try
            {
                var _with1 = openFileDialog1;

                _with1.Filter = ("Image Files |*.png; *.bmp; *.jpg;*.jpeg; *.gif;");
                _with1.FilterIndex = 4;
                //Reset the file name
                openFileDialog1.FileName = "";

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void NewRecord_Click(object sender, EventArgs e)
        {
            Reset();
        }

        private void Save_Click(object sender, EventArgs e)
        {

            if (txtEmployeeName.Text == "")
            {
                MessageBox.Show("Please select Employee", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmployeeName.Focus();
                return;
            }
            if (fatherName.Text == "")
            {
                MessageBox.Show("Please select fatherName", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                fatherName.Focus();
                return;
            }
            if (City.Text == "")
            {
                MessageBox.Show("Please select City", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                City.Focus();
                return;
            }
            if (ContactNo.Text == "")
            {
                MessageBox.Show("Please select ContactNo", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ContactNo.Focus();
                return;
            }
            if (Designation.Text == "")
            {
                MessageBox.Show("Please select Designation", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Designation.Focus();
                return;
            }
            if (cmbDepartment.Text == "")
            {
                MessageBox.Show("Please select Department", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbDepartment.Focus();
                return;
            }




            try
            {
                ID.Text = "E-" + GetUniqueKey(6);
                con = new SqlConnection(cs.ConDB);
                con.Open();
                string cb = "insert into Employee(Id, Name, FatherName, City, Address, ContactNo, Email_Id, Designation, Department, Bloodgroup, DateOfJoining, Dob, Experience_Years,Experience_Months, PastExperienceDetails, Photo) VALUES ('" + ID.Text + "','" + txtEmployeeName.Text + "','" + fatherName.Text + "','" + City.Text + "','" + Address.Text + "','" + ContactNo.Text + "','" + EmailId.Text + "','" + Designation.Text + "','" + cmbDepartment.Text + "','" + BloodGroup.Text + "','" + joiningDate.Value.Date + "','" + DOB.Text + "'," + Years.Text + "," + Months.Text + ",'" + PastExperience.Text + "',@d1)";
                cmd = new SqlCommand(cb);
                cmd.Connection = con;
                MemoryStream ms = new MemoryStream();
                Bitmap bmpImage = new Bitmap(pictureBox1.Image);
                bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] data = ms.GetBuffer();
                SqlParameter p = new SqlParameter("@d1", SqlDbType.Image);
                p.Value = data;
                cmd.Parameters.Add(p);
                cmd.ExecuteNonQuery();
                con.Close();
                st1 = lblUser.Text;
                st2 = "added the new Employee '" +txtEmployeeName.Text + "'";
                cf.LogFunc(st1, System.DateTime.Now, st2);
                MessageBox.Show("Successfully saved", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
               
                Save.Enabled = false;
               // Print.Enabled = true;
                FillDepartment();
                FillDesignation();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void Reset()
        {
            ID.Text = "";
            BloodGroup.SelectedIndex = -1;
            txtEmployeeName.Text = "";
            fatherName.Text = "";
            City.Text = "";
            Address.Text = "";
            ContactNo.Text = "";
            EmailId.Text = "";
            Designation.Text = "";
            cmbDepartment.Text = "";
            joiningDate.Text = System.DateTime.Today.ToString();
            DOB.Text = System.DateTime.Today.ToString();
            Years.Text = "";
            Months.Text = "";
            PastExperience.Text = "";
            Delete.Enabled = false;
            btnUpdate.Enabled = false;
            Save.Enabled = true;
            pictureBox1.Image = null;
           // Print.Enabled = false;
            pictureBox1.Image = Properties.Resources.photo;
            txtEmployeeName.Focus();
        }


        private void ContactNo_Validating(object sender, CancelEventArgs e)
        {
            if (ContactNo.TextLength < 10)
            {
                MessageBox.Show("Contact no. must contains 10 digits", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ContactNo.Focus();
            }
            if (ContactNo.TextLength > 15)
            {
                MessageBox.Show("less than 15 digits are allowed", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ContactNo.Focus();
            }
        }

        private void ContactNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void EmailId_Validating(object sender, CancelEventArgs e)
        {
            System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
            if (EmailId.Text.Length > 0)
            {
                if (!rEMail.IsMatch(EmailId.Text))
                {
                    MessageBox.Show("invalid email address", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    EmailId.SelectAll();
                    e.Cancel = true;
                }
            }
        }

        private void Delete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you really want to delete this record?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                delete_records();
            }
        }
        private void delete_records()
        {

            try
            {

                int RowsAffected = 0;
          
                con = new SqlConnection(cs.ConDB);

                con.Open();
                string ct = "select EmployeeID_PM from projectinfo where EmployeeID_PM=@find";


                cmd = new SqlCommand(ct);

                cmd.Connection = con;
                cmd.Parameters.Add(new SqlParameter("@find", System.Data.SqlDbType.NChar, 10, "EmployeeID_PM"));


                cmd.Parameters["@find"].Value = ID.Text;


                rdr = cmd.ExecuteReader();

                if (rdr.Read())
                {
                    MessageBox.Show("Unable to delete...This Employee Already use As a Project Manager in Project Management Records form", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Reset();


                    if ((rdr != null))
                    {
                        rdr.Close();
                    }
                    return;
                }
                con = new SqlConnection(cs.ConDB);
                con.Open();
                string cq = "delete from Employee where ID='" + ID.Text + "'";
                cmd = new SqlCommand(cq);
                cmd.Connection = con;
                RowsAffected = cmd.ExecuteNonQuery();
                if (RowsAffected > 0)
                {
                    st1 = lblUser.Text;
                    st2 = "Deleted the Employee '" + txtEmployeeName.Text + "'";
                    cf.LogFunc(st1, System.DateTime.Now, st2);
                    MessageBox.Show("Successfully deleted", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Reset();
                    FillDepartment();
                    FillDesignation();
                }
                else
                {
                    MessageBox.Show("No Record found", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Reset();
                }
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                con = new SqlConnection(cs.ConDB);
                con.Open();
       

                string cb = "update Employee set Name='" + txtEmployeeName.Text + "',FatherName='"+fatherName.Text+"',ContactNo='"+ContactNo.Text+"',City='" + City.Text + "',Address='"+Address.Text+"',Email_id='"+EmailId.Text+"',Designation='" + Designation.Text + "',Department='" + cmbDepartment.Text + "',Bloodgroup='" + BloodGroup.Text + "',DateOfJoining='" + joiningDate.Value.Date + "',Dob='" + DOB.Text + "',Experience_years=" + Years.Text + ",Experience_months=" + Months.Text + ",PastExperienceDetails='" + PastExperience.Text + "',Photo=@d1 Where ID='" + ID.Text + "'";
                cmd = new SqlCommand(cb);
                cmd = new SqlCommand(cb);
                cmd.Connection = con;
                MemoryStream ms = new MemoryStream();
                Bitmap bmpImage = new Bitmap(pictureBox1.Image);
                bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] data = ms.GetBuffer();
                SqlParameter p = new SqlParameter("@d1", SqlDbType.Image);   
                p.Value = data;
                cmd.Parameters.Add(p);
                cmd.ExecuteNonQuery();
                con.Close();
                FillDepartment();
                FillDesignation();
                st1 = lblUser.Text;
                st2 = "Updated the Employee '" + txtEmployeeName.Text + "'";
                cf.LogFunc(st1, System.DateTime.Now, st2);
                MessageBox.Show("Successfully updated", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
                btnUpdate.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button2_Click(object sender, EventArgs e)                 
        {
            this.Hide(); 
            EmployeeRecord frm = new EmployeeRecord();
            frm.lblUser.Text = lblUser.Text;
            frm.Show();
        }

        public void FillDepartment()
        {

            try
            {
                con = new SqlConnection(cs.ConDB);
                con.Open();
                adp = new SqlDataAdapter();
                adp.SelectCommand = new SqlCommand("SELECT distinct RTRIM(Department) FROM Employee", con);
                ds = new DataSet("ds");
                adp.Fill(ds);
                dtable = ds.Tables[0];
                cmbDepartment.Items.Clear();
                foreach (DataRow drow in dtable.Rows)
                {
                    cmbDepartment.Items.Add(drow[0].ToString());

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
            public void FillDesignation()
        {

            try
            {
                con = new SqlConnection(cs.ConDB);
                con.Open();
                adp = new SqlDataAdapter();
                adp.SelectCommand = new SqlCommand("SELECT distinct RTRIM(Designation) FROM Employee", con);
                ds = new DataSet("ds");
                adp.Fill(ds);
                dtable = ds.Tables[0];
                Designation.Items.Clear();
                foreach (DataRow drow in dtable.Rows)
                {
                    Designation.Items.Add(drow[0].ToString());

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

           
    }
        }
        

     
    
    
