using moduleExamen.Data;
using moduleExamen.Models;

namespace moduleExamen.Forms
{
    public partial class ProductEditForm : Form
    {
        private Product editingProduct;
        private bool isEditing;
        private byte[] photoBytes;

        public ProductEditForm(Product product)
        {
            InitializeComponent();

            var iconPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "icon.ico");
            if (File.Exists(iconPath))
                Icon = new Icon(iconPath);

            var logoPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "logo.png");
            if (File.Exists(logoPath))
                logoPictureBox.Image = Image.FromFile(logoPath);

            editingProduct = product;
            isEditing = product != null;

            if (isEditing)
            {
                Text = "Sport Farm - Редактирование товара";
                idLabel.Text = "ID товара: " + product.Idproduct;
            }
            else
            {
                Text = "Sport Farm - Добавление товара";
                idLabel.Text = "ID: (новый)";
            }

            LoadComboBoxData();

            if (isEditing)
                FillFields();
        }

        private void LoadComboBoxData()
        {
            try
            {
                using var context = new SportShopContext();

                categoryComboBox.DataSource = context.TipeProducts.ToList();
                categoryComboBox.DisplayMember = "Name";
                categoryComboBox.ValueMember = "IdtipeProduct";

                manufacturerComboBox.DataSource = context.Manufacts.ToList();
                manufacturerComboBox.DisplayMember = "Name";
                manufacturerComboBox.ValueMember = "Idmanufact";

                supplierComboBox.DataSource = context.Supliers.ToList();
                supplierComboBox.DisplayMember = "Name";
                supplierComboBox.ValueMember = "Idsuplier";

                edComboBox.DataSource = context.Eds.ToList();
                edComboBox.DisplayMember = "Name";
                edComboBox.ValueMember = "Ided";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки справочников: " + ex.Message);
            }
        }

        private void FillFields()
        {
            if (editingProduct == null) return;

            articlTextBox.Text = editingProduct.Articl;
            articlTextBox.ReadOnly = true;
            nameTextBox.Text = editingProduct.Name;
            categoryComboBox.SelectedValue = editingProduct.IdTipeProduct;
            descriptionTextBox.Text = editingProduct.ProductContent;
            manufacturerComboBox.SelectedValue = editingProduct.IdManufactur;
            supplierComboBox.SelectedValue = editingProduct.IdSuplier;
            priceTextBox.Text = editingProduct.PriceProduct.ToString("F2");
            edComboBox.SelectedValue = editingProduct.IdEd;
            kolvoTextBox.Text = editingProduct.KolVo != null ? editingProduct.KolVo.ToString() : "0";
            saleTextBox.Text = editingProduct.Sale != null ? editingProduct.Sale.ToString() : "0";

            photoBytes = editingProduct.IdPhoto;
            if (photoBytes != null && photoBytes.Length > 0)
            {
                try
                {
                    using var ms = new MemoryStream(photoBytes);
                    photoPictureBox.Image = Image.FromStream(ms);
                }
                catch { }
            }
        }

        private void ChangePhoto_Click(object sender, EventArgs e)
        {
            using var dialog = new OpenFileDialog();
            dialog.Filter = "Изображения (*.jpg;*.png)|*.jpg;*.png";

            if (dialog.ShowDialog() != DialogResult.OK) return;

            try
            {
                photoBytes = File.ReadAllBytes(dialog.FileName);
                using var ms = new MemoryStream(photoBytes);
                photoPictureBox.Image = Image.FromStream(ms);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки изображения: " + ex.Message);
            }
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(nameTextBox.Text))
            {
                MessageBox.Show("Введите наименование товара.");
                return;
            }

            if (!decimal.TryParse(priceTextBox.Text, out var price))
            {
                MessageBox.Show("Введите корректную цену.");
                return;
            }

            if (!int.TryParse(kolvoTextBox.Text, out var kolvo))
            {
                MessageBox.Show("Введите корректное количество.");
                return;
            }

            if (!int.TryParse(saleTextBox.Text, out var sale))
            {
                MessageBox.Show("Введите корректную скидку.");
                return;
            }

            try
            {
                using var context = new SportShopContext();

                Product product;
                if (isEditing)
                {
                    product = context.Products.Find(editingProduct.Idproduct);
                }
                else
                {
                    product = new Product();
                    product.Articl = articlTextBox.Text.Trim();
                    context.Products.Add(product);
                }

                product.Name = nameTextBox.Text.Trim();
                product.IdTipeProduct = (int)categoryComboBox.SelectedValue;
                product.ProductContent = descriptionTextBox.Text.Trim();
                product.IdManufactur = (int)manufacturerComboBox.SelectedValue;
                product.IdSuplier = (int)supplierComboBox.SelectedValue;
                product.PriceProduct = price;
                product.IdEd = (int)edComboBox.SelectedValue;
                product.KolVo = kolvo;
                product.Sale = sale;
                product.IdPhoto = photoBytes;

                context.SaveChanges();

                MessageBox.Show("Данные сохранены.");
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка сохранения: " + ex.Message);
            }
        }
    }
}
