using MySql.Data.MySqlClient;
using System;
using System.Windows.Forms;


namespace programming_ii__lesson_2_
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            refreshlist();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 obj2 = new Form2();
            obj2.RefToForm1 = this;
            this.Hide();
            obj2.Show();
            
            

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            var senderGrid = (DataGridView)sender;
            int columnIndex = dataGridView1.CurrentCell.ColumnIndex;
            string columnName = dataGridView1.Columns[columnIndex].HeaderText;

            if (columnName == "Edit" && e.RowIndex >= 0)
            {
                int myid = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());

                Form3 obj3 = new Form3(myid);
                obj3.RefToForm1 = this;
                this.Hide();
                obj3.Show();
            }



            if (columnName == "Delete" && e.RowIndex >= 0)
            {
                int myid = int.Parse(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
                if (MessageBox.Show(string.Format($"Do you want to delete Customer ID: {myid}?"), "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    var myConnection = dbconnect.myConnection;
                    myConnection.Open();
                    string sqlQuery = null;

                    sqlQuery = $"DELETE FROM employees WHERE id = {myid}";
                    MySqlCommand cmd = new MySqlCommand(sqlQuery, myConnection);
                    cmd.ExecuteNonQuery();
                    myConnection.Close();
                    dataGridView1.Rows.Clear();
                    refreshlist();

                }

            }
        }

        public void refreshlist()
        {
            var myConnection = dbconnect.myConnection;
            myConnection.Open();
            string sqlQuery = null;
            dataGridView1.Rows.Clear();

            sqlQuery = "Select * from employees";
            MySqlCommand cmd = new MySqlCommand(sqlQuery, myConnection);
            MySqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {

                dataGridView1.Rows.Add(rdr["id"], rdr["name"], rdr["surname"], rdr["afm"], Convert.ToDateTime(rdr["birth_date"]).ToString("dd-MM-yyyy"), rdr["payroll"]);
            }
            myConnection.Close();
        }

        private void dataGridView1_VisibleChanged(object sender, EventArgs e)
        {
            refreshlist();
        }
    }
}
