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

namespace sport_invent_modul_14._05
{
    public partial class Admin_Form : Form
    {
        string connectionString = "Server=85.239.57.125; Database=Primakov_Natalya_modul; Uid=Primakov_Natalya; Pwd=TempPass123!; SslMode=none;";

        public Admin_Form()
        {
            InitializeComponent();
            LoadProducts();
            

          //  button2.Click += (s, e) => { if (new ProductEditForm(connectionString, null).ShowDialog() == DialogResult.OK) LoadProducts(); };
            button3.Click += (s, e) => EditProduct();
            button4.Click += (s, e) => DeleteProduct();
            textBox1.TextChanged += (s, e) => FilterAndSort();
            comboBox1.SelectedIndexChanged += (s, e) => FilterAndSort();
            comboBox2.SelectedIndexChanged += (s, e) => FilterAndSort();
        }

        // Загрузка товаров
        void LoadProducts()
        {
            using (var conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                var adapter = new MySqlDataAdapter(@"SELECT p.idProduct, p.Article, p.Name, c.Category, p.Description, 
                     m.Manufacturer, s.Supplier, p.Price, p.Discount, p.Quantity, u.Unit, p.Photo
                     FROM Product p
                     LEFT JOIN Category c ON p.CategoryID = c.idCategory
                     LEFT JOIN Manufacturer m ON p.ManufacturerID = m.idManufacturer
                     LEFT JOIN Supplier s ON p.SupplierID = s.idSupplier
                     LEFT JOIN Unit u ON p.EdinicaID = u.idUnit", conn);

                var dt = new DataTable();
                adapter.Fill(dt);
                dataGridView1.DataSource = dt;
                if (dataGridView1.Columns["idProduct"] != null)
                    dataGridView1.Columns["idProduct"].Visible = false;
            }
        }

        // Редактирование товара
        void EditProduct()
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("Выберите товар", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            int id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["idProduct"].Value);
         //   if (new ProductEditForm(connectionString, id).ShowDialog() == DialogResult.OK)
                LoadProducts();
        }

        // Удаление товара
        void DeleteProduct()
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("Выберите товар", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["idProduct"].Value);
            string name = dataGridView1.SelectedRows[0].Cells["Name"].Value.ToString();

            if (MessageBox.Show($"Удалить \"{name}\"?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                using (var conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    var cmd = new MySqlCommand("DELETE FROM Product WHERE idProduct = @id", conn);
                    cmd.Parameters.AddWithValue("@id", id);
                    cmd.ExecuteNonQuery();
                }
                LoadProducts();
            }
        }

        // Фильтрация и сортировка
        void FilterAndSort()
        {
            string search = textBox1.Text.Trim();
            string filter = comboBox1.SelectedItem?.ToString() ?? "";
            string sort = comboBox2.SelectedItem?.ToString() ?? "";

            string query = @"SELECT p.idProduct, p.Article, p.Name, c.Category, p.Description, 
                 m.Manufacturer, s.Supplier, p.Price, p.Discount, p.Quantity, u.Unit, p.Photo
                 FROM Product p
                 LEFT JOIN Category c ON p.CategoryID = c.idCategory
                 LEFT JOIN Manufacturer m ON p.ManufacturerID = m.idManufacturer
                 LEFT JOIN Supplier s ON p.SupplierID = s.idSupplier
                 LEFT JOIN Unit u ON p.EdinicaID = u.idUnit
                 WHERE 1=1";

            // Фильтрация
            if (!string.IsNullOrEmpty(search))
            {
                if (filter == "По названию") query += " AND p.Name LIKE @search";
                else if (filter == "По артикулу") query += " AND p.Article LIKE @search";
                else if (filter == "По производителю") query += " AND m.Manufacturer LIKE @search";
                else if (filter == "По поставщику") query += " AND s.Supplier LIKE @search";
                else query += " AND (p.Name LIKE @search OR p.Article LIKE @search OR m.Manufacturer LIKE @search)";
            }

            // Сортировка
            if (sort == "По названию А-Я") query += " ORDER BY p.Name ASC";
            else if (sort == "По названию Я-А") query += " ORDER BY p.Name DESC";
            else if (sort == "По цене возр.") query += " ORDER BY p.Price ASC";
            else if (sort == "По цене убыв.") query += " ORDER BY p.Price DESC";
            else if (sort == "По артикулу") query += " ORDER BY p.Article ASC";
            else if (sort == "По количеству") query += " ORDER BY p.Quantity ASC";
            else query += " ORDER BY p.Name ASC";

            using (var conn = new MySqlConnection(connectionString))
            {
                conn.Open();
                var cmd = new MySqlCommand(query, conn);
                if (!string.IsNullOrEmpty(search))
                    cmd.Parameters.AddWithValue("@search", "%" + search + "%");

                var dt = new DataTable();
                new MySqlDataAdapter(cmd).Fill(dt);
                dataGridView1.DataSource = dt;
                if (dataGridView1.Columns["idProduct"] != null)
                    dataGridView1.Columns["idProduct"].Visible = false;
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            new Form1().Show();
            Close();
        }

        private void Admin_Form_Load(object sender, EventArgs e)
        {

        }
    }
}
