using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NeshinaPolina2111
{
    public partial class EditMaterials : Form
    {
        public EditMaterials()
        {
            InitializeComponent();
        }
        public int MaterialId { get; set; } //ДЛЯ ПЕРЕХОДА

        private void EditMaterials_Load(object sender, EventArgs e)
        {
            LoadTypes();
            LoadUnits();
            LoadMaterialData();
        }

        private void LoadTypes() //ТИПЫ
        {
            string query = "SELECT idMaterial_type_import, Name FROM Material_type_import ORDER BY Name";
            var conn = DB.GetInstance().GetConnection();
            if (conn.State == ConnectionState.Closed)
                conn.Open();

            using (var cmd = new MySqlCommand(query, conn))
            {
                var adapter = new MySqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adapter.Fill(dt);

                cmbType.DisplayMember = "Name";
                cmbType.ValueMember = "idMaterial_type_import";
                cmbType.DataSource = dt;
            }
        }

        private void LoadUnits() //ИЗМЕРЕНИЕ ЕДИНИЦЫ
        {
            string query = "SELECT idUnit, Name FROM Unit ORDER BY Name";
            var conn = DB.GetInstance().GetConnection();
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            using (var cmd = new MySqlCommand(query, conn))
            {
                var adapter = new MySqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adapter.Fill(dt);

                cmbUnit.DisplayMember = "Name";
                cmbUnit.ValueMember = "idUnit";
                cmbUnit.DataSource = dt;
            }
        }

        private void LoadMaterialData() //САМА ТАБЛИЦА
        {
            string query = @"
                SELECT
                    m.Name,
                    m.idMaterial_type_import,
                    m.PriceUnitMaterial,
                    m.Quantity,
                    m.MinQuantity,
                    m.QuantityPack,
                    m.idUnit
                FROM Materials_import m
                WHERE m.idMaterials_import = @idMaterials_import";
            var conn = DB.GetInstance().GetConnection();
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            using (var cmd = new MySqlCommand(query, conn))
            {
                cmd.Parameters.AddWithValue("@idMaterials_import", MaterialId);

                var reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    txtName.Text = reader["Name"].ToString();
                    txtPrice.Text = reader["PriceUnitMaterial"].ToString();
                    txtQuantity.Text = reader["Quantity"].ToString();
                    txtMinQuantity.Text = reader["MinQuantity"].ToString();
                    txtQuantityPack.Text = reader["QuantityPack"].ToString();
                    cmbType.SelectedValue = reader["idMaterial_type_import"];
                    cmbUnit.SelectedValue = reader["idUnit"];
                }
                else
                {
                    MessageBox.Show("Материал не найден.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    DialogResult = DialogResult.Cancel;
                    Close();
                }
                reader.Close();
            }
        }

        private void btnEdit_Click(object sender, EventArgs e) //СОХРАНЕНИЕ 
        {
            if (string.IsNullOrWhiteSpace(txtName.Text)) //ПРОВЕРКИ НА ВСЁ
            {
                MessageBox.Show("Введите название материала.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (cmbType.SelectedValue == null || cmbUnit.SelectedValue == null)
            {
                MessageBox.Show("Выберите тип материала и единицу измерения.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            decimal price;
            int quantity, minQuantity, quantityPack;

            if (!decimal.TryParse(txtPrice.Text, out price) || price < 0)
            {
                MessageBox.Show("Цена должна быть числом ≥ 0.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (!int.TryParse(txtQuantity.Text, out quantity) || quantity < 0)
            {
                MessageBox.Show("Количество должно быть целым числом ≥ 0.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (!int.TryParse(txtMinQuantity.Text, out minQuantity) || minQuantity < 0)
            {
                MessageBox.Show("Минимальное количество должно быть целым числом ≥ 0.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!int.TryParse(txtQuantityPack.Text, out quantityPack) || quantityPack < 0)
            {
                MessageBox.Show("Количество в упаковке должно быть целым числом ≥ 0.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }//ОБНОВЛЕНИЕ ТУТ
            string updateQuery = @"
                UPDATE Materials_import SET
                    Name = @Name,
                    idMaterial_type_import = @idMaterial_type_import,
                    PriceUnitMaterial = @PriceUnitMaterial,
                    Quantity = @Quantity,
                    MinQuantity = @MinQuantity,
                    QuantityPack = @QuantityPack,
                    idUnit = @idUnit
                WHERE idMaterials_import = @idMaterials_import";
            var conn = DB.GetInstance().GetConnection();
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            using (var cmd = new MySqlCommand(updateQuery, conn))
            {
                cmd.Parameters.AddWithValue("@Name", txtName.Text.Trim());
                cmd.Parameters.AddWithValue("@idMaterial_type_import", cmbType.SelectedValue);
                cmd.Parameters.AddWithValue("@PriceUnitMaterial", price);
                cmd.Parameters.AddWithValue("@Quantity", quantity);
                cmd.Parameters.AddWithValue("@MinQuantity", minQuantity);
                cmd.Parameters.AddWithValue("@QuantityPack", quantityPack);
                cmd.Parameters.AddWithValue("@idUnit", cmbUnit.SelectedValue);
                cmd.Parameters.AddWithValue("@idMaterials_import", MaterialId);
                try
                {
                    int rowsAffected = cmd.ExecuteNonQuery();
                    if (rowsAffected > 0)
                    {
                        MessageBox.Show("Материал успешно обновлён!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        DialogResult = DialogResult.OK;
                        Close();
                    }
                    else
                    {
                        MessageBox.Show("Не удалось обновить материал.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Ошибка при обновлении: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Hide();

        }
    }
}
