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

namespace WindowsFormsApp2
{
    public partial class OrderEditForm : Form
    {
        string connectionString;
        int? orderId;

        public OrderEditForm(string connStr, int? id)
        {
            connectionString = connStr;
            orderId = id;
            InitializeComponent();
            LoadUsers();
            LoadStatuses();
            LoadProducts();
            if (orderId.HasValue)
            {
                LoadOrderData();
            }
            buttonSave.Click += ButtonSave_Click;
            buttonAddItem.Click += ButtonAddItem_Click;
            buttonRemoveItem.Click += ButtonRemoveItem_Click;
        }

        void LoadUsers()
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT id, full_name FROM users", conn);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                comboBoxUser.DisplayMember = "full_name";
                comboBoxUser.ValueMember = "id";
                comboBoxUser.DataSource = dt;
            }
        }

        void LoadStatuses()
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT idstatus, name FROM status", conn);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                comboBoxStatus.DisplayMember = "name";
                comboBoxStatus.ValueMember = "idstatus";
                comboBoxStatus.DataSource = dt;
            }
        }

        void LoadProducts()
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT id, name, sku FROM products", conn);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                comboBoxProduct.DisplayMember = "name";
                comboBoxProduct.ValueMember = "id";
                comboBoxProduct.DataSource = dt;
            }
        }

        void LoadOrderData()
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                string query = "SELECT order_number, user_id, status, pickup_address, order_date, delivery_date FROM orders WHERE id = @id";
                MySqlCommand cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", orderId.Value);
                MySqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    textBoxOrderNumber.Text = reader["order_number"].ToString();
                    comboBoxUser.SelectedValue = reader["user_id"];
                    comboBoxStatus.SelectedValue = reader["status"];
                    textBoxAddress.Text = reader["pickup_address"].ToString();
                    dateTimePickerOrder.Value = Convert.ToDateTime(reader["order_date"]);

                    if (reader["delivery_date"] != DBNull.Value)
                    {
                        dateTimePickerDelivery.Value = Convert.ToDateTime(reader["delivery_date"]);
                        dateTimePickerDelivery.Checked = true;
                    }
                    else
                    {
                        dateTimePickerDelivery.Checked = false;
                    }
                }
                reader.Close();

                string itemsQuery = "SELECT p.id as product_id, p.name as product_name, oi.quantity FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.order_id = @id";
                MySqlCommand itemsCmd = new MySqlCommand(itemsQuery, conn);
                itemsCmd.Parameters.AddWithValue("@id", orderId.Value);
                MySqlDataAdapter adapter = new MySqlDataAdapter(itemsCmd);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                dataGridViewItems.DataSource = dt;
            }
        }

        void ButtonSave_Click(object sender, EventArgs e)
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                if (orderId.HasValue)
                {
                    string query = "UPDATE orders SET order_number = @num, user_id = @uid, status = @sid, pickup_address = @addr, order_date = @odate, delivery_date = @ddate WHERE id = @id";
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    cmd.Parameters.AddWithValue("@num", textBoxOrderNumber.Text);
                    cmd.Parameters.AddWithValue("@uid", comboBoxUser.SelectedValue);
                    cmd.Parameters.AddWithValue("@sid", comboBoxStatus.SelectedValue);
                    cmd.Parameters.AddWithValue("@addr", textBoxAddress.Text);
                    cmd.Parameters.AddWithValue("@odate", dateTimePickerOrder.Value.Date);
                    cmd.Parameters.AddWithValue("@ddate", dateTimePickerDelivery.ValueOrNull());
                    cmd.Parameters.AddWithValue("@id", orderId.Value);
                    cmd.ExecuteNonQuery();
                }
                else
                {
                    string query = "INSERT INTO orders (order_number, user_id, status, pickup_address, order_date, delivery_date) VALUES (@num, @uid, @sid, @addr, @odate, @ddate)";
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    cmd.Parameters.AddWithValue("@num", textBoxOrderNumber.Text);
                    cmd.Parameters.AddWithValue("@uid", comboBoxUser.SelectedValue);
                    cmd.Parameters.AddWithValue("@sid", comboBoxStatus.SelectedValue);
                    cmd.Parameters.AddWithValue("@addr", textBoxAddress.Text);
                    cmd.Parameters.AddWithValue("@odate", dateTimePickerOrder.Value.Date);
                    cmd.Parameters.AddWithValue("@ddate", dateTimePickerDelivery.ValueOrNull());
                    cmd.ExecuteNonQuery();
                    orderId = (int)cmd.LastInsertedId;
                }
                SaveOrderItems();
            }
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        void SaveOrderItems()
        {
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                MySqlCommand deleteCmd = new MySqlCommand("DELETE FROM order_items WHERE order_id = @id", conn);
                deleteCmd.Parameters.AddWithValue("@id", orderId.Value);
                deleteCmd.ExecuteNonQuery();

                foreach (DataGridViewRow row in dataGridViewItems.Rows)
                {
                    if (row.IsNewRow) continue;

                    if (row.Cells[0].Value != null && row.Cells[0].Value != DBNull.Value)
                    {
                        string query = "INSERT INTO order_items (order_id, product_id, quantity) VALUES (@oid, @pid, @qty)";
                        MySqlCommand cmd = new MySqlCommand(query, conn);
                        cmd.Parameters.AddWithValue("@oid", orderId.Value);
                        cmd.Parameters.AddWithValue("@pid", row.Cells[0].Value);
                        cmd.Parameters.AddWithValue("@qty", row.Cells[2].Value);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }

        void ButtonAddItem_Click(object sender, EventArgs e)
        {
            if (comboBoxProduct.SelectedValue != null && numericUpDownQty.Value > 0)
            {
                int productId = Convert.ToInt32(comboBoxProduct.SelectedValue);
                string productName = comboBoxProduct.Text;
                int qty = (int)numericUpDownQty.Value;
                dataGridViewItems.Rows.Add(productId, productName, qty);
            }
        }

        void ButtonRemoveItem_Click(object sender, EventArgs e)
        {
            if (dataGridViewItems.SelectedRows.Count > 0)
            {
                dataGridViewItems.Rows.RemoveAt(dataGridViewItems.SelectedRows[0].Index);
            }
        }
    }

    public static class DateTimeExtensions
    {
        public static object ValueOrNull(this DateTimePicker picker)
        {
            return picker.Checked ? (object)picker.Value.Date : DBNull.Value;
        }
    }
}