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

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

        private void LoginButton_Click(object sender, EventArgs e)
        {
            var login = loginTextBox.Text.Trim();
            var password = passwordTextBox.Text.Trim();

            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("Введите логин и пароль.");
                return;
            }

            try
            {
                using var context = new SportShopContext();
                var user = context.Users
                    .Include(u => u.IdRoleNavigation)
                    .FirstOrDefault(u => u.Login == login && u.Password == password);

                if (user == null)
                {
                    MessageBox.Show("Неверный логин или пароль.");
                    return;
                }

                SessionManager.CurrentUser = user;
                var productForm = new ProductListForm();
                productForm.Show();
                Hide();
                productForm.FormClosed += (s, args) =>
                {
                    SessionManager.CurrentUser = null;
                    loginTextBox.Clear();
                    passwordTextBox.Clear();
                    Show();
                };
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка подключения к базе данных: " + ex.Message);
            }
        }

        private void GuestButton_Click(object sender, EventArgs e)
        {
            SessionManager.CurrentUser = null;
            var productForm = new ProductListForm();
            productForm.Show();
            Hide();
            productForm.FormClosed += (s, args) => Show();
        }
    }
}
