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

namespace Neshina1703
{
    public partial class AdminForm : Form
    {
        private int userId;
        private string userName;
        private DataTable allProducts;

        public AdminForm(int userId, string userName)
        {
            InitializeComponent();
            this.userId = userId;
            this.userName = userName;
        }

        private void AdminForm_Load(object sender, EventArgs e)
        {
            lblUser.Text = $" {userName}";
            LoadSuppliers();
            LoadProducts();
            LoadOrders();
            SetupGrids();
        }

        private void LoadSuppliers()
        {
            var suppliers = DB.ExecuteQuery("SELECT DISTINCT supplier_name FROM suppliers ORDER BY supplier_name");
            cbFilterSupplier.Items.Clear();
            cbFilterSupplier.Items.Add("Все поставщики");
            foreach (DataRow row in suppliers.Rows)
                cbFilterSupplier.Items.Add(row["supplier_name"].ToString());
            cbFilterSupplier.SelectedIndex = 0;
        }

        private void LoadProducts()
        {
            try
            {
                string query = @"SELECT 
                    m.id AS 'ID',
                    m.medication_name AS 'Название',
                    CONCAT(m.price, ' ₽') AS 'Цена',
                    m.stock_quantity AS 'На складе',
                    m.batch_number AS 'Партия',
                    s.supplier_name AS 'Поставщик',
                    ds.status_name AS 'Отпуск',
                    IF(m.has_analog, '✅', '❌') AS 'Аналог'
                    FROM medications m
                    LEFT JOIN suppliers s ON m.supplier_id = s.id
                    LEFT JOIN dispensing_statuses ds ON m.dispensing_status_id = ds.id
                    ORDER BY m.medication_name";

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

        private void ApplyFilters(object sender = null, EventArgs e = null)
        {
            if (allProducts == null) return;

            DataView view = allProducts.DefaultView;
            string filter = "";

            if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
                filter += $"Название LIKE '%{txtSearch.Text.Trim()}%'";

            if (cbFilterStatus.SelectedIndex > 0)
            {
                string status = cbFilterStatus.SelectedItem.ToString();
                if (!string.IsNullOrEmpty(filter)) filter += " AND ";
                filter += $"Отпуск = '{status}'";
            }

            if (cbFilterSupplier.SelectedIndex > 0)
            {
                string supplier = cbFilterSupplier.SelectedItem.ToString();
                if (!string.IsNullOrEmpty(filter)) filter += " AND ";
                filter += $"Поставщик = '{supplier}'";
            }

            view.RowFilter = filter;
            dgvProducts.DataSource = view;
        }

        private void txtSearch_TextChanged(object sender, EventArgs e) => ApplyFilters();

        private void SetupGrids()
        {
            dgvProducts.Columns["ID"].Visible = false;
            dgvProducts.Columns["Цена"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvProducts.Columns["На складе"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvProducts.Columns["Аналог"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgvProducts.CellFormatting += (s, args) =>
            {
                if (dgvProducts.Columns[args.ColumnIndex].Name == "На складе" &&
                    args.Value != null && Convert.ToInt32(args.Value) < 10)
                {
                    args.CellStyle.BackColor = Color.FromArgb(255, 220, 220);
                    args.CellStyle.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold);
                }
            };

            dgvOrders.Columns["ID"].Visible = false;
        }

        private void LoadOrders()
        {
            try
            {
                string query = @"SELECT 
                    p.id AS 'ID',
                    p.purchase_date AS 'Дата',
                    COALESCE(c.full_name, '—') AS 'Клиент',
                    COALESCE(pr.prescription_number, '—') AS 'Рецепт',
                    GROUP_CONCAT(CONCAT(m.medication_name, ' ×', pm.quantity) SEPARATOR ', ') AS 'Состав',
                    SUM(m.price * pm.quantity) AS 'Сумма, ₽'
                    FROM purchases p
                    LEFT JOIN clients c ON p.client_id = c.id
                    LEFT JOIN prescriptions pr ON p.prescription_id = pr.id
                    LEFT JOIN purchase_medications pm ON p.id = pm.purchase_id
                    LEFT JOIN medications m ON pm.medication_id = m.id
                    GROUP BY p.id
                    ORDER BY p.purchase_date DESC";

                dgvOrders.DataSource = DB.ExecuteQuery(query);
                dgvOrders.Columns["Сумма, ₽"].DefaultCellStyle.Format = "0.00 ₽";
                dgvOrders.Columns["Сумма, ₽"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки заказов: " + ex.Message, "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

        private void btnAddProduct_Click(object sender, EventArgs e)
        {
            var productForm = new ProductForm(-1); 
            if (productForm.ShowDialog() == DialogResult.OK)
            {
                LoadProducts();
                LoadSuppliers();
                MessageBox.Show("овар добавлен!", "Успех",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnEditProduct_Click(object sender, EventArgs e)
        {
            EditSelectedProduct();
        }

        private void EditSelectedProduct()
        {
            if (dgvProducts.CurrentRow == null)
            {
                MessageBox.Show("Выберите товар для редактирования!", "Внимание",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int productId = Convert.ToInt32(dgvProducts.CurrentRow.Cells["ID"].Value);
            var productForm = new ProductForm(productId);
            if (productForm.ShowDialog() == DialogResult.OK)
            {
                LoadProducts();
                MessageBox.Show("Товар обновлён!", "Успех",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnDeleteProduct_Click(object sender, EventArgs e)
        {
            if (dgvProducts.CurrentRow == null)
            {
                MessageBox.Show("Выберите товар для удаления!", "Внимание",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            int productId = Convert.ToInt32(dgvProducts.CurrentRow.Cells["ID"].Value);
            string productName = dgvProducts.CurrentRow.Cells["Название"].Value.ToString();
            var checkQuery = "SELECT COUNT(*) FROM purchase_medications WHERE medication_id = @id";
            var count = DB.ExecuteScalar(checkQuery, new MySqlParameter[] { new MySqlParameter("@id", productId) });
            if (Convert.ToInt32(count) > 0)
            {
                MessageBox.Show(" Нельзя удалить товар, который есть в истории заказов!", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var result = MessageBox.Show(
                $"Удалить товар \"{productName}\"?\n\nЭто действие нельзя отменить.",
                "Подтверждение удаления",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    DB.ExecuteCommand("DELETE FROM medications WHERE id = @id",
     new MySqlParameter[] { new MySqlParameter("@id", productId) });

                    LoadProducts();
                    MessageBox.Show("Товар удалён!", "Успех",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ошибка: " + ex.Message, "Ошибка",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            txtSearch.Clear();
            cbFilterStatus.SelectedIndex = 0;
            cbFilterSupplier.SelectedIndex = 0;
            LoadProducts();
            LoadOrders();
            MessageBox.Show("Данные обновлены", "Информация",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("Выйти из системы?", "Подтверждение",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                this.Hide();
                var loginForm = new LoginForm();
                loginForm.Show();
                this.FormClosed += (s, args) => loginForm.FormClosed += (s2, a2) => Application.Exit();
            }
        }

        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            LoadProducts();
            LoadOrders();
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
                if (dgvProducts.CurrentRow != null)
                {
                    int productId = Convert.ToInt32(dgvProducts.CurrentRow.Cells["ID"].Value);
                    var qrForm = new QRCodeViewerForm(productId);
                    qrForm.ShowDialog();
                }
            
        }
    }
}