using Microsoft.EntityFrameworkCore;
using moduleExamen.Data;
using moduleExamen.Helpers;
using moduleExamen.Models;

namespace moduleExamen.Forms
{
    public partial class OrderListForm : Form
    {
        public OrderListForm()
        {
            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);

            addButton.Visible = SessionManager.IsAdmin;
            deleteButton.Visible = SessionManager.IsAdmin;

            LoadData();
        }

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

        private void LoadData()
        {
            try
            {
                using var context = new SportShopContext();
                var orders = context.Orders
                    .Include(o => o.FioNavigation)
                    .Include(o => o.IdStatusNavigation)
                    .Include(o => o.OrderItems)
                    .OrderByDescending(o => o.DataStart)
                    .ToList();

                orderGrid.Rows.Clear();
                foreach (var o in orders)
                {
                    var client = o.FioNavigation != null ? o.FioNavigation.Fio : "—";
                    var status = o.IdStatusNavigation != null ? o.IdStatusNavigation.Name : "—";
                    var dateEnd = o.DateEnd.HasValue ? o.DateEnd.Value.ToString("dd.MM.yyyy") : "—";

                    var rowIndex = orderGrid.Rows.Add(
                        o.Idzakaz,
                        o.Article,
                        client,
                        status,
                        o.Adrec,
                        o.DataStart.ToString("dd.MM.yyyy"),
                        dateEnd,
                        o.OrderItems.Count
                    );
                    orderGrid.Rows[rowIndex].Tag = o;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки заказов: " + ex.Message);
            }
        }

        private void OrderGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || !SessionManager.IsAdmin) return;

            var order = orderGrid.Rows[e.RowIndex].Tag as Order;
            if (order == null) return;

            var editForm = new OrderEditForm(order);
            editForm.FormClosed += (s, args) => LoadData();
            editForm.Show();
        }

        private void AddButton_Click(object sender, EventArgs e)
        {
            var editForm = new OrderEditForm(null);
            editForm.FormClosed += (s, args) => LoadData();
            editForm.Show();
        }

        private void DeleteButton_Click(object sender, EventArgs e)
        {
            if (orderGrid.CurrentRow == null) return;

            var order = orderGrid.CurrentRow.Tag as Order;
            if (order == null) return;

            var result = MessageBox.Show("Удалить заказ \"" + order.Article + "\"?",
                "Подтверждение", MessageBoxButtons.YesNo);

            if (result != DialogResult.Yes) return;

            try
            {
                using var context = new SportShopContext();
                var dbOrder = context.Orders
                    .Include(o => o.OrderItems)
                    .FirstOrDefault(o => o.Idzakaz == order.Idzakaz);

                if (dbOrder != null)
                {
                    context.OrderItems.RemoveRange(dbOrder.OrderItems);
                    context.Orders.Remove(dbOrder);
                    context.SaveChanges();
                }

                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка удаления: " + ex.Message);
            }
        }
    }
}
