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

namespace Percent___Qualification_work.Classes
{
    public class databaseConnection
    {
        // Class-level variables
        private MySqlConnection connection;
        private string connectionString;

        // Constructor
        public databaseConnection()
        {
            // Retrieve the connection string from the configuration file
            connectionString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
            connection = new MySqlConnection(connectionString);
        }

        // Open the database connection
        public bool openConnection()
        {
            try
            {
                connection.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Connection error: " + ex.Message);
                return false;
            }
        }

        // Close the database connection
        public bool closeConnection()
        {
            try
            {
                connection.Close();
                return true;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Closing connection error: " + ex.Message);
                return false;
            }
        }

        // Execute a query and return the result as a DataTable
        public DataTable ExecuteQuery(string query)
        {
            DataTable dataTable = new DataTable();

            try
            {
                if (openConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                    adapter.Fill(dataTable);
                    closeConnection();
                }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Query error: " + ex.Message);
            }

            return dataTable;
        }

        // Add a new user to the database
        public bool AddUser(string username, string hashedPassword)
        {
            string query = "INSERT INTO users (username, password) VALUES (@username, @password)";

            try
            {
                if (openConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    cmd.Parameters.AddWithValue("@username", username);
                    cmd.Parameters.AddWithValue("@password", hashedPassword);
                    cmd.ExecuteNonQuery();
                    closeConnection();
                    return true;
                }
                return false;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Database error: " + ex.Message);
                return false;
            }
        }

        // Add a new plan to the database
        public bool addPlan(int userID, string name, string date, int priority)
        {
            string query = "INSERT INTO plans (user_id, name, date, priority) VALUES (@userID, @name, @date, @priority)";

            try
            {
                if (openConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    cmd.Parameters.AddWithValue("@userID", userID);
                    cmd.Parameters.AddWithValue("@name", name);
                    cmd.Parameters.AddWithValue("@date", date);
                    cmd.Parameters.AddWithValue("@priority", priority);
                    cmd.ExecuteNonQuery();
                    closeConnection();
                    return true;
                }
                return false;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Database error: " + ex.Message);
                return false;
            }
        }

        // Get the hashed password for a user
        public string GetPasswordForUser(string username)
        {
            string query = "SELECT password FROM users WHERE username = @username";

            try
            {
                if (openConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    cmd.Parameters.AddWithValue("@username", username);
                    MySqlDataReader reader = cmd.ExecuteReader();

                    if (reader.Read())
                    {
                        string hashedPassword = reader["password"].ToString();
                        closeConnection();
                        return hashedPassword;
                    }
                    closeConnection();
                    return null;
                }
                return null;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Query error: " + ex.Message);
                return null;
            }
        }

        // Check if a username is already taken
        public bool IsUsernameTaken(string username)
        {
            string query = "SELECT COUNT(*) FROM users WHERE username = @username";

            try
            {
                if (openConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    cmd.Parameters.AddWithValue("@username", username);
                    int userCount = Convert.ToInt32(cmd.ExecuteScalar());
                    closeConnection();
                    return userCount > 0;
                }
                return false;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Query error: " + ex.Message);
                return false;
            }
        }

        // Get the user ID for a username
        public int getUserID(string username)
        {
            string query = "SELECT id FROM users WHERE username = @username";

            try
            {
                if (openConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    cmd.Parameters.AddWithValue("@username", username);
                    int id = Convert.ToInt32(cmd.ExecuteScalar());
                    closeConnection();
                    return id;
                }
                return 0;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Query error: " + ex.Message);
                return 0;
            }
        }

        // Get plans for a user, ordered by the specified column
        public DataTable getPlans(int userID, string order)
        {
            DataTable plans = new DataTable();
            string query = $"SELECT id, name, date, priority FROM plans WHERE user_id = @userID ORDER BY {order} DESC";

            if (order == "date") query = $"SELECT id, name, date, priority FROM plans WHERE user_id = @userID ORDER BY {order}";

            try
            {
                if (openConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    cmd.Parameters.AddWithValue("@userID", userID);
                    MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                    adapter.Fill(plans);  // Fill the DataTable with the query result
                    closeConnection();
                }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Query error: " + ex.Message);
            }

            return plans;
        }

        // Get a plan by its ID
        public DataTable getPlanByID(int planID)
        {
            DataTable plan = new DataTable();
            string query = "SELECT * FROM plans WHERE id = @planID";

            try
            {
                if (openConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    cmd.Parameters.AddWithValue("@planID", planID);
                    MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                    adapter.Fill(plan);  // Fill the DataTable with the query result
                    closeConnection();
                }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Query error: " + ex.Message);
            }

            return plan;
        }

        // Update a plan's details
        public void updatePlan(int planID, string name, string date, int priority)
        {
            string query = "UPDATE plans SET name = @name, date = @date, priority = @priority WHERE id = @planID";

            try
            {
                if (openConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    cmd.Parameters.AddWithValue("@planID", planID);
                    cmd.Parameters.AddWithValue("@name", name);
                    cmd.Parameters.AddWithValue("@date", date);
                    cmd.Parameters.AddWithValue("@priority", priority);
                    cmd.ExecuteNonQuery();
                    closeConnection();
                }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Query error: " + ex.Message);
            }
        }

        // Delete a plan from the database
        public void deletePlan(int planID)
        {
            string query = "DELETE FROM plans WHERE id = @planID";

            try
            {
                if (openConnection())
                {
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    cmd.Parameters.AddWithValue("@planID", planID);
                    cmd.ExecuteNonQuery();
                    closeConnection();
                }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("Query error: " + ex.Message);
            }
        }
    }
}
