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 Npgsql;

namespace PM11
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void buttonEnter(object sender, EventArgs e)
        {
            Program.login = textBox1.Text;
            string password = textBox2.Text;

            if (string.IsNullOrEmpty(Program.login) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("Заполните логин или пароль", "Ошибка");
                return;
            }

            try
            {
                using (var conn = new NpgsqlConnection(Program.connString))
                {
                    conn.Open();

                    string sql = "select id, role from users where login = @login and password_hash = @password";
                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("login", Program.login);
                        cmd.Parameters.AddWithValue("password", password);

                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                Program.user_id = Convert.ToInt32(reader["id"]);
                                Program.role_id = Convert.ToInt32(reader["role"]);

                                Form2 form2 = new Form2(Program.user_id, Program.connString);
                                form2.Show();
                                this.Hide();
                            }
                            else
                            {
                                MessageBox.Show("Неверный логин или пароль", "Ошибка");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка подключения к БД:\n" + ex.Message, "Ошибка");
            }
        }
    }
}
