using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace Neshina1703
{
    public partial class EmployeeForm : Form
    {
        private int userId;
        private string userName;

        public EmployeeForm(int userId, string userName)
        {
            InitializeComponent();
            this.userId = userId;
            this.userName = userName;
        }

        private void EmployeeForm_Load(object sender, EventArgs e)
        {
            lblUser.Text = $"👤 {userName}";
            LoadProducts();
            LoadOrders();
            LoadClients();
        }

        // 🔹 Загрузка товаров в DataGrid
        private void LoadProducts()
        {
            try
            {
                string query = @"SELECT 
                    m.id AS 'ID',
                    m.medication_name AS 'Название',
                    m.price AS 'Цена, ₽',
                    m.stock_quantity AS 'На складе',
                    ds.status_name AS 'Отпуск',
                    s.supplier_name AS 'Поставщик'
                    FROM medications m
                    LEFT JOIN dispensing_statuses ds ON m.dispensing_status_id = ds.id
                    LEFT JOIN suppliers s ON m.supplier_id = s.id
                    ORDER BY m.medication_name";

                dgvProducts.DataSource = DB.ExecuteQuery(query);

                // Скрыть ID и настроить столбцы
                if (dgvProducts.Columns["ID"] != null)
                    dgvProducts.Columns["ID"].Visible = false;

                FormatGrid(dgvProducts);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки товаров: " + ex.Message, "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 🔹 Загрузка истории заказов
        private void LoadOrders()
        {
            try
            {
                string query = @"SELECT 
                    p.id AS 'ID',
                    p.purchase_date AS 'Дата',
                    c.full_name AS 'Клиент',
                    pr.prescription_number AS 'Рецепт №',
                    GROUP_CONCAT(CONCAT(m.medication_name, ' ×', pm.quantity) SEPARATOR ', ') AS 'Состав'
                    FROM purchases p
                    LEFT JOIN clients c ON p.client_id = c.id
                    LEFT JOIN prescriptions pr ON p.prescription_id = pr.id
                    LEFT JOIN purchase_medications pm ON p.id = pm.purchase_id
                    LEFT JOIN medications m ON pm.medication_id = m.id
                    GROUP BY p.id
                    ORDER BY p.purchase_date DESC";

                dgvOrders.DataSource = DB.ExecuteQuery(query);

                if (dgvOrders.Columns["ID"] != null)
                    dgvOrders.Columns["ID"].Visible = false;

                FormatGrid(dgvOrders);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки заказов: " + ex.Message, "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 🔹 Загрузка клиентов в DataGrid
        private void LoadClients()
        {
            try
            {
                string query = @"SELECT 
                    c.id AS 'ID',
                    c.full_name AS 'ФИО',
                    c.phone AS 'Телефон',
                    c.email AS 'Email',
                    dc.discount_percentage AS 'Скидка, %'
                    FROM clients c
                    LEFT JOIN discount_cards dc ON c.discount_card_id = dc.id
                    ORDER BY c.full_name";

                dgvClients.DataSource = DB.ExecuteQuery(query);

                if (dgvClients.Columns["ID"] != null)
                    dgvClients.Columns["ID"].Visible = false;

                FormatGrid(dgvClients);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки клиентов: " + ex.Message, "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 🔹 Форматирование DataGrid
        private void FormatGrid(DataGridView grid)
        {
            grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            grid.DefaultCellStyle.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F);
            grid.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold);
            grid.ColumnHeadersDefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(240, 240, 240);
            grid.DefaultCellStyle.SelectionBackColor = System.Drawing.Color.FromArgb(0, 120, 215);
            grid.DefaultCellStyle.SelectionForeColor = System.Drawing.Color.White;
            grid.RowHeadersVisible = false;
            grid.AllowUserToResizeRows = false;
        }

        // 🔹 Кнопка: Оформить заказ
        private void btnCreateOrder_Click(object sender, EventArgs e)
        {
            var orderForm = new OrderForm(userId);
            if (orderForm.ShowDialog() == DialogResult.OK)
            {
                LoadProducts();   // Обновить остатки
                LoadOrders();     // Показать новый заказ
                MessageBox.Show("✅ Заказ оформлен!", "Успех",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        // 🔹 Кнопка: Завести бонусную карту
        private void btnAddCard_Click(object sender, EventArgs e)
        {
            var clientForm = new ClientForm();
            if (clientForm.ShowDialog() == DialogResult.OK)
            {
                LoadClients();
                MessageBox.Show("✅ Карта заведена!", "Успех",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        // 🔹 Кнопка: Выход
        private void btnLogout_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("Выйти из системы?", "Подтверждение",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                this.Hide();
                var loginForm = new LoginForm();
                loginForm.Show();
                this.FormClosed += (s, args) => loginForm.FormClosed += (s2, a2) => Application.Exit();
            }
        }

        // 🔹 Обновление при возврате фокуса
        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            LoadProducts();
            LoadOrders();
            LoadClients();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var messengerForm = new MessengerForm(userId);
            messengerForm.Show();
        }
    }
}