using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace Neshina1703
{
    public partial class OrderForm : Form
    {
        private int userId;
        private List<OrderItem> orderItems = new List<OrderItem>();
        private decimal orderTotal = 0;

        public OrderForm(int userId)
        {
            InitializeComponent();
            this.userId = userId;
        }

        private void OrderForm_Load(object sender, EventArgs e)
        {
            LoadClients();
            LoadProducts();
            SetupGrids();
        }

        private void LoadClients()
        {
            try
            {
                var query = @"SELECT 0 AS id, '— Без регистрации —' AS full_name
                              UNION ALL
                              SELECT id, full_name FROM clients ORDER BY full_name";

                var clients = DB.ExecuteQuery(query);
                cbClient.DataSource = clients;
                cbClient.DisplayMember = "full_name";
                cbClient.ValueMember = "id";
                cbClient.SelectedIndex = 0; 
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки клиентов: " + ex.Message, "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cbClient_SelectedIndexChanged(object sender, EventArgs e)
        {
            object selectedValue = cbClient.SelectedValue;

            if (selectedValue == null || selectedValue == DBNull.Value)
            {
                cbPrescription.DataSource = null;
                cbPrescription.Enabled = false;
                return;
            }

            int clientId;
            try
            {
                clientId = Convert.ToInt32(selectedValue);
            }
            catch
            {
                cbPrescription.DataSource = null;
                cbPrescription.Enabled = false;
                return;
            }

            if (clientId == 0)
            {
                cbPrescription.DataSource = null;
                cbPrescription.Enabled = false;
                return;
            }

            var query = @"SELECT id, prescription_number, valid_until 
                         FROM prescriptions 
                         WHERE client_id = @clientId AND valid_until >= CURDATE()
                         ORDER BY valid_until";

            var prescriptions = DB.ExecuteQuery(query,
                new MySqlParameter[] { new MySqlParameter("@clientId", clientId) });

            if (prescriptions.Rows.Count > 0)
            {
                var table = prescriptions.Clone();
                table.Rows.Add(0, "— Без рецепта —", DBNull.Value);
                foreach (DataRow row in prescriptions.Rows)
                    table.ImportRow(row);

                cbPrescription.DataSource = table;
                cbPrescription.DisplayMember = "prescription_number";
                cbPrescription.ValueMember = "id";
                cbPrescription.SelectedIndex = 0;
                cbPrescription.Enabled = true;
            }
            else
            {
                cbPrescription.DataSource = null;
                cbPrescription.Enabled = false;
            }
        }

        private void LoadProducts()
        {
            try
            {
                var query = @"SELECT 
                    m.id,
                    m.medication_name AS 'Название',
                    m.price,
                    m.stock_quantity AS 'Остаток',
                    ds.status_name AS 'Тип'
                    FROM medications m
                    LEFT JOIN dispensing_statuses ds ON m.dispensing_status_id = ds.id
                    WHERE m.stock_quantity > 0
                    ORDER BY m.medication_name";

                dgvProducts.DataSource = DB.ExecuteQuery(query);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки товаров: " + ex.Message, "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SetupGrids()
        {
            if (dgvProducts.Columns["id"] != null)
                dgvProducts.Columns["id"].Visible = false;
            if (dgvProducts.Columns["price"] != null)
                dgvProducts.Columns["price"].DefaultCellStyle.Format = "0.00 ₽";

            dgvOrder.Columns.Clear();
            dgvOrder.Columns.Add("Name", "Товар");
            dgvOrder.Columns.Add("Price", "Цена");
            dgvOrder.Columns.Add("Quantity", "Кол-во");
            dgvOrder.Columns.Add("Total", "Сумма");
            dgvOrder.Columns["Price"].DefaultCellStyle.Format = "0.00 ₽";
            dgvOrder.Columns["Total"].DefaultCellStyle.Format = "0.00 ₽";
            dgvOrder.Columns["Total"].DefaultCellStyle.Font =
                new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold);
        }

        private void dgvProducts_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
                AddProductToOrder();
        }

        private void btnAddToOrder_Click(object sender, EventArgs e)
        {
            AddProductToOrder();
        }

        private void AddProductToOrder()
        {
            if (dgvProducts.CurrentRow == null) return;

            int productId = Convert.ToInt32(dgvProducts.CurrentRow.Cells["id"].Value);
            string name = dgvProducts.CurrentRow.Cells["Название"].Value.ToString();
            decimal price = Convert.ToDecimal(dgvProducts.CurrentRow.Cells["price"].Value);
            int stock = Convert.ToInt32(dgvProducts.CurrentRow.Cells["Остаток"].Value);
            int quantity = (int)numQuantity.Value;

            if (quantity > stock)
            {
                MessageBox.Show($" На складе только {stock} шт.!", "Недостаточно товара",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var existing = orderItems.FirstOrDefault(x => x.ProductId == productId);
            if (existing != null)
            {
                if (existing.Quantity + quantity > stock)
                {
                    MessageBox.Show($" Превышен остаток на складе!", "Ошибка",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                existing.Quantity += quantity;
            }
            else
            {
                orderItems.Add(new OrderItem
                {
                    ProductId = productId,
                    Name = name,
                    Price = price,
                    Quantity = quantity
                });
            }

            RefreshOrderGrid();
            numQuantity.Value = 1;
        }

        private void btnRemoveFromOrder_Click(object sender, EventArgs e)
        {
            if (dgvOrder.CurrentRow == null) return;

            int index = dgvOrder.CurrentRow.Index;
            orderItems.RemoveAt(index);
            RefreshOrderGrid();
        }

        private void RefreshOrderGrid()
        {
            dgvOrder.Rows.Clear();
            orderTotal = 0;

            foreach (var item in orderItems)
            {
                decimal lineTotal = item.Price * item.Quantity;
                orderTotal += lineTotal;

                dgvOrder.Rows.Add(item.Name, item.Price, item.Quantity, lineTotal);
            }

            lblTotal.Text = $"Итого: {orderTotal:0.00} ₽";
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (orderItems.Count == 0)
            {
                MessageBox.Show(" Добавьте товары в заказ!", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                using (var conn = DB.GetConnection())
                {
                    conn.Open();
                    using (var transaction = conn.BeginTransaction())
                    {
                        try
                        {
                            object clientVal = cbClient.SelectedValue;
                            int? clientId = null;
                            if (clientVal != null && clientVal != DBNull.Value)
                            {
                                int id = Convert.ToInt32(clientVal);
                                if (id > 0) clientId = id; 
                            }

                            int? prescriptionId = null;
                            if (cbPrescription.Enabled && cbPrescription.SelectedValue != null && cbPrescription.SelectedValue != DBNull.Value)
                            {
                                int pid = Convert.ToInt32(cbPrescription.SelectedValue);
                                if (pid > 0) prescriptionId = pid; 
                            }

                            var insertPurchase = @"INSERT INTO purchases (purchase_date, client_id, prescription_id) 
                                                  VALUES (@date, @client, @prescription)";

                            var purchaseParams = new MySqlParameter[]
                            {
                                new MySqlParameter("@date", DateTime.Now.ToString("yyyy-MM-dd")),
                                new MySqlParameter("@client", clientId ?? (object)DBNull.Value),
                                new MySqlParameter("@prescription", prescriptionId ?? (object)DBNull.Value)
                            };

                            int purchaseId;
                            using (var cmd = new MySqlCommand(insertPurchase, conn, transaction))
                            {
                                cmd.Parameters.AddRange(purchaseParams);
                                cmd.ExecuteNonQuery();

                                cmd.CommandText = "SELECT LAST_INSERT_ID()";
                                purchaseId = Convert.ToInt32(cmd.ExecuteScalar());
                            }
                            foreach (var item in orderItems)
                            {
                                var insertItem = @"INSERT INTO purchase_medications (purchase_id, medication_id, quantity) 
                                                  VALUES (@purchase, @medication, @qty)";

                                var itemParams = new MySqlParameter[]
                                {
                                    new MySqlParameter("@purchase", purchaseId),
                                    new MySqlParameter("@medication", item.ProductId),
                                    new MySqlParameter("@qty", item.Quantity)
                                };

                                using (var cmd = new MySqlCommand(insertItem, conn, transaction))
                                {
                                    cmd.Parameters.AddRange(itemParams);
                                    cmd.ExecuteNonQuery();
                                }

                                var updateStock = @"UPDATE medications SET stock_quantity = stock_quantity - @qty WHERE id = @id";
                                var stockParams = new MySqlParameter[]
                                {
                                    new MySqlParameter("@qty", item.Quantity),
                                    new MySqlParameter("@id", item.ProductId)
                                };

                                using (var cmd = new MySqlCommand(updateStock, conn, transaction))
                                {
                                    cmd.Parameters.AddRange(stockParams);
                                    cmd.ExecuteNonQuery();
                                }
                            }

                            transaction.Commit();
                            this.DialogResult =DialogResult.OK;
                            MessageBox.Show($"Заказ оформлен!\nСумма: {orderTotal:0.00} ₽", "Успех",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.Close();
                        }
                        catch
                        {
                            transaction.Rollback();
                            throw;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(" Ошибка сохранения: " + ex.Message, "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
        private class OrderItem
        {
            public int ProductId { get; set; }
            public string Name { get; set; }
            public decimal Price { get; set; }
            public int Quantity { get; set; }
        }
    }
}