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

namespace Neshina1703
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string email = txtEmail.Text.Trim();
            string password = txtPassword.Text.Trim();

            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("Введите email и пароль!", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var parameters = new MySqlParameter[]
            {
                new MySqlParameter("@email", email),
                new MySqlParameter("@password_hash", password)
            };

            var query = "SELECT id, full_name, position_id FROM employees WHERE email = @email AND password_hash = @password_hash LIMIT 1";
            var result = DB.ExecuteQuery(query, parameters);

            if (result.Rows.Count > 0)
            {
                int userId = Convert.ToInt32(result.Rows[0]["id"]);
                string fullName = result.Rows[0]["full_name"].ToString();
                int positionId = Convert.ToInt32(result.Rows[0]["position_id"]);

                this.Hide();

                if (positionId == 1) // Главный фармацевт = Админ
                {
                    new AdminForm(userId, fullName).Show();
                }
                else // Фармацевт = Сотрудник
                {
                    new EmployeeForm(userId, fullName).Show();
                }

                this.FormClosed += (s, args) => Application.Exit();
            }
            else
            {
                MessageBox.Show("Неверный email или пароль!", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPassword.Clear();
                txtPassword.Focus();
            }
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {

        }
    }
}