using Microsoft.Data.SqlClient;
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;

namespace WMS_project
{
    public partial class forgotPassword : Form
    {
        private SqlConnection connection;
        private SqlCommand command;
        private SqlDataReader reader;

        public forgotPassword()
        {
            InitializeComponent();
            InitializeDatabaseConnection();
            usernameTextBox.TextChanged += UsernameTextBox_TextChanged;
            buttonRetrievePassword.Click += ButtonRetrievePassword_Click;
            buttonClose.Click += ButtonClose_Click;
        }
        private void InitializeDatabaseConnection()
        {
            string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\WMSDBAPP\DB\WMSDB.mdf;Integrated Security=True;";
            connection = new SqlConnection(connectionString);
        }

        private void ButtonRetrievePassword_Click(object sender, EventArgs e)
        {
            string username = usernameTextBox.Text.Trim();

            if (string.IsNullOrEmpty(username))
            {
                MessageBox.Show("Please enter a username.");
                return;
            }

            string query = "SELECT Password FROM UserInfo WHERE Username = @Username";

            try
            {
                connection.Open();

                command = new SqlCommand(query, connection);
                command.Parameters.AddWithValue("@Username", username);

                reader = command.ExecuteReader();

                if (reader.Read())
                {
                    string password = reader["Password"].ToString();
                    passwordLabel.Text = $"{username}: {password}";
                }
                else
                {
                    passwordLabel.Text = "Username not found.";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
                if (connection.State == ConnectionState.Open)
                    connection.Close();
            }
        }


        private void ButtonClose_Click(object sender, EventArgs e)
        {
            this.Close(); // Close the form
        }

        private void UsernameTextBox_TextChanged(object sender, EventArgs e)
        {
            passwordLabel.Text = ""; // Clear password result label
        }
    }
}
