﻿Imports System
Imports System.Data
Imports System.Data.SqlClient
Partial Class Admin_NewUser
    Inherits System.Web.UI.Page

#Region "Events"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Session("AdminID") Is Nothing Then
            Response.Redirect("AdminLogin.aspx?sesn=expire")
            Exit Sub
        End If
        If Not IsPostBack Then
            fillgrid("")
            fillcombo()
            LoadCategory()
            Call CancelClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel)
            txtName.Text = ""
            txtPassword.Text = ""
            txtName.Enabled = False
            txtPassword.Enabled = False
            ddlSelectMentor.Enabled = False
            rdbstatus.Enabled = False
        End If
    End Sub

    Protected Sub gvAdmin_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvAdmin.PageIndexChanging
        gvAdmin.PageIndex = e.NewPageIndex
        fillgrid("")
        gvAdmin.SelectedIndex = -1
        ClearFields()
        txtName.Enabled = False
        txtPassword.Enabled = False
        ddlSelectMentor.Enabled = False
        Call CancelClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel)
    End Sub

    Protected Sub gvAdmin_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvAdmin.SelectedIndexChanged
        txtkid.Text = gvAdmin.SelectedDataKey.Value
        txtName.Enabled = False
        txtPassword.Enabled = True
        rdbstatus.Enabled = True
        txtPassword.TextMode = TextBoxMode.SingleLine
        txtPassword.Text = CType(gvAdmin.SelectedRow.FindControl("Label1"), Label).Text.ToString
        If gvAdmin.SelectedRow.Cells(6).Text <> "&nbsp;" Then
            SetComboSelected(gvAdmin.SelectedRow.Cells(6).Text, ddlSelectMentor)
            'ddlSelectMentor.Items.FindByValue(gvAdmin.SelectedRow.Cells(6).Text).Selected = True
        Else
            ddlSelectMentor.SelectedIndex = 0
        End If
        txtName.Text = gvAdmin.SelectedRow.Cells(1).Text  'gvAdmin.Rows(gvAdmin.SelectedIndex).Cells(1).Text
        If gvAdmin.SelectedRow.Cells(4).Text = "Active" Then
            rdbstatus.SelectedValue = 1
        Else
            rdbstatus.SelectedValue = 2
        End If
        If gvAdmin.SelectedRow.Cells(1).Text = "esourcing@atcomaart.com" Then
            ddlSelectMentor.Enabled = False
            rdbstatus.Enabled = False
        Else
            ddlSelectMentor.Enabled = True
            rdbstatus.Enabled = True

        End If

        Call GridClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel)
        BtnDelete.Visible = False
    End Sub

    Protected Sub gvAdmin_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvAdmin.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then

            If e.Row.Cells(4).Text = "Y" Then
                e.Row.Cells(4).Text = "Active"
            End If

            If e.Row.Cells(4).Text = "N" Then
                e.Row.Cells(4).Text = "De Active"
                e.Row.Cells(4).ForeColor = Drawing.Color.Red
            End If

            'Dim catins As String = ""
            'catins = ReturnValue("select AdminUser_CategoryId from AdminUser where AdminUser_Kid='" & e.Row.Cells(5).Text.Trim & "'")
            'Dim dk = Split(catins, " - ")
            'Dim i As Integer
            'Dim mycategory As String = ""
            'If catins <> Nothing Then
            '    For i = 0 To dk.Length - 1
            '        mycategory += ReturnValue("select Category_Name from Category_Master where Category_Kid='" & dk(i).ToString & "' and Category_IsDeleted='0'") & "<br/>"
            '    Next
            '    CType(e.Row.Cells(2).FindControl("linkcategory"), Label).Attributes.Add("onmouseover", "fixedtooltip('" & mycategory & "',this,event,'200px');")
            'Else
            '    CType(e.Row.Cells(2).FindControl("linkcategory"), Label).Attributes.Add("onmouseover", "fixedtooltip('No Category Assign.',this,event,'200px');")
            'End If
            'CType(e.Row.Cells(2).FindControl("linkcategory"), Label).Attributes.Add("onmouseout", "delayhidetip();")
        End If
    End Sub

    Protected Sub BtnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        ClearFields()   'Clears the TextFields
        'listcategory.Enabled = True
        txtName.Enabled = True
        txtPassword.Enabled = True
        ddlSelectMentor.Enabled = True
        'rdbstatus.Enabled = True
        gvAdmin.SelectedIndex = -1
        rdbstatus.Enabled = True
        Call AddClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel)
        'fillgrid()
        ScriptManager.GetCurrent(Me).SetFocus(txtName)
    End Sub

    Protected Sub BtnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        Try
            txtkid.Text = NewPrimaryKey(Me)
            If IsAlreadyPresent("SELECT Count(*) FROM AdminUser WHERE (AdminUser_Name = '" + txtName.Text.Trim.ToString + "')") Then
                CreateMessageAlert(Me, "User Already Exist..", "StrKeyVal")
                ClearFields()  'Clear the TextFields
                Exit Sub
            Else
                UpdateData("Insert")   'Inserts the Record
                ClearFields()  'Clear the TextFields
                CreateMessageAlert(Me, "Record Saved Successfully...", "StrKeyVal")             'Display the Message

                fillgrid("")
                fillcombo()
                Call SaveClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel)
                lblMsg.Text = ""
                txtName.Enabled = False
                txtPassword.Enabled = False
                ddlSelectMentor.Enabled = False
                rdbstatus.Enabled = False
                rdbstatus.Items(0).Selected = False
                rdbstatus.Items(1).Selected = False
                'clearselected()
                'listcategory.Enabled = False
                gvAdmin.SelectedIndex = -1
            End If
        Catch ex As Exception

        End Try
    End Sub

    Protected Sub BtnEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            UpdateData("Update")  'Updates the record
            CreateMessageAlert(Me, "Record Modified Successfully...", "StrKeyVal")             'Display the Message
            ClearFields()   'Clear the TextFields
            fillgrid("")
            fillcombo()
            lblMsg.Text = ""
            txtName.Enabled = False
            txtPassword.Enabled = False
            ddlSelectMentor.Enabled = False
            rdbstatus.Enabled = False
            Call EditClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel)
            rdbstatus.Items(0).Selected = False
            rdbstatus.Items(1).Selected = False
            '' clearselected()
            ' listcategory.Enabled = False
            gvAdmin.SelectedIndex = -1
        Catch ex As Exception

        End Try
    End Sub

    Protected Sub BtnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        ClearFields()                                       'Clears the TextFields
        Call fillgrid("")
        gvAdmin.SelectedIndex = -1
        Call CancelClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel)
        rdbstatus.Items(0).Selected = False
        rdbstatus.Items(1).Selected = False
        lblMsg.Text = ""
        txtName.Enabled = False
        txtPassword.Enabled = False
        ddlSelectMentor.Enabled = False
        rdbstatus.Enabled = False
        ' clearselected()
        ' listcategory.Enabled = False
    End Sub

    Protected Sub ddlSelectMentor_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlSelectMentor.SelectedIndexChanged
        If ddlSelectMentor.SelectedIndex > 0 Then
            If ddlSelectMentor.SelectedItem.Text = "esourcing@atcomaart.com" Then
                fillgrid("")
            Else
                fillgrid(ddlSelectMentor.SelectedValue.ToString)
            End If
        Else
            fillgrid("")
        End If
    End Sub

#End Region

#Region "Methods"

    Public Sub LoadCategory()
        Dim dt As DataTable
        dt = ReturnDataTable("Select Category_KId, Category_Name from Category_Master where Category_ParentId ='Root Category' and Category_IsDeleted ='0' order by Category_Name")
        listcategory.DataSource = dt
        listcategory.DataTextField = "Category_Name"
        listcategory.DataValueField = "Category_KId"
        listcategory.DataBind()
        For i As Integer = 0 To listcategory.Items.Count - 1
            listcategory.Items(i).Selected = True
        Next
    End Sub

    Protected Sub fillgrid(ByVal kid As String)
        Try
            Dim dt As DataTable
            gvAdmin.Columns(5).Visible = True
            If kid = "" Then
                dt = ReturnDataTable("SELECT *,CASE WHEN AdminUser_Name = 'esourcing@atcomaart.com' THEN 'Admin' ELSE CASE WHEN AdminUser_ReportingTo = (SELECT  AdminUser_Kid FROM AdminUser WHERE (AdminUser_Name = 'esourcing@atcomaart.com')) THEN 'Mentor' ELSE 'PE' END END AS UserType FROM AdminUser WHERE  AdminUser_IsDeleted = '0' AND AdminUser_Name = 'esourcing@atcomaart.com' OR AdminUser_ReportingTo IN (SELECT	AdminUser_Kid FROM AdminUser WHERE AdminUser_Name = 'esourcing@atcomaart.com') OR AdminUser_ReportingTo IN (SELECT	AdminUser_Kid FROM AdminUser WHERE AdminUser_ReportingTo = AdminUser_ReportingTo)  Order by AdminUser_Name")
            Else
                dt = ReturnDataTable("SELECT   AdminUser.*, 'PE' as UserType FROM AdminUser Where AdminUser_ReportingTo='" + RemoveLiterals(kid) + "' AND AdminUser_IsDeleted='0' AND AdminUser_ActiveFlag='Y' Order by AdminUser_Name ")
            End If

            gvAdmin.DataSource = dt
            gvAdmin.DataBind()
            gvAdmin.Columns(5).Visible = False
            'gvAdmin.Columns(6).Visible = False
        Catch ex As Exception
        End Try
    End Sub

    Protected Sub fillcombo()
        Try
            Dim dt As DataTable
            dt = ReturnDataTable("SELECT * FROM AdminUser WHERE AdminUser_Name = 'esourcing@atcomaart.com'  OR (AdminUser_ReportingTo IN (SELECT AdminUser_Kid FROM AdminUser WHERE AdminUser_Name = 'esourcing@atcomaart.com') AND AdminUser_IsDeleted = '0' AND AdminUser_ActiveFlag = 'Y') Order by AdminUser_Name")
            ddlSelectMentor.DataSource = dt
            ddlSelectMentor.DataTextField = "AdminUser_Name"
            ddlSelectMentor.DataValueField = "AdminUser_Kid"
            ddlSelectMentor.DataBind()
            ddlSelectMentor.Items.Insert(0, New ListItem("Select", "0"))
        Catch ex As Exception
        End Try
    End Sub

    Protected Sub ClearFields()
        txtName.Text = ""
        txtPassword.Text = ""
        ddlSelectMentor.ClearSelection()
    End Sub

    Private Sub SetComboSelected(ByVal value As String, ByVal ddl As DropDownList)
        For i As Integer = 0 To ddl.Items.Count - 1
            If ddl.Items(i).Value = value Then
                ddl.SelectedIndex = i
                Exit Sub
            End If
        Next
    End Sub

    'Protected Sub BtnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    '    Try


    '        'UpdateData("Delete")  'Deletes the record                                               'Execute the Query
    '        CreateMessageAlert(Me, "Record Deleted Successfully...", "StrKeyVal")             'Display the Message
    '        ClearFields()  'Clear the TextFields
    '        fillgrid()
    '        txtName.Enabled = False
    '        txtPassword.Enabled = False
    '        ddlSelectMentor.Enabled = False
    '        ' rdbstatus.Enabled = False
    '        Call DeleteClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel)
    '        '  rdbstatus.Items(0).Selected = False
    '        '  rdbstatus.Items(1).Selected = False
    '        '  clearselected()
    '        '  listcategory.Enabled = False
    '        gvAdmin.SelectedIndex = -1
    '    Catch ex As Exception

    '    End Try
    'End Sub

    Private Sub UpdateData(ByVal strMode As String)
        Dim selcatid As String = ""
        Dim i, j As Integer
        i = listcategory.Items.Count
        For j = 0 To i - 1
            If listcategory.Items(j).Selected = True Then
                selcatid += listcategory.Items(j).Value & " - "
            End If
        Next
        If rdbstatus.SelectedValue = 1 Then
            If (txtPassword.Text.Length < 6) Then
                CreateMessageAlert(Me, "Please Enter Password atleast 6 Character.!", "StrKeyVal")
                Exit Sub
            End If
            Dim cipher As String
            cipher = Encrypt(txtPassword.Text)
            Dim cmd As New Data.SqlClient.SqlCommand()
            Dim sqlcoll As Data.SqlClient.SqlParameterCollection = cmd.Parameters
            sqlcoll.Clear()
            sqlcoll.Add("@AdminUser_Kid", Data.SqlDbType.NVarChar, 20).Value = txtkid.Text.Trim
            sqlcoll.Add("@AdminUser_Code", Data.SqlDbType.NVarChar, 20).Value = Generate_Code("select count(*) from AdminUser_Master where AdminUser_Code='", "AU")
            sqlcoll.Add("@AdminUser_Name", Data.SqlDbType.NVarChar, 200).Value = txtName.Text.Trim
            sqlcoll.Add("@AdminUser_UserTypeId", Data.SqlDbType.NVarChar, 20).Value = "000007?"  'For Admin Only
            sqlcoll.Add("@AdminUser_Password", Data.SqlDbType.NVarChar, 100).Value = cipher.ToString
            If rdbstatus.SelectedValue = "1" Then
                sqlcoll.Add("@AdminUser_ActiveFlag", Data.SqlDbType.NVarChar, 20).Value = "Y"
            ElseIf rdbstatus.SelectedValue = "2" Then
                sqlcoll.Add("@AdminUser_ActiveFlag", Data.SqlDbType.NVarChar, 20).Value = "N"
            End If
            sqlcoll.Add("@AdminUser_Assigned", Data.SqlDbType.NVarChar, 20).Value = "Y"
            sqlcoll.Add("@AdminUser_CategoryId", Data.SqlDbType.NVarChar, selcatid.Length).Value = selcatid

            sqlcoll.Add("@AdminUser_FinancialYearId", Data.SqlDbType.NVarChar, 20).Value = Session("g_FinYear").ToString
            sqlcoll.Add("@AdminUser_CompanyID", Data.SqlDbType.NVarChar, 20).Value = Session("g_Company").ToString
            sqlcoll.Add("@AdminUser_UserID", Data.SqlDbType.NVarChar, 20).Value = Session("g_User").ToString
            If ddlSelectMentor.SelectedIndex > 0 Then
                sqlcoll.Add("@Reporting_To", Data.SqlDbType.NVarChar, 20).Value = ddlSelectMentor.SelectedValue.ToString
            Else
                sqlcoll.Add("@Reporting_To", Data.SqlDbType.NVarChar, 20).Value = System.DBNull.Value
            End If
            sqlcoll.Add("@FormName", Data.SqlDbType.NVarChar, 20).Value = Me.Title.ToString
            sqlcoll.Add("@Mode", Data.SqlDbType.Char, 15).Value = strMode.Trim
            ExecQuery("AdminUser_Mentor_Proc", sqlcoll)
            'CreateMessageAlert(Me, "Record Modified Successfully...", "StrKeyVal")             'Display the Message
        Else
            'Dim dt As DataTable
            'dt = ReturnDataTable("")
            If IsAlreadyPresent("SELECT Count(*) FROM AdminUser WHERE (AdminUser_ReportingTo = '" + txtkid.Text.ToString + "') AND (AdminUser_IsDeleted = N'0') AND (AdminUser_ActiveFlag = N'Y')") Then
                CreateMessageAlert(Me, "Can not De Active Mentor...", "StrKeyVal")
                Exit Sub
            Else
                ExecuteQuery("update adminuser set AdminUser_ActiveFlag='N' where AdminUser_Kid='" & txtkid.Text.Trim & "' ")
            End If

        End If

    End Sub

#End Region

    
End Class
