using moduleExamen.Data;
using moduleExamen.Models;

namespace moduleExamen.Forms
{
    public partial class OrderEditForm : Form
    {
        private Order editingOrder;
        private bool isEditing;

        public OrderEditForm(Order order)
        {
            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);

            editingOrder = order;
            isEditing = order != null;

            if (isEditing)
            {
                Text = "Sport Farm - Редактирование заказа";
                idLabel.Text = "Заказ #" + order.Idzakaz;
            }
            else
            {
                Text = "Sport Farm - Добавление заказа";
                idLabel.Text = "Новый заказ";
            }

            LoadStatuses();
            if (isEditing) FillFields();
        }

        private void DateEndCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            dateEndPicker.Enabled = dateEndCheckBox.Checked;
        }

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

        private void LoadStatuses()
        {
            try
            {
                using var context = new SportShopContext();
                statusComboBox.DataSource = context.Statuses.ToList();
                statusComboBox.DisplayMember = "Name";
                statusComboBox.ValueMember = "IdStatus";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки статусов: " + ex.Message);
            }
        }

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

            articleTextBox.Text = editingOrder.Article;
            statusComboBox.SelectedValue = editingOrder.IdStatus;
            addressTextBox.Text = editingOrder.Adrec;
            dateStartPicker.Value = editingOrder.DataStart.ToDateTime(TimeOnly.MinValue);

            if (editingOrder.DateEnd.HasValue)
            {
                dateEndCheckBox.Checked = true;
                dateEndPicker.Value = editingOrder.DateEnd.Value.ToDateTime(TimeOnly.MinValue);
            }
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(articleTextBox.Text))
            {
                MessageBox.Show("Введите артикул заказа.");
                return;
            }

            if (string.IsNullOrWhiteSpace(addressTextBox.Text))
            {
                MessageBox.Show("Введите адрес пункта выдачи.");
                return;
            }

            try
            {
                using var context = new SportShopContext();

                Order order;
                if (isEditing)
                {
                    order = context.Orders.First(o => o.Idzakaz == editingOrder.Idzakaz);
                }
                else
                {
                    order = new Order();
                    order.Fio = 1;
                    context.Orders.Add(order);
                }

                order.Article = articleTextBox.Text.Trim();
                order.IdStatus = (int)statusComboBox.SelectedValue;
                order.Adrec = addressTextBox.Text.Trim();
                order.DataStart = DateOnly.FromDateTime(dateStartPicker.Value);

                if (dateEndCheckBox.Checked)
                    order.DateEnd = DateOnly.FromDateTime(dateEndPicker.Value);
                else
                    order.DateEnd = null;

                context.SaveChanges();

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