using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using MySql.Data.MySqlClient;
using BCrypt.Net;

namespace SkyTeam
{
    public partial class AdminLoginPage : Page
    {
        public AdminLoginPage() => InitializeComponent();

        private void AdminLogin_Click(object sender, RoutedEventArgs e)
        {
            string query = "SELECT Id, PasswortHash FROM users WHERE Email = @email AND Vorname = @user AND Rolle = @role";

            try
            {
                using (MySqlConnection conn = new MySqlConnection(DatenbankServices.GetConnection()))
                {
                    conn.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, conn))
                    {
                        cmd.Parameters.AddWithValue("@email", AdminEmailBox.Text);
                        cmd.Parameters.AddWithValue("@user", AdminUserBox.Text);
                        cmd.Parameters.AddWithValue("@role", AdminRoleBox.Text);

                        using (MySqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                string storedHash = reader.GetString("PasswortHash");
                                int dbId = reader.GetInt32("Id");

                                if (BCrypt.Net.BCrypt.Verify(AdminPassBox.Password, storedHash))
                                {
                                    SessionManager.CurrentUserId = dbId;
                                    SessionManager.CurrentUserName = AdminUserBox.Text;

                                    MessageBox.Show("Admin-Zugriff gewährt!");
                                    NavigationService.Navigate(new AdminDashboard());
                                }
                                else
                                {
                                    MessageBox.Show("Ungültiges Passwort.");
                                }
                            }
                            else
                            {
                                MessageBox.Show("Kein Admin mit diesen Daten gefunden.");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler: " + ex.Message);
            }
        }

        private void Back_Click(object sender, RoutedEventArgs e) => NavigationService.Navigate(new LogInPage());
    }
}