Imports System.Web.Configuration
Imports Superbowl.sqlDB
Imports Superbowl.AuditEntity

Partial Public Class CustomerDetails
   Inherits System.Web.UI.Page

   Private strCustomerNo As String = "0"
   'Private Shared strFilter As String = "refSegmentID = 0"
   Private db As New sqlDB
   Private ds As DataSet
   Private dr As DataRow
   Private aeFormer, aeLatter As AuditEntity

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      lblMessage.Text = ""
      'sdsChannel.FilterExpression = strFilter

      If Not Page.IsPostBack Then
         WebConfigurationManager.AppSettings("strPage") = "CustomerDetails"
         If WebConfigurationManager.AppSettings("ULEVEL") <> 5 Then
            btnSave.Enabled = False
         End If
         Try
            strCustomerNo = Nz(Request.QueryString("CID"), "")
         Catch ex As Exception
            strCustomerNo = "0"
         End Try

         If strCustomerNo <> "0" And strCustomerNo.Length > 0 Then
            'load controls				
            Try
               dr = db.GetRow(db.sql_get_Customer(strCustomerNo))

               txtCustomerNo.Text = strCustomerNo
               txtCustomerNo.ReadOnly = True
               strCustomerName.Text = Nz(dr!strCustomerName, "")

               'strFilter = "refSegmentID = " & Nz(dr!refSegmentID, 0) & " OR refSegmentID = 0 OR ChannelID = " & dr!refChannelID
               'sdsChannel.FilterExpression = strFilter

               strSnellChannel.Text = Nz(dr!strSnellChannel, "")
               strSnellcwsireg.Text = Nz(dr!strSnellcwsireg, "")
               strSnellgrading.Text = Nz(dr!strSnellgrading, "")
               strSnellrepno.Text = Nz(dr!strSnellrepno, "")
               strSnellsupergroup.Text = Nz(dr!strSnellsupergroup, "")
               If strSnellsupergroup.Text <> "" Then
                  lblSnellsupergroupName.Text = Nz(dr!strSnellsupergroupName, "<div align=center><img src='redExclamation24.png'/></div>")
                  'If Nz(dr!strSnellsupergroupName, "") = "" Then sqlDB.WriteLog("Superbowl", "Customer Details [" & strCustomerNo & "]", "Snell Supergroup description was not found: ID = '" & dr!strSnellsupergroup & "'")
               Else
                  lblSnellsupergroupName.Text = Nz(dr!strSnellsupergroupName, "")
               End If

               'try catch doesn't work for render-time errors like !strSnellArea = "TNC", but "TNC" isn't in the ddlSnellArea
               ddlBranch.SelectedValue = Nz(dr!refBranchID, 0)
               ddlType1.SelectedValue = Nz(dr!refType1ID, 0)
               ddlType2.SelectedValue = Nz(dr!refType2ID, 0)
               ddlChannelSegment.SelectedValue = Nz(dr!refChannelSegmentID, 0)
               ddlKAG.SelectedValue = Nz(dr!refKeyAccount_GroupID, 0)

               If Not ddlSnellArea.Items.FindByValue(Nz(dr!strSnellArea, 0)) Is Nothing Then
                  ddlSnellArea.SelectedValue = Nz(dr!strSnellArea, "")
               End If

               ddlRep.SelectedValue = Nz(dr!refRepID, "")
               ddlRepLux.SelectedValue = Nz(dr!refRepLuxID, "")
               ddlRepBB.SelectedValue = Nz(dr!refRepBBID, "")
               ddlRepDlx.SelectedValue = Nz(dr!refRepDlxID, "")

               txtCountry.Text = Nz(dr!strCountry, "")
               ddlCountry.SelectedValue = Nz(dr!strCountry, "- Select -")
               
               chkPromotionalAccount.Checked = dr!blnPromotionalAccounts
               chkActive.Checked = dr!blnActive
               lblLastEdit.Text = Nz(dr!strLastUser, "unknown") & " - " & SqlDate(Nz(dr!dtStamp, ""), "d MMMM yyyy HH:mm")

            Catch ex As IndexOutOfRangeException                'dr = ds.tables(0).rows(0) doesn't exist
               lblMessage.Text = "Customer, <font color=black>" & strCustomerNo & "</font>, was not found!"
            End Try
         Else
            txtCustomerNo.ReadOnly = False
         End If

      End If

   End Sub

   Private Sub CustomerDetails_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete

   End Sub

   Protected Sub txtCustomerNo_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles txtCustomerNo.TextChanged
      If db.CountRows("SELECT * FROM mstCustomer WHERE strCustomerNo = '" & sqlDB.CleanString(txtCustomerNo.Text.Trim) & "' ") > 0 Then
         Response.Redirect("CustomerDetails.aspx?CID=" & sqlDB.CleanString(txtCustomerNo.Text.Trim))
      Else
         'If strCustomerName.Text.Length = 0 Then
         '  strCustomerName.Text = txtCustomerNo.Text.Trim & " "
         'End If
         strCustomerName.Focus()
      End If
   End Sub

   Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click

      lblMessage.Text = ""
      Dim sql As String = ""

      strCustomerNo = Nz(Request.QueryString("CID"), "")

      dr = db.GetRow(db.sql_get_Customer(strCustomerNo))
      'v.1.2.4
      If Not dr Is Nothing Then
         aeFormer = New AuditEntity(dr, "mstCustomer")
      End If

      If txtCustomerNo.Text.Trim.Length = 0 Then lblMessage.Text &= "<BR>Customer Number Required"
      If strCustomerName.Text.Trim.Length = 0 Then lblMessage.Text &= "<BR>Customer Name Required"
      If ddlBranch.SelectedIndex < 1 Then lblMessage.Text &= "<BR>Branch Required"
      If ddlChannelSegment.SelectedIndex < 1 Then lblMessage.Text &= "<BR>Channel Segment Required"
      If ddlRep.SelectedIndex < 1 Then lblMessage.Text &= "<BR>Sales Rep Required"
      If ddlType1.SelectedIndex < 1 Then lblMessage.Text &= "<BR>Type 1 Required"
      If ddlType2.SelectedIndex < 1 Then lblMessage.Text &= "<BR>Type 2 Required"
      If txtCountry.Text.Trim() = "" Then lblMessage.Text &= "<BR>Country required.<BR>"
      'If db.CountRows(db.sql_get_Customer(strCustomerNo, strCustomerName.Text)) > 0 Then lblMessage.Text &= "<BR> Customer already exists"

      If Not lblMessage.Text.Length > 0 Then          'redundant validation check	
         Try

            '1- Update/insert into MST
            If strCustomerNo <> "0" And strCustomerNo.Length > 0 Then 'Update
               Try                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             'ddlType1.SelectedValue, ddlType2.SelectedValue
                  sql = db.sql_update_Customer(txtCustomerNo.Text.Trim(), strCustomerName.Text, strSnellChannel.Text, ddlSnellArea.SelectedValue, strSnellcwsireg.Text, strSnellrepno.Text, strSnellsupergroup.Text, strSnellgrading.Text, ddlRep.SelectedValue, ddlRepBB.SelectedValue, ddlRepDlx.SelectedValue, ddlRepLux.SelectedValue, ddlBranch.SelectedValue, ddlKAG.SelectedValue, ddlChannelSegment.SelectedValue, CInt(chkActive.Checked), CInt(chkPromotionalAccount.Checked), ddlType1.SelectedValue, ddlType2.SelectedValue, txtCountry.Text, Session.Item("User"))
                  sqlDB.doQueryDS(sql)
               Catch ex As Exception
                  lblMessage.Text = "<BR>Update Failed.<BR><BR>" & ex.Message
                  Throw (New Exception("Could not write to master tables"))
               End Try
               Try
                  'v.1.2.4
                  dr = db.GetRow(db.sql_get_Customer(strCustomerNo))
                  aeLatter = New AuditEntity(dr, "mstCustomer")
                  AuditEntity.Audit(aeFormer, aeLatter, Session.Item("User")) 'v1.4.5 - 20160913 - Fixed logged In user & savings (i.e use session instead) - maanie
               Catch ex As Exception
                  sqlDB.WriteLog("Superbowl", "Audit: Customer Details [" & strCustomerNo & "]", ex.Message & "<BR>" & ex.StackTrace)
               End Try

            Else 'Insert
               Try                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ', ddlType1.SelectedValue, ddlType2.SelectedValue
                  sql = db.sql_insert_Customer(txtCustomerNo.Text.Trim(), strCustomerName.Text, strSnellChannel.Text, ddlSnellArea.SelectedValue, strSnellcwsireg.Text, strSnellrepno.Text, strSnellsupergroup.Text, strSnellgrading.Text, ddlRep.SelectedValue, ddlRepBB.SelectedValue, ddlRepDlx.SelectedValue, ddlRepLux.SelectedValue, ddlBranch.SelectedValue, ddlKAG.SelectedValue, ddlChannelSegment.SelectedValue, CInt(chkActive.Checked), CInt(chkPromotionalAccount.Checked), ddlType1.SelectedValue, ddlType2.SelectedValue, txtCountry.Text, Session.Item("User"))
                  sqlDB.doQueryDS(sql)
                  strCustomerNo = sqlDB.CleanString(txtCustomerNo.Text)

               Catch ex As Exception
                  lblMessage.Text = "<BR>Insert Failed.<BR><BR>" & ex.Message
                  Throw (New Exception("Could not write to datawarehouse"))
               End Try
            End If

            '2-Update/insert into DW
            Dim Keys As String() = {"strCustomerNo"}
            Dim Values As String() = {strCustomerNo}

            ds = sqlDB.getDW("dwdCustomer", Keys, Values)
            If ds.Tables(0).Rows.Count > 0 Then  'update dw
               Dim fields As String = ""
               fields = sqlDB.Update_OuterDwd(sqlDB.doQueryDS(db.sql_get_Customer_dw(strCustomerNo)).Tables(0))  'build up the "SET bla = $bla

               sql = db.sql_update_Customer_dw(strCustomerNo, fields)
               sqlDB.doQueryDS(sql)
            Else  'insert dw
               sql = db.sql_insert_Customer_dw(strCustomerNo)
               sqlDB.doQueryDS(sql)
            End If

            'Response.Redirect("CustomerList.aspx")
            Response.Redirect("CustomerDetails.aspx?CID=" & strCustomerNo)
         Catch ex As Exception
            lblMessage.Text &= "<BR>" & ex.Message & ":<BR>" & sql
         End Try
      End If
   End Sub

   Protected Sub btnClose_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClose.Click
      Response.Redirect("CustomerList.aspx")
   End Sub

   Protected Sub ddlCountry_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlCountry.SelectedIndexChanged
      If ddlCountry.SelectedIndex > 0 Then txtCountry.Text = ddlCountry.SelectedValue Else txtCountry.Text = ""
   End Sub
End Class