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

namespace _0503NeshinaRogova
{
    public partial class Form1 : Form
    {
        private Random rand = new Random();
        private int escapeCount = 0;
        private const int MAX_ESCAPES = 3; 
        private Timer flashTimer;
        private Color[] epilepticColors = {
            Color.Red, Color.Lime, Color.Blue, Color.Yellow,
            Color.Magenta, Color.Cyan, Color.White, Color.Orange,
            Color.Purple, Color.HotPink
        };

        public Form1()
        {
            InitializeComponent();
            this.FormBorderStyle = FormBorderStyle.SizableToolWindow;
            this.StartPosition = FormStartPosition.Manual;
            this.Location = new Point(100, 100);
            this.button1.MouseEnter += Button1_MouseEnter;
            this.button1.MouseHover += Button1_MouseHover;
            this.button1.Click += Button1_Click;
            flashTimer = new Timer();
            flashTimer.Interval = 60; 
            flashTimer.Tick += FlashTimer_Tick;
            flashTimer.Start();
        }

        private void FlashTimer_Tick(object sender, EventArgs e)
        {
            Color randomColor = epilepticColors[rand.Next(epilepticColors.Length)];
            this.BackColor = randomColor;
            if (rand.Next(0, 3) == 0)
            {
                this.label1.ForeColor = Color.Black;
                this.label2.ForeColor = Color.White;
                this.label3.ForeColor = Color.Yellow;
            }
            else
            {
                this.label1.ForeColor = Color.White;
                this.label2.ForeColor = Color.Black;
                this.label3.ForeColor = Color.Red;
            }
        }

        private void Button1_MouseEnter(object sender, EventArgs e)
        {
            if (escapeCount < MAX_ESCAPES)
            {
                MoveButtonRandomly();
                escapeCount++;
                if (escapeCount == 1) this.button1.Text = "Не догонишь!";
                else if (escapeCount == 2) this.button1.Text = "Мимо!";
                else if (escapeCount == 3) this.button1.Text = "Ха-ха-ха!";
                else if (escapeCount == 4) this.button1.Text = "Последний рывок!";
                else this.button1.Text = "Войти";
            }
            else
            {
                this.button1.Text = "Ну всё, лови!";
                this.button1.BackColor = Color.Green; 
            }
        }

        private void Button1_MouseHover(object sender, EventArgs e)
        {
            if (escapeCount < MAX_ESCAPES)
            {
                MoveButtonRandomly();
            }
        }

        private void MoveButtonRandomly()
        {
            int maxX = this.ClientSize.Width - this.button1.Width;
            int maxY = this.ClientSize.Height - this.button1.Height;
            int newX = rand.Next(0, Math.Max(10, maxX));
            int newY = rand.Next(0, Math.Max(10, maxY));
            this.button1.Location = new Point(newX, newY);
            this.button1.Width = rand.Next(30, 120);
            this.button1.Height = rand.Next(20, 60);
            this.button1.BackColor = epilepticColors[rand.Next(epilepticColors.Length)];
            this.button1.ForeColor = Color.Black;
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            flashTimer.Stop();
            this.BackColor = Color.White;
            string login = tbLogin.Text.Trim();
            string password = tbPass.Text;

            if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password))
            {
                MessageBox.Show("Серьезно? Поля пустые!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                flashTimer.Start();
                return;
            }

            string connectionString = "Server=cfif31.ru;Port=3306;Database=ISPr25-21_NeshinaPV_1003;Uid=ISPr25-21_NeshinaPV;Pwd=ISPr25-21_NeshinaPV;Charset=utf8mb4;";
            string query = "SELECT user_id, type_id FROM users WHERE login = @login AND password = @password";

            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, conn))
                    {
                        cmd.Parameters.AddWithValue("@login", login);
                        cmd.Parameters.AddWithValue("@password", password);
                        using (MySqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                int currentUserId = reader.GetInt32("user_id");
                                int userRole = reader.GetInt32("type_id");
                                Form nextForm = null;

                                if (userRole == 1) nextForm = new AdminForm(currentUserId);
                                else if (userRole == 2) nextForm = new MasterForm(currentUserId);
                                else if (userRole == 4) nextForm = new ClientForm(currentUserId);
                                else if (userRole == 3) nextForm = new OperatorForm(currentUserId);
                                else
                                {
                                    MessageBox.Show("Роль не найдена. Ты призрак?", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    flashTimer.Start();
                                    return;
                                }

                                if (nextForm != null)
                                {
                                    nextForm.Show();
                                    this.Hide();
                                    tbLogin.Clear();
                                    tbPass.Clear();
                                    escapeCount = 0;
                                    this.button1.Visible = true;
                                    flashTimer.Start();
                                }
                            }
                            else
                            {
                                MessageBox.Show("Неверный логин/пароль! Жаль, что ты всё-таки поймал кнопку.", "Ошибка входа", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                tbPass.Clear();
                                tbPass.Focus();
                                flashTimer.Start();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("База данных упала: " + ex.Message, "Критическая ошибка", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                flashTimer.Start();
            }
        }
    }
}