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_modify_employee : Form
    {

        int editingId = -1;
        bool isEditing => editingId >= 0;
        Dictionary<string, string> departmentIdDic = new Dictionary<string, string>();
        public form_modify_employee(int _editingId = -1)
        {
            InitializeComponent();
            editingId = _editingId;
        }

        private void form_modify_employee_Load(object sender, EventArgs e)
        {
            using(SqlConnection con = new SqlConnection(Helpers.conString))
            {
                con.Open();
                using(SqlCommand cmd = new SqlCommand("SELECT * FROM Departments",con))
                {
                    using(SqlDataReader reader = cmd.ExecuteReader())
                    {
                        departmentIdDic.Clear();
                        combo_department.Items.Clear();
                        while (reader.Read()) {
                            departmentIdDic.Add(reader["Name"].ToString(), reader["ID"].ToString());
                            combo_department.Items.Add(reader["Name"].ToString());
                        }
                        if (combo_department.Items.Count > 0) { combo_department.SelectedIndex = 0; }
                    }
                }

                if (isEditing)
                {
                    using(SqlCommand cmd = new SqlCommand("SELECT * FROM Employees WHERE ID=@id",con))
                    {
                        cmd.Parameters.AddWithValue("@id", editingId);

                        using(SqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                txtName.Text = reader["Name"].ToString();
                                txtAllowance.Text = reader["Allowance"].ToString();

                                string depId = reader["Department_ID"].ToString();
                                foreach(KeyValuePair<string,string> department in departmentIdDic)
                                {
                                    if(department.Value == depId)
                                    {
                                        for(int i=0; i < combo_department.Items.Count; i++)
                                        {
                                            if(combo_department.Items[i].ToString() == depId)
                                            {
                                                combo_department.SelectedIndex =i;
                                            }
                                        }
                                        break;
                                    }
                                }

                                date_joined.Value = DateTime.Parse(reader["Joined_Date"].ToString());
                            }
                        }
                    }
                }

                con.Close();
            }

            this.Text = isEditing ? "Edit Employee Data" : "Add new Employee";
            btnAdd.Text = isEditing ? "Edit" : "Add";

            if (!isEditing)
            {
                date_joined.Value = DateTime.Now;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //Validate the inputs
            if(txtName.Text.Length <= 2) { MessageBox.Show("Please enter a name longer than 2 letters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }
            try
            {
                int allowance = Convert.ToInt32(txtAllowance.Text);
            }
            catch
            {
                MessageBox.Show("Enter a valid input on the allowance", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return;
            }


            using (SqlConnection connection = new SqlConnection(Helpers.conString))
            {
                string query = "INSERT INTO Employees (Name, Department_ID, Allowance, Joined_Date) VALUES(@name, @depId, @allowance, @joinedDate)";
                if (isEditing)
                {
                    query = "UPDATE Employees SET Name=@name, Department_ID=@depId, Allowance=@allowance, Joined_Date=@joinedDate WHERE ID=@id";
                }
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    if (isEditing)
                    {
                        command.Parameters.AddWithValue("@id", editingId);
                    }
                    command.Parameters.AddWithValue("@name", txtName.Text);
                    command.Parameters.AddWithValue("@depId", departmentIdDic[combo_department.SelectedItem.ToString()]);
                    command.Parameters.AddWithValue("@allowance", txtAllowance.Text);
                    command.Parameters.AddWithValue("@joinedDate", date_joined.Value);

                    connection.Open();
                    int result = command.ExecuteNonQuery();
                    connection.Close();

                    if (result < 0)
                    {
                        MessageBox.Show($"There was an error {(isEditing ? "editing" : "adding new")} employee", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }

            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
