'Option Explicit On  
'Option Strict On
'Option Compare Text

Imports System.Web.Security
Imports System.Data.SqlClient

Public Class Login
    Inherits System.Web.UI.Page
    Protected WithEvents txtUserName As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtPassword As System.Web.UI.WebControls.TextBox
    Protected WithEvents rfvUserName As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents rfvPassword As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents lblMsg As System.Web.UI.WebControls.Label
    Protected WithEvents btnLogin As System.Web.UI.WebControls.Button

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region
	Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        'txtUserName.
	End Sub

	Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        Dim cn As SqlConnection
        Dim ds As New DataSet()
        Dim da As New SqlDataAdapter()
		Dim sConStr As String = ConfigurationSettings.AppSettings("sConnection")
		Try
			cn = New SqlConnection(sConStr)
		Catch ex As Exception
			With lblMsg
				.Text = "Unable to open database connection" & vbCrLf & ex.ToString
				.ToolTip = .Text
				.ForeColor = Color.Red
			End With
			Exit Sub
		End Try

		If cn.State = ConnectionState.Closed Then cn.Open()
		'Only the [admin] login goes in admin module
        'all other logins get to the teachers area, but teachers login is checked from as_Teachers table
        
        Select Case (txtUserName.Text.ToLower)
            Case "admin"
                Dim cmd As New SqlCommand("Select * from as_AdminUsers where " & _
                   " userid='" & txtUserName.Text.Replace("'", "''") & "'" & _
                          " AND password='" & txtPassword.Text.Replace("'", "''") & "'", cn)
                Dim sValue As String = Convert.ToString(cmd.ExecuteScalar())

                'Response.Write(sql)
                'Response.Write(ds.Tables(0).Rows.Count)
                If sValue = Trim(txtUserName.Text) Then
                    'If ds.Tables(0).Rows.Count > 0 Then
                    'If ds.Tables(0).Rows(0)("permfor") = "Full" Then
                    Session.Add("LoginType", "administrator")
                    Session.Add("ClassPageID", "-1")
                    Session.Add("TeacherLoginID", "admin")
                    FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False)
                    Response.Redirect("../Admins")
                    'Response.Redirect("default.aspx")
                    'if no redirection page name available then go to main admin page
                    'If (FormsAuthentication.GetRedirectUrl(txtUserName.Text, False) = String.Empty) Then
                    'Response.Redirect("default.aspx")
                    'ElseIf ds.Tables(0).Rows(0)("permfor") = "School" Then
                    'Session.Add("LoginType", "scholl")
                    'Response.Redirect("http://galaxy/allsaints/Admin/MgrContent.aspx?Level=1&ID=268")
                    'End If
                Else
                    With lblMsg
                        .Text = "Invalid username or password !"
                        .ToolTip = .Text
                        .ForeColor = Color.Red
                    End With
                End If

            Case "ptoadmin"
                Dim cmd As New SqlCommand("Select * from as_AdminUsers where " & _
                   " userid='" & txtUserName.Text.Replace("'", "''") & "'" & _
                          " AND password='" & txtPassword.Text.Replace("'", "''") & "'", cn)
                Dim sValue As String = Convert.ToString(cmd.ExecuteScalar())

                'Response.Write(sql)
                'Response.Write(ds.Tables(0).Rows.Count)
                If sValue = Trim(txtUserName.Text) Then
                    'If ds.Tables(0).Rows.Count > 0 Then
                    'If ds.Tables(0).Rows(0)("permfor") = "Full" Then
                    Session.Add("LoginType", "ptoadmin")
                    FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False)
                    Response.Redirect("../Admins")
                    'Response.Redirect("default.aspx")
                    'if no redirection page name available then go to main admin page
                    'If (FormsAuthentication.GetRedirectUrl(txtUserName.Text, False) = String.Empty) Then
                    'Response.Redirect("default.aspx")
                    'ElseIf ds.Tables(0).Rows(0)("permfor") = "School" Then
                    'Session.Add("LoginType", "scholl")
                    'Response.Redirect("http://galaxy/allsaints/Admin/MgrContent.aspx?Level=1&ID=268")
                    'End If
                Else
                    With lblMsg
                        .Text = "Invalid username or password !"
                        .ToolTip = .Text
                        .ForeColor = Color.Red
                    End With
                End If

            Case Else
                'Else
                'before checking the teachers's login there is on login of Scheduler Manager in config.web
                Dim id As String = ConfigurationSettings.AppSettings("Schedulers_ID").ToString
                Dim pass As String = ConfigurationSettings.AppSettings("Schedulers_Pass").ToString
                If txtUserName.Text.ToLower.Trim = "kwhelan" Then
                    If txtPassword.Text.Trim = "123" Then
                        Session.Add("LoginType", "schedulers")
                        Session.Add("LoginID", "kwhelan")
                        FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False)
                        Response.Redirect("../Schedulers/default.aspx")
                    End If
                Else
                    'check for the teachers' login
                    Dim cmdTeacher As New SqlCommand("Select LoginName,ClassPageID from as_Teachers " & _
                     " inner join as_Teachers_Classes ON (as_Teachers.LoginName = as_Teachers_Classes.TeacherLoginName) where(" & _
                     " LoginName='" & txtUserName.Text.Replace("'", "''") & "'" & _
                     " AND Password='" & txtPassword.Text.Replace("'", "''") & "')", cn)

                    'testing area
                    Dim str As String = cmdTeacher.ToString()
                    'end of testing area

                    If cn.State = ConnectionState.Closed Then cn.Open()
                    Dim tdr As SqlDataReader = cmdTeacher.ExecuteReader

                    Try
                        tdr.Read()
                        Dim sValue As String = tdr.Item("LoginName").ToString

                        'if the given name of teacher is the found in the database then set the session
                        If Trim(sValue) = Trim(txtUserName.Text) Then
                            Session.Add("LoginType", "teacher")
                            Session.Add("ClassPageID", tdr.Item("ClassPageID"))
                            Session.Add("TeacherLoginID", sValue)
                            tdr.Close()
                            FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False)
                            'Always go to the Teacher Home Page
                            'If (FormsAuthentication.GetRedirectUrl(txtUserName.Text, False) = String.Empty) Then
                            Response.Redirect("../Teachers/default.aspx")
                            'End If
                        Else
                            tdr.Close()
                            With lblMsg
                                .Text = "Invalid username or password !"
                                .ToolTip = .Text
                                .ForeColor = Color.Red
                            End With
                        End If
                    Catch ex As Exception
                        With lblMsg
                            .Text = "Invalid username or password !"
                            .ToolTip = .Text
                            .ForeColor = Color.Red
                        End With
                    End Try
                End If

                ''End If

        End Select
        '<SAQIB ADDED LINES>
        If cn.State = ConnectionState.Open Then cn.Close()
        '<SAQIB ADDED LINES/>
        cn.Close()
	End Sub

    Private Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Unload
        '<SAQIB ADDED LINES>
        'If .State = ConnectionState.Open Then conn.Close()
        '<SAQIB ADDED LINES/>

    End Sub
End Class
