using System;
using UserAuthApp.BLL;  // Reference to Business Logic Layer

namespace UserAuthApp.Web
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // If user is already logged in, send them to the Dashboard
            if (Session["Username"] != null)
            {
                Response.Redirect("Dashboard.aspx");
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            try
            {
                // ── STEP A: Get the username and password from the form ──
                string username = txtUsername.Text.Trim();
                string password = txtPassword.Text;

                // ── STEP B: Call the Business Logic Layer to authenticate ──
                UserBLL userBLL = new UserBLL();
                int result = userBLL.LoginUser(username, password);

                // ── STEP C: Handle the result ──
                if (result == 1)
                {
                    // SUCCESS — Save username in Session (keeps user logged in)
                    Session["Username"] = username;

                    // Redirect to the protected Dashboard page
                    Response.Redirect("Dashboard.aspx");
                }
                else
                {
                    // FAILED — Show error message
                    lblMessage.Text = "✗ Invalid username or password. Please try again.";
                    lblMessage.CssClass = "message error";
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = "✗ Error: " + ex.Message;
                lblMessage.CssClass = "message error";
            }
        }
    }
}
