using RestaurantApp.DAL;
using RestaurantApp.Models;
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;

namespace RestaurantApp
{
    public partial class DishEditForm : Form
    {
        private DishRepository repo = new DishRepository();
        private Dish dish;
        private bool isEdit = false;

        public DishEditForm()
        {
            InitializeComponent();
            isEdit = false;
            dish = new Dish();
            this.Text = "Новое блюдо";
            LoadCategories();

            btnSave.Click += BtnSave_Click;
            btnCancel.Click += (s, e) => DialogResult = DialogResult.Cancel;
        }

        public DishEditForm(Dish existingDish)
        {
            InitializeComponent();
            isEdit = true;
            dish = existingDish;
            this.Text = "Редактирование блюда";
            LoadCategories();
            LoadData();

            btnSave.Click += BtnSave_Click;
            btnCancel.Click += (s, e) => DialogResult = DialogResult.Cancel;
        }

        private void LoadCategories()
        {
            var dtCategories = repo.GetCategories();

            var list = dtCategories.AsEnumerable().Select(r => new
            {
                category_id = r.Field<int>("category_id"),
                name = r.Field<string>("name")
            }).ToList();

            cmbCategory.DataSource = list;
            cmbCategory.DisplayMember = "name";
            cmbCategory.ValueMember = "category_id";

            if (!isEdit && cmbCategory.Items.Count > 0)
                cmbCategory.SelectedIndex = 0;
        }

        private void LoadData()
        {
            cmbCategory.SelectedValue = dish.CategoryId;
            txtName.Text = dish.Name;
            txtDescription.Text = dish.Description;
            numPrice.Value = dish.Price;
            numWeight.Value = dish.WeightG ?? 0;
            numCookTime.Value = dish.CookTimeMin ?? 0;
            chkAvailable.Checked = dish.IsAvailable;
        }

        private void SaveData()
        {
            dish.CategoryId = (int)cmbCategory.SelectedValue;
            dish.Name = txtName.Text.Trim();
            dish.Description = txtDescription.Text.Trim();
            dish.Price = numPrice.Value;
            dish.WeightG = numWeight.Value > 0 ? (int?)numWeight.Value : null;
            dish.CookTimeMin = numCookTime.Value > 0 ? (int?)numCookTime.Value : null;
            dish.IsAvailable = chkAvailable.Checked;

            if (string.IsNullOrWhiteSpace(dish.Name))
                throw new Exception("Введите название блюда");
            if (dish.Price <= 0)
                throw new Exception("Цена должна быть больше 0");

            if (isEdit)
                repo.Update(dish);
            else
                repo.Insert(dish);
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SaveData();
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DishEditForm_Load(object sender, EventArgs e)
        {

        }
    }
}