Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.IO
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Partial Class Admin_category_description
    Inherits System.Web.UI.Page
    Dim str, str1 As String
    Dim slc1 = "Select Date"
    'Dim slc2 = "MM"
    Dim slc3 = "Select Year"
    Dim slc4 = "Select Country"
    Dim strcon As String = ConfigurationSettings.AppSettings.Item("ConnectionString")
    Dim con As New SqlConnection(strcon)
    Dim cmd As New SqlCommand()
    Dim dr As SqlDataReader
    Shared Category(10) As String
    Shared i As Integer
    Shared CatID1 As String
    Shared CatID2 As String
    Shared CatID3 As String
    Shared c As String
    Dim sproduct As Integer
    Shared dt1 As DataTable
    Dim categories As DataTable
    Dim count As Integer
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
        'Put user code to initialize the page here
        Try
            If Session("AdminID") Is Nothing Then
                Response.Redirect("AdminLogin.aspx?sesn=expire")
                Exit Sub
            End If
            Dim parentid As String
            If Not Me.Page.IsPostBack Then
                If Session("AdminID") = Nothing Then
                    Response.Redirect("AdminLogin.aspx")
                End If
                ' gvProducts.Visible = False
                '------getting the value of subcatid from the getparents function that declared in this form--------
                btnSave.Enabled = False
                btnUpdate.Enabled = False
                btnDelete.Enabled = False
                sproduct = 0
                g_FinYear = Session("g_FinYear").ToString()
                g_Company = Session("g_Company").ToString()
                g_User = Session("g_User").ToString()
                parentid = Request.QueryString("subcatid")
                If parentid = Nothing Or parentid = "Root" Then
                    parentid = "Root Category"
                Else
                    parentid = Request.QueryString("subcatid")
                End If
                i = 0
                LoadCategory(parentid)
                c = ""
                cbosubCategory1.Visible = False
                cbosubCategory2.Visible = False
                btnDelete.Attributes.Add("onclick", "javascript:return confirm('Are you sure want to delete?');")
                ' txtcertification.Visible = False
            End If

            cboCategory.Visible = True
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Sub
    Private Sub cboCategory_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCategory.SelectedIndexChanged
        ' gvProducts.Visible = False
        Try
            If cboCategory.SelectedItem.Text = "Select Category" Then
                ' Panel1.Visible = True
                Label2.Visible = True
                Label2.Text = "Please Select the Category"
                '  Spcat.InnerText = cboCategory.SelectedItem.Text + " > "
                '  SpSubCat1.Visible = False
                ''extrs code
                cbosubCategory1.Visible = False
                cbosubCategory2.Visible = False
                Label15.Visible = False
            Else
                Session("lastsubcategory") = ""
                Session("lastsubcategory") = cboCategory.SelectedItem.Value
                CatID1 = cboCategory.SelectedItem.Value
                CatID2 = ""
                CatID3 = ""
                getparents(cboCategory.SelectedItem.Value)
                LoadSubCategory1(cboCategory.SelectedItem.Value)
                getdesc(CatID1)
                c = CatID1
            End If
            If cboCategory.SelectedIndex = 0 Then
                setbutton(False)
            End If
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Sub
    Protected Sub getdesc(ByVal catid As String)
        Try
            TextArea.Text = ""
            btnSave.Enabled = False
            btnUpdate.Enabled = False
            btnDelete.Enabled = False
            Dim strqry As String = "select categorydescription_description from categorydescription where categorydescription_isdeleted='0' and categorydescription_categoryid='" & catid & "'"
            Dim con As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
            Dim cmd As New SqlCommand(strqry, con)
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Open()
            Dim desc As String = Convert.ToString(cmd.ExecuteScalar)
            con.Close()
            If desc = "" Or desc = "&nbsp;" Then
                btnSave.Enabled = True
                btnUpdate.Enabled = False
                btnDelete.Enabled = False

            Else
                btnUpdate.Enabled = True
                btnDelete.Enabled = True
                btnSave.Enabled = False
                TextArea.Text = desc
            End If
            'Return desc.Trim
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Sub


    Private Sub cbosubCategory1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbosubCategory1.SelectedIndexChanged
        Try
            ' gvProducts.Visible = False
            Session("lastsubcategory") = cbosubCategory1.SelectedItem.Value
            CatID2 = cbosubCategory1.SelectedItem.Value
            CatID1 = ""
            CatID3 = ""
            getparents(cbosubCategory1.SelectedItem.Value)
            LoadSubCategory2(cbosubCategory1.SelectedItem.Value)
            '   SpSubCat.InnerText = cbosubCategory1.SelectedItem.Text + " > "
            '  Session("subcategory1") = SpSubCat.InnerText
            'Response.Write(Session("subcategory1"))
            '   SpSubCat.Visible = True
            '   SpSubCat1.Visible = True
            ''extra code
            cbosubCategory1.Visible = True
            ''cbosubCategory2.Visible = True
            '   SpSubCat1.InnerText = "Select Sub Category"

            getdesc(CatID2)
            c = CatID2
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Sub
    Private Sub cbosubCategory2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbosubCategory2.SelectedIndexChanged
        Try
            'gvProducts.Visible = False
            Session("lastsubcategory") = cbosubCategory2.SelectedItem.Value
            CatID3 = cbosubCategory2.SelectedItem.Value
            CatID1 = ""
            CatID2 = ""
            getparents(cbosubCategory2.SelectedItem.Value)
            LoadSubCategory3(cbosubCategory2.SelectedItem.Value)

            getdesc(CatID3)
            c = CatID3
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Sub
    Private Sub LoadSubCategory3(ByVal intId As String)
        Try
            Dim strsql As String
            'strsql = "select cat_id as id,catname as Name from categorymaster where parent_id=" & intId & "order by catname asc"
            strsql = "SELECT Category_Kid as id, Category_Name as Name FROM Category_Master WHERE Category_ParentId = '" & intId & "' ORDER BY Category_Name"
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Open()

            Dim cmd As New SqlCommand(strsql, con)
            Dim mReader As SqlDataReader
            mReader = cmd.ExecuteReader
            cboCategory.Items.Clear()
            cboCategory.Items.Add(New ListItem("Select Subcategory", "-4"))
            If mReader.Read Then
                cboCategory.Items.Add(New ListItem(mReader("Name"), mReader("id")))
                While mReader.Read
                    cboCategory.Items.Add(New ListItem(mReader("Name"), mReader("id")))
                End While
                Label14.Visible = True
                Label15.Visible = False
                Label16.Visible = False
                cbosubCategory1.Visible = False
                cbosubCategory2.Visible = False
                cboCategory.ForeColor = Drawing.Color.Red
                cbosubCategory1.ForeColor = Drawing.Color.Black
                cbosubCategory2.ForeColor = Drawing.Color.Black
                Label14.Text = "Select the next level"
            Else
                Label14.Visible = False
                Label15.Visible = False
                Label16.Visible = False
                Label2.Visible = True
                Label2.Text = "Last category selected."
                Session("CategoryId") = intId

                'Response.Redirect("Product_Information.aspx?CatID=" & intId)
            End If
            mReader.Close()

        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Sub
    Private Sub LoadCategory(ByVal parentid As String)
        Try
            Dim strsql As String
            'strsql = "select cat_id as id,catname as Name from categorymaster where parent_id=" & parentid & "order by catname asc"
            strsql = "SELECT Category_Kid as id, Category_Name as Name FROM Category_Master WHERE Category_ParentId = '" & parentid & "' ORDER BY Category_Name"
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Open()
            Dim cmd As New SqlCommand(strsql, con)
            Dim mReader As SqlDataReader
            mReader = cmd.ExecuteReader
            cboCategory.Items.Clear()
            cboCategory.Items.Add(New ListItem("Select Category", "-1"))
            If mReader.Read Then
                cboCategory.Items.Add(New ListItem(mReader("Name"), mReader("id")))
                While mReader.Read
                    cboCategory.Items.Add(New ListItem(mReader("Name"), mReader("id")))
                End While
                Label14.Visible = True
                Label15.Visible = False
                Label16.Visible = False

                cboCategory.ForeColor = Drawing.Color.Red
                cbosubCategory1.ForeColor = Drawing.Color.Black
                cbosubCategory2.ForeColor = Drawing.Color.Black

                Label14.Text = "Select the category"
            Else
                Label14.Visible = False
                Label15.Visible = False
                Label16.Visible = False
                Label2.Visible = True
                Label2.Text = "Last category selected."
                Session("CategoryId") = parentid

                'Response.Redirect("Product_Information.aspx?CatID =" & parentid)
            End If
            mReader.Close()


        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Sub
    Private Sub LoadSubCategory1(ByVal intId As String)
        Try
            Dim strsql As String
            'strsql = "Select cat_id as id,catname as Name from categorymaster where parent_id=" & intId & "order by catname asc"
            strsql = "SELECT Category_Kid as id, Category_Name as Name FROM Category_Master WHERE Category_ParentId = '" & intId & "' ORDER BY Category_Name"
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Open()

            Dim cmd As New SqlCommand(strsql, con)
            Dim mReader As SqlDataReader
            mReader = cmd.ExecuteReader
            cbosubCategory1.Items.Clear()
            cbosubCategory1.Items.Add(New ListItem("Select Subcategory", "-2"))
            If mReader.Read Then
                cbosubCategory1.Items.Add(New ListItem(mReader("Name"), mReader("id")))
                While mReader.Read
                    cbosubCategory1.Items.Add(New ListItem(mReader("Name"), mReader("id")))
                End While
                Label14.Visible = False
                Label15.Visible = True
                Label16.Visible = False
                cboCategory.ForeColor = Drawing.Color.Black
                cbosubCategory1.ForeColor = Drawing.Color.Red
                cbosubCategory2.ForeColor = Drawing.Color.Black
                cbosubCategory1.Visible = True
                cbosubCategory2.Visible = False
                Label15.Text = "Select the next level"
            Else
                'Response.Write("check")
                cbosubCategory1.Visible = False
                cbosubCategory2.Visible = False
                Label14.Visible = False
                Label15.Visible = False
                Label16.Visible = False
                Label2.Visible = True
                Label2.Text = "Last category selected."
                Session("CategoryId") = intId

                'Response.Redirect("Product_Information.aspx?CatID =" & intId)
            End If
            mReader.Close()

        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Sub
    Private Sub LoadSubCategory2(ByVal intId As String)
        Try
            Dim strsql As String
            'strsql = "select cat_id as id,catname as Name from categorymaster where parent_id=" & intId & "order by catname asc"
            strsql = "SELECT Category_Kid as id, Category_Name as Name FROM Category_Master WHERE Category_ParentId = '" & intId & "' ORDER BY Category_Name"
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Open()

            Dim cmd As New SqlCommand(strsql, con)
            Dim mReader As SqlDataReader
            mReader = cmd.ExecuteReader
            cbosubCategory2.Items.Clear()
            cbosubCategory2.Items.Add(New ListItem("Select Subcategory", "-3"))
            If mReader.Read Then
                cbosubCategory2.Items.Add(New ListItem(mReader("Name"), mReader("id")))
                While mReader.Read
                    cbosubCategory2.Items.Add(New ListItem(mReader("Name"), mReader("id")))
                End While
                Label14.Visible = False
                Label15.Visible = False
                Label16.Visible = True
                cboCategory.ForeColor = Drawing.Color.Black
                cbosubCategory1.ForeColor = Drawing.Color.Black
                cbosubCategory2.ForeColor = Drawing.Color.Red
                Label16.Text = "Select the next level"
                cbosubCategory2.Visible = True
            Else
                cbosubCategory2.Visible = False
                Label14.Visible = False
                Label15.Visible = False
                Label16.Visible = False
                Label2.Visible = True
                Label2.Text = "Last category selected."
                Session("CategoryId") = intId

                'Response.Redirect("Product_Information.aspx?CatID =" & intId)
            End If
            mReader.Close()

        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try

    End Sub
    Private Function getparents(ByVal i As String) As String
        Try
            Dim strsql As String
            'strsql = "select parent_id ,catname as Name from categorymaster where cat_id=" & i
            strsql = "SELECT Category_ParentId, Category_Name FROM Category_Master WHERE Category_Kid = '" & i & "'"
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Open()
            Dim cmd As New SqlCommand(strsql, con)
            Dim dr As SqlDataReader
            dr = cmd.ExecuteReader
            Dim j As String
            Dim flag As Boolean = False
            If dr.Read Then
                j = dr(0)
                'Response.Write(j)
                flag = True
            Else
                'Response.Write("not")
            End If

            If flag = True Then
                ''If j = 0 Then
                ''Exit Function
                ''ElseIf j <> 0 Then
                TextArea.Text = ""
                str1 = dr(1) & " > " & str1


                'str = "<a href=../ProductDetails/prodinfo.aspx?subcatid=" & dr(0) & ">" & dr(1) & "</a>" & " > " & str
                str = "<a href=./category-description.aspx?subcatid=" & dr(0) & ">" & dr(1) & "</a>" & " > " & str
                getparents(j)
                ''End If
            End If
            dr.Close()
            con.Close()
            Label13.Text = str
            Session("categorylevel") = Nothing
            Session("categorylevel") = str1
            Session("Category") = str1

        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Function
    Public Sub FillCategoryName(ByVal Catid As String)
        Try
            Dim dt As DataTable
            dt = ReturnDataTable("Select * From Category_Master Where Category_Kid ='" & Catid & "' and Category_Isdeleted = '0' ") 'and Category_CompanyId ='" & g_Company & "'
            Dim ParentId As String
            ParentId = dt.Rows(0).Item(3).ToString()
            If ParentId = "Root Category" Then
                'Label1.Text += dt.Rows(0).Item(2).ToString()
                'Dim CategoryName(10) As String
                Dim j As Integer
                Category(i) = dt.Rows(0).Item(2).ToString() & "  >  "
                'Array.Reverse(Category)
                For j = 0 To i
                    '  lblError.Text += Category(i)
                    i = i - 1
                Next
                Exit Sub
            Else
                Category(i) = dt.Rows(0).Item(2).ToString() & "  >  "
                i = i + 1
                'Label1.Text += dt.Rows(0).Item(2).ToString() & "  >  "
                FillCategoryName(dt.Rows(0).Item(3).ToString())
            End If
            'GridView1.DataSource = dt
            'GridView1.DataBind()
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try

    End Sub

    Public Function NewPrimaryKey1(ByVal aspxpage As System.Web.UI.UserControl) As String
        Try
            NewPrimaryKey1 = ""

            Dim mycon As New SqlConnection()
            mycon.ConnectionString = ConfigurationManager.AppSettings("ConnectionString")     'Read the ConnectionString from web.config File
            mycon.Open()
            Dim myCommand As New SqlCommand("New_Kid", mycon)
            myCommand.CommandType = CommandType.StoredProcedure
            Dim retValParam As New SqlParameter("@sKey", SqlDbType.Char, 7)
            retValParam.Direction = ParameterDirection.Output
            retValParam.IsNullable = True
            retValParam.Size = 7
            myCommand.Parameters.Add(retValParam)
            Dim reader As SqlDataReader = myCommand.ExecuteReader()
            NewPrimaryKey1 = retValParam.Value.ToString

            myCommand.Dispose()
            If Not reader.IsClosed Then reader.Close()
            If mycon.State = ConnectionState.Open Then mycon.Close()

            'CreateMessageAlert(Me, Ex.Message, "StrKeyVal")
            NewPrimaryKey1 = ""
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Function

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Try
            If insertdata("insert", c) = True Then
                showmessage("Record saved successfully", lblerror)
                TextArea.Text = ""
                setbutton(False)
            End If
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Sub

    Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        Try
            If insertdata("update", c) = True Then
                showmessage("Record updated sucessfully", lblerror)
                TextArea.Text = ""
                setbutton(False)
            End If
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Sub
    Protected Sub setbutton(ByVal action As Boolean)
        btnSave.Enabled = action
        btnUpdate.Enabled = action
        btnDelete.Enabled = action
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Try
            If insertdata("delete", c) = True Then
                showmessage("Record deleted successfully", lblerror)
                TextArea.Text = ""
                setbutton(False)
            End If
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Sub
    Protected Function insertdata(ByVal mode As String, ByVal catid As String) As Boolean
        Try
            Dim flag As Boolean = False
            Dim con As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
            Dim cmd As New SqlCommand("CategoryDescription_Proc", con)
            cmd.CommandType = CommandType.StoredProcedure
            Dim code As String = ""
            Dim kid As String = ""
            Dim noofsubcategory As Integer = 0
            Dim desc As String
            If mode <> "insert" Then
                Dim dt As DataTable = getTable("select * from categorydescription where categorydescription_categoryid='" & catid & "' and categorydescription_isdeleted='0'", "tbl")
                kid = dt.Rows(0)("categorydescription_kid")
                code = dt.Rows(0)("categorydescription_code")
                noofsubcategory = Convert.ToInt32(dt.Rows(0)("categorydescription_noofsubcategory"))
                'desc = dt.Rows(0)("categorydescription_description")
            Else
                kid = RemoveLiterals(NewPrimaryKey(Me))
                GenerateCode(code)
                ' desc = RemoveLiterals(textarea.Text.Trim)
                noofsubcategory = returnintegervalue("select count(*) from category_master where category_parentid='" & catid & "' and category_isdeleted='0'")
            End If
            cmd.Parameters.Add("@CategoryDescription_Kid", SqlDbType.NVarChar, 10).Value = kid
            cmd.Parameters.Add("@CategoryDescription_Code", SqlDbType.NVarChar, 25).Value = code
            cmd.Parameters.Add("@CategoryDescription_CategoryId", SqlDbType.NVarChar, 10).Value = RemoveLiterals(catid)
            cmd.Parameters.Add("@CategoryDescription_Description", SqlDbType.NVarChar, 2000).Value = TextArea.Text
            cmd.Parameters.Add("@CategoryDescription_NoOfSubCategory", SqlDbType.Int, 8).Value = noofsubcategory
            cmd.Parameters.Add("@CategoryDescription_FinancialYearId", SqlDbType.NVarChar, 10).Value = Session("g_FinYear")
            cmd.Parameters.Add("@CategoryDescription_CompanyId", SqlDbType.NVarChar, 10).Value = Session("g_company")
            cmd.Parameters.Add("@CategoryDescription_UserId", SqlDbType.NVarChar, 10).Value = Session("g_user")
            cmd.Parameters.Add("@Formname", SqlDbType.NVarChar, 50).Value = Me.Title
            cmd.Parameters.Add("@Mode", SqlDbType.NVarChar, 10).Value = mode
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            flag = True
            Return flag
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Function

    Protected Function returnintegervalue(ByVal strqry As String) As Integer
        Try
            Dim con As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
            Dim cmd As New SqlCommand(strqry, con)
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            con.Open()
            Dim i As Integer = Convert.ToInt32(cmd.ExecuteScalar())
            con.Close()
            Return i
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "strkeyval")
        End Try
    End Function

    Protected Sub GenerateCode(ByRef code As String)
        Try
            Dim i As String
            Dim qry As String

            i = "1"
            i = Format(Val(i), "000")
            While True
                code = "GDC" & "/" & Year(Date.Today) & "/" & Format(Month(Date.Today), "00") & "/" & Day(Date.Today) & "/" & i
                qry = "select count(*) from categorydescription where categorydescription_Code='" & code & "'"
                If IsAlreadyPresent(qry) Then
                    i = Val(i) + 1
                    i = Format(Val(i), "000")
                Else
                    Exit Sub
                End If
            End While
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub
End Class
