using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PayrollSystem
{
    public partial class form_departments : Form
    {
        form_main mainForm;

        public form_departments(form_main main)
        {
            InitializeComponent();
            mainForm= main;
        }

        private void form_departments_Load(object sender, EventArgs e)
        {
            Search();
            RefreshUI();
        }


        void Search()
        {
            string query = @"
            SELECT 
            Departments.ID,
            Departments.Name,
            Departments.Basic,
            COUNT(Employees.ID) AS EmployeeCount
        FROM 
            Departments
        LEFT JOIN 
            Employees ON Departments.ID = Employees.Department_ID
        GROUP BY 
            Departments.ID, Departments.Name, Departments.Basic;
        ";

            using (SqlConnection con = new SqlConnection(Helpers.conString))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand(query, con)) {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        list_departments.Items.Clear();
                        while (reader.Read()) {
                            ListViewItem newItem = new ListViewItem(reader["ID"].ToString());
                            newItem.SubItems.Add(reader["Name"].ToString());
                            newItem.SubItems.Add(reader["Basic"].ToString());
                            newItem.SubItems.Add(reader["EmployeeCount"].ToString());

                            list_departments.Items.Add(newItem);
                        }
                    }

                }
                con.Close();
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            form_modify_department addForm = new form_modify_department();
            addForm.ShowDialog();

            Search();
        }

        private void btnShowEmployees_Click(object sender, EventArgs e)
        {
            RefreshUI();
            if (!isSelectedItem) { return; }

            mainForm.ShowEmployeesOnDepartment(list_departments.SelectedItems[0].SubItems[1].Text);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            RefreshUI();
            if (!isSelectedItem) { return; }

            form_modify_department editForm = new form_modify_department(int.Parse(list_departments.SelectedItems[0].Text));
            editForm.ShowDialog();

            Search();
        }
        bool isSelectedItem => list_departments.SelectedItems.Count > 0;
        void RefreshUI()
        {
            btnEdit.Enabled = btnRemove.Enabled = btnShowEmployees.Enabled = isSelectedItem;
        }

        private void list_departments_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshUI();
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            RefreshUI();
            if (!isSelectedItem) { return; }
            
            string selectedID = list_departments.SelectedItems[0].Text;

            DialogResult confirmation = MessageBox.Show("Are you sure to remove this department? This will cause all the employees in this department to be removed!", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirmation == DialogResult.Yes)
            {
                List<string> affectedEmployees = new List<string>();
                using (SqlConnection con = new SqlConnection(Helpers.conString))
                {
                    con.Open();
                    using (SqlCommand cmd = new SqlCommand("SELECT Name FROM Employees WHERE Department_ID=@id", con)) {
                        cmd.Parameters.AddWithValue("@id", selectedID);
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read()) {
                                affectedEmployees.Add(reader["Name"].ToString());
                            }
                        }
                    }

                    string msg = "These are the list of employees that will be removed with this operation\n";
                    foreach (string employee in affectedEmployees)
                    {
                        msg += $"\n{employee}";
                    }

                    DialogResult finalConfirmation = MessageBox.Show(msg, "Are you still sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (finalConfirmation == DialogResult.Yes)
                    {
                        using (SqlCommand cmd = new SqlCommand("DELETE FROM Employees WHERE Department_ID=@id", con))
                        {
                            cmd.Parameters.AddWithValue("@id", selectedID);

                            int result = cmd.ExecuteNonQuery();
                        }

                        using (SqlCommand cmd = new SqlCommand("DELETE FROM Departments WHERE ID=@id", con))
                        {
                            cmd.Parameters.AddWithValue("@id", selectedID);

                            int result = cmd.ExecuteNonQuery();
                        }
                    }
                    con.Close();
                }

                Search();
            }
        }
    }
}
