Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Net.Mail
Imports System.Math
Imports System.IO
Imports System.EnterpriseServices
Imports System.Drawing
'Imports System.Web.HttpWriter
Imports System.Web.Security
Imports System.Resources.Tools
Imports System.Configuration
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Data.Sql
Imports System.Text

Partial Class Buyer_BuyerLogin
    Inherits System.Web.UI.Page
    Dim query As String
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            txtName.Text = ""
            txtpwd.Text = ""
        End If
    End Sub
    'Protected Sub ImgLogin_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImgLogin.Click

    'End Sub

    Private Function RetriveBuyerId(ByVal AdminId As String) As String
        Dim BuyerId As String = ""
        query = "select BuyerRegister_Kid from BuyerRegister where BuyerRegister_AdminUserId='" & AdminId & "'"
        Dim cmd As New SqlCommand
        Dim sqlcon As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
        cmd.Connection = sqlcon
        cmd.CommandText = query
        Dim dr As SqlDataReader
        sqlcon.Open()
        dr = cmd.ExecuteReader
        Do While dr.Read
            BuyerId = dr(0)
        Loop
        Return BuyerId
    End Function

    Protected Sub btnLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        Dim flag As Boolean = False
        Dim adminid As String = ""
        Dim cmd As New SqlCommand
        Dim cipher As String

        cipher = Encrypt(txtpwd.Text)
        'query = "select * from AdminUser where AdminUser_Name=@uname and AdminUser_Password=@pwd"
        'query = "SELECT BuyerRegister_EmailId, BuyerRegister_AdminUserId FROM dbo.BuyerRegister WHERE (BuyerRegister_EmailId = N'pankaj@atco.com') AND (BuyerRegister_AdminUserId = N'p')"
        query = "select * from BuyerRegister where (BuyerRegister_EmailId=@uname) and (BuyerRegister_pwd=@pwd) and (BuyerRegister_Verification = @verify) and (BuyerRegister_Status=@status)"

        Dim uname As String
        uname = txtName.Text
        If uname.Contains("'") Or uname.Contains("--") Or uname.Contains(";") Or uname.Contains(" ") Or uname.Contains("*") Or uname.Contains("where") Or uname.Contains("=") Then
            lblError.Visible = True
            lblError.Text = "Invalid UserName or Password."
            Exit Sub
        End If

        Dim ds_log As DataSet
        ds_log = AdminUserLog(uname, "Buyer")
        'By Pankaj
        ''If ds_log.Tables(0).Rows.Count <> 0 Then
        ''    If (ds_log.Tables(0).Rows(0).Item(5).ToString = 0) Then
        ''        lblError.Visible = True
        ''        lblError.Text = "You are already logged in"
        ''        Exit Sub
        ''    End If
        ''End If
        If ds_log.Tables(0).Rows.Count <> 0 Then
            If (ds_log.Tables(0).Rows(0).Item(5).ToString = 0) And ds_log.Tables(0).Rows(0).Item(4).ToString <> Request.UserHostAddress Then
                lblError.Visible = True
                lblError.Text = "You are already logged in"
                Exit Sub
            ElseIf (ds_log.Tables(0).Rows(0).Item(5).ToString = 0) And ds_log.Tables(0).Rows(0).Item(4).ToString = Request.UserHostAddress Then
                ' Dim nextlogintime As String = ReturnValue("SELECT  TOP (1) AdminUserLog_LoginDateTime AS NextLogin  FROM AdminUserLog  WHERE  AdminUserLog_Status = '0' AND AdminUserLog_Kid = '" & RemoveLiterals(ds.Tables(0).Rows(0).Item(0).ToString) & "' AND AdminUserLog_UserName ='" & ds.Tables(0).Rows(0).Item(1).ToString & "' ORDER BY NextLogin desc")
                Dim logout As Date
                Dim timedef As Long
                timedef = DateDiff(DateInterval.Hour, Convert.ToDateTime(ds_log.Tables(0).Rows(0).Item(2).ToString), DateTime.Now)
                If timedef >= 8 Then
                    logout = DateAdd(DateInterval.Minute, 50, Convert.ToDateTime(ds_log.Tables(0).Rows(0).Item(2).ToString))
                ElseIf timedef >= 4 Then
                    logout = DateAdd(DateInterval.Hour, 1, Convert.ToDateTime(ds_log.Tables(0).Rows(0).Item(2).ToString))
                ElseIf timedef >= 2 Then
                    logout = DateAdd(DateInterval.Minute, 50, Convert.ToDateTime(ds_log.Tables(0).Rows(0).Item(2).ToString))
                Else
                    logout = DateAdd(DateInterval.Second, -20, DateTime.Now)
                End If
                ExecuteQuery("Update AdminUserLog set AdminUserLog_Status =1,AdminUserLog_LogoutDateTime='" & logout & "',AdminUserLog_ClientIP='" & Request.UserHostAddress & "' where AdminUserLog_Kid='" & RemoveLiterals(ds_log.Tables(0).Rows(0).Item(0).ToString) & "'")
            End If
        End If
        cmd.Parameters.AddWithValue("@uname", Trim(txtName.Text.ToString()))
        cmd.Parameters.AddWithValue("@pwd", cipher)
        cmd.Parameters.AddWithValue("@verify", "Verified")
        cmd.Parameters.AddWithValue("@status", "Y")
        Dim sqlcon As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
        cmd.Connection = sqlcon
        cmd.CommandText = query
        Dim dr As SqlDataReader
        sqlcon.Open()
        dr = cmd.ExecuteReader
        If dr.Read Then

            Dim key As String = RemoveLiterals(NewPrimaryKey(Me).ToString.Trim)
            InsertAdminUserLog(key, txtName.Text, Request.UserHostAddress, 0, "Buyer", "BuyerLogin", "Insert")

            Session("LogKid") = key
            Session("LogName") = txtName.Text
            '  Do While dr.Read
            'DBUserId is nothing but AdminId
            'Session("DBUserID") = dr(0)
            'Session("ComanyId") = dr(8)
            'Session("UserId") = dr(9)
            'Session("BuyId") = RetriveBuyerId(Session("DBUserId"))
            Session("UserId") = dr(0)
            Session("BuyId") = dr(0)
            Session("Byrusername") = dr(2).ToString
            flag = True
            Session("g_Company") = "00006Z4"
            Session("g_FinYear") = "000010N"
            ' Loop
        End If

        sqlcon.Close()
        If flag = True Then
            Dim con1 As New SqlConnection
            con1.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")

            con1.Open()
            Dim str As String = "delete  FROM ShopCart where ShopCart_BuyerUserId ='" & Session("BuyId") & "'"
            Dim da As New SqlDataAdapter
            cmd = New SqlCommand(str, con1)
            cmd.ExecuteNonQuery()
            con1.Close()
            cmd.Dispose()
            da.Dispose()
            con1.Dispose()
            If Session("Checkstatus") = "ShopCart" Then

                Dim shoptabel As New DataTable
                shoptabel = Session("ShopTabel")
                Dim shopi As Integer
                Dim shoplen As Integer = shoptabel.Rows.Count
                For shopi = 0 To shoplen - 1

                    ShopCartProcedure(shoptabel.Rows(shopi).Item(0).ToString)
                Next
                Session("Checkstatus") = Nothing
                Response.Redirect("ShopCart.aspx")
            ElseIf Session("Checkstatus") = "WishLsit" Then

                Dim Wishtabel As New DataTable
                Wishtabel = Session("WishTabel")
                Dim wishi As Integer
                Dim len As Integer = Wishtabel.Rows.Count
                For wishi = 0 To len - 1

                    WishListProcedure(Wishtabel.Rows(wishi).Item(0).ToString)
                Next
                'sqlcon.Close()
                Session("Checkstatus") = Nothing
                Response.Redirect("WishList.aspx")
            Else
                '    Response.Redirect("newBuyerSearch.aspx")
                Response.Redirect("~/Buyer/newBuyerSearch.aspx")
            End If

        Else
            lblError.Visible = True
            lblError.Text = "<img alt='' src='" & Page.ResolveUrl("~/Images/javascripts.gif") & "' &nbsp; /> Plz Enter Correct UserId and Password."

        End If
    End Sub

    Protected Function ShopCartProcedure(ByVal prodid As String)
        Try
            Dim strr As String = "select Product_AtcoPrice from product_Information where Product_Approved='Y' and Product_Kid='" & prodid & "'"

            'Dim strr As String = "select * from TempShopCart"
            Dim con As New SqlConnection
            con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")

            con.Open()
            'dr = cmd.ExecuteReader
            Dim da1 As New SqlDataAdapter(strr, con)
            Dim ds1 As New DataSet
            ' Dim i As Integer = 0
            da1.Fill(ds1)

            Dim shopid As String = NewPrimaryKey(Me.Page)
            shopid = RemoveLiterals(shopid)
            Dim shopCode As String = Generate_Code("select count(*) from ShopCart where ShopCart_Code='", "SC")
            Dim con1 As New SqlConnection                        'Define connection variable for connecting to SQL-Server
            con1.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")    'Read the ConnectionString from web.config File
            Dim cmd As New SqlCommand
            con1.Open()
            Dim sqlcol As Data.SqlClient.SqlParameterCollection = cmd.Parameters
            sqlcol.Add("@ShopCart_Kid", SqlDbType.NVarChar, 10).Value = shopid.ToString.Trim
            sqlcol.Add("@ShopCart_Code", SqlDbType.NVarChar, 25).Value = shopCode.Trim
            sqlcol.Add("@ShopCart_ProductId", SqlDbType.NVarChar, 10).Value = prodid.Trim
            sqlcol.Add("@ShopCart_BuyerUserId", SqlDbType.NVarChar, 25).Value = Session("BuyId")
            sqlcol.Add("@ShopCart_Quantity", SqlDbType.Int).Value = 1
            sqlcol.Add("@ShopCart_SpecialPrice", SqlDbType.Decimal, 18).Value = ds1.Tables(0).Rows(0).Item(0).ToString
            sqlcol.Add("@ShopCart_FinancialYearId", SqlDbType.NVarChar, 10).Value = Session("g_FinYear")
            sqlcol.Add("@ShopCart_CompanyId", SqlDbType.NVarChar, 10).Value = Session("companyId")
            sqlcol.Add("@ShopCart_UserId", SqlDbType.NVarChar, 10).Value = Session("UserId")
            sqlcol.Add("@FormName", SqlDbType.NVarChar, 50).Value = Me.Page.ToString
            sqlcol.Add("@Mode", SqlDbType.VarChar, 10).Value = "Insert"
            ExecQuery("ShopCart_Proc", sqlcol).StartsWith("True")
            sqlcol = Nothing
            cmd = Nothing
            'Return True

        Catch ex As Exception
            ex.Message.ToString()
        End Try
    End Function

    Protected Function WishListProcedure(ByVal prodid As String)
        Try
            Dim wishlistid As String = NewPrimaryKey(Me.Page)
            wishlistid = RemoveLiterals(wishlistid)
            Dim wishlistCode As String = Generate_Code("select count(*) from AddWishList where AddWishList_Code='", "WL")
            Dim con As New SqlConnection                        'Define connection variable for connecting to SQL-Server
            con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")    'Read the ConnectionString from web.config File
            Dim cmd As New SqlCommand
            con.Open()
            Dim str As String = "select AddWishList_Code from AddWishList where AddWishList_ProductId='" & prodid & "'"
            Dim da As New SqlDataAdapter(str, con)
            Dim ds As New DataSet
            da.Fill(ds)
            If ds.Tables(0).Rows.Count > 0 Then
                Return False
            Else
                Dim sqlcol As Data.SqlClient.SqlParameterCollection = cmd.Parameters
                sqlcol.Add("@AddWishList_Kid", SqlDbType.NVarChar, 10).Value = wishlistid.Trim
                sqlcol.Add("@AddWishList_Code", SqlDbType.NVarChar, 25).Value = wishlistCode.Trim
                sqlcol.Add("@AddWishList_ProductId", SqlDbType.NVarChar, 10).Value = prodid.Trim
                sqlcol.Add("@AddWishList_BuyerUserId", SqlDbType.NVarChar, 25).Value = Session("BuyId")
                sqlcol.Add("@AddWishList_FinancialYearId", SqlDbType.NVarChar, 10).Value = Session("g_FinYear")
                sqlcol.Add("@AddWishList_CompanyId", SqlDbType.NVarChar, 10).Value = Session("companyId")
                sqlcol.Add("@AddWishList_UserId", SqlDbType.NVarChar, 10).Value = Session("UserId")
                sqlcol.Add("@FormName", SqlDbType.NVarChar, 50).Value = Me.Page.ToString
                sqlcol.Add("@Mode", SqlDbType.VarChar, 10).Value = "Insert"
                ExecQuery("AddWishList_Proc", sqlcol).StartsWith("True")
                sqlcol = Nothing
                cmd = Nothing
                ' Dim gvRow As GridViewRow
                Return True
            End If
        Catch ex As Exception
            ex.Message.ToString()
        End Try
    End Function

    'Protected Sub lnkbtnRegister_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkbtnRegister.Click
    '    Response.Redirect("Register.aspx")
    'End Sub
End Class
