Imports System.Web.Configuration
Imports Superbowl.sqlDB
Imports Superbowl.AuditEntity

Partial Public Class CompSetProductDetails
   Inherits System.Web.UI.Page

   Private Shared strPrimaryProdCode As String = "0"
   Private db As New sqlDB
   Private ds As DataSet
   Private dr As DataRow

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      lblMessage.Text = ""

      If Not Page.IsPostBack Then
         WebConfigurationManager.AppSettings("strPage") = "CompSetProductDetails"
         If sqlDB.Nz(WebConfigurationManager.AppSettings("ULEVEL"), 0) <> 5 Then
            btnSave.Enabled = False
         End If
         Try
            strPrimaryProdCode = Nz(Request.QueryString("PID"), "0")
         Catch ex As Exception
            strPrimaryProdCode = "0"
         End Try

         If strPrimaryProdCode <> "0" And strPrimaryProdCode.Length > 0 Then
            'Load existing comp set data
            Try
               LoadCompSetData(strPrimaryProdCode)
            Catch ex As Exception
               lblMessage.Text = "Error loading comp set data: " & ex.Message
            End Try
         Else
            lblLastEdit.Text = "New"
         End If
      End If
   End Sub

   Private Sub LoadCompSetData(ByVal strProdCode As String)
      'Load primary product
      ddlPrimaryProduct.SelectedValue = strProdCode
      ddlPrimaryProduct.Enabled = False 'Cannot change primary product when editing

      'Load comp set name (get from any record, active or inactive)
      Try
         'Get comp set name from any record (prefer active, but get inactive if no active exists)
         Dim dsNameCheck As DataSet = db.doQueryDS("SELECT TOP 1 strCompSetName FROM mstProductCompetitorSet WHERE strPrimaryProdCode = '" & sqlDB.CleanString(strProdCode) & "' ORDER BY blnActive DESC, intPosition ASC")
         If dsNameCheck.Tables(0).Rows.Count > 0 Then
            Dim strName As String = Nz(dsNameCheck.Tables(0).Rows(0)!strCompSetName, "")
            If strName <> "" Then
               txtCompSetName.Text = strName
            Else
               txtCompSetName.Text = strProdCode
            End If
         Else
            txtCompSetName.Text = strProdCode
         End If
      Catch ex As Exception
         txtCompSetName.Text = strProdCode
      End Try

      'Load comp set records (include inactive to get active status)
      ds = db.doQueryDS(db.sql_get_ProductCompetitorSet(strProdCode, True))

      'Load active status from first record (all records should have same status)
      If ds.Tables(0).Rows.Count > 0 Then
         chkActive.Checked = Nz(ds.Tables(0).Rows(0)!blnActive, True)
      Else
         chkActive.Checked = True 'Default to active for new records
      End If

      'First, clear all comp product dropdowns
      Dim ddlCompProducts() As DropDownList = {ddlCompProduct1, ddlCompProduct2, ddlCompProduct3, ddlCompProduct4, ddlCompProduct5,
                                                ddlCompProduct6, ddlCompProduct7, ddlCompProduct8, ddlCompProduct9, ddlCompProduct10}
      For Each ddl As DropDownList In ddlCompProducts
         Try
            If ddl.Items.FindByValue("") IsNot Nothing Then
               ddl.SelectedValue = ""
            Else
               ddl.SelectedIndex = -1
            End If
         Catch ex As Exception
            ddl.SelectedIndex = -1
         End Try
      Next

      If ds.Tables(0).Rows.Count > 0 Then
         Dim intIndex As Integer = 0
         For Each dr In ds.Tables(0).Rows
            'Load all records into dropdowns (active and inactive)
            If intIndex < 10 Then
               Dim strCompCode As String = Nz(dr!strCompProdCode, "")
               If strCompCode <> "" Then
                  Try
                     ddlCompProducts(intIndex).SelectedValue = strCompCode
                     intIndex += 1
                  Catch ex As Exception
                     'Value doesn't exist in dropdown, skip it
                  End Try
               End If
            End If
         Next

         'Get last edit info from first record
         If ds.Tables(0).Rows.Count > 0 Then
            lblLastEdit.Text = Nz(ds.Tables(0).Rows(0)!strLastUser, "unknown") & " - " &
                              SqlDate(Nz(ds.Tables(0).Rows(0)!dtStamp, ""), "d MMMM yyyy HH:mm")
         End If
      End If
   End Sub

   Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
      lblMessage.Text = ""

      'Validation
      If txtCompSetName.Text.Trim.Length = 0 Then
         lblMessage.Text = "Comp Set Name is required."
         Return
      End If

      If ddlPrimaryProduct.SelectedValue = "0" Or ddlPrimaryProduct.SelectedValue = "" Then
         lblMessage.Text = "RGBC Products (Primary Product) is required."
         Return
      End If

      Dim strPrimaryProd As String = ddlPrimaryProduct.SelectedValue
      Dim strCompSetName As String = txtCompSetName.Text.Trim
      Dim strUserName As String = Session.Item("User")
      Dim ddlCompProducts() As DropDownList = {ddlCompProduct1, ddlCompProduct2, ddlCompProduct3, ddlCompProduct4, ddlCompProduct5,
                                                ddlCompProduct6, ddlCompProduct7, ddlCompProduct8, ddlCompProduct9, ddlCompProduct10}

      'Collect selected comp products (excluding empty selections)
      Dim lstCompProducts As New List(Of String)
      For Each ddl As DropDownList In ddlCompProducts
         If ddl.SelectedValue <> "" And ddl.SelectedValue <> "0" Then
            lstCompProducts.Add(ddl.SelectedValue)
         End If
      Next

      'Validation: Max 10 comp products
      If lstCompProducts.Count > 10 Then
         lblMessage.Text = "Maximum of 10 competitive products allowed."
         Return
      End If

      'Validation: No duplicates
      If lstCompProducts.Count <> lstCompProducts.Distinct().Count() Then
         lblMessage.Text = "Duplicate competitive products are not allowed."
         Return
      End If

      'Validation: No self-reference
      If lstCompProducts.Contains(strPrimaryProd) Then
         lblMessage.Text = "Primary product cannot be in its own competitive set."
         Return
      End If

      Try
         'Get existing comp set records for this primary product (include inactive to check for duplicates)
         Dim dsExisting As DataSet = db.doQueryDS(db.sql_get_ProductCompetitorSet(strPrimaryProd, True))
         Dim dictByPosition As New Dictionary(Of Integer, Integer) ' Key: Position, Value: ProductCompetitorSetID
         Dim dictByCompCode As New Dictionary(Of String, Integer) ' Key: CompProdCode, Value: ProductCompetitorSetID (for tracking duplicates)
         Dim listProcessedIDs As New List(Of Integer) ' Track which IDs we've processed

         'Build dictionary by position - prefer active records at each position
         For Each drExisting In dsExisting.Tables(0).Rows
            Dim intExistingPosition As Integer = CInt(drExisting!intPosition)
            Dim intID As Integer = CInt(drExisting!ProductCompetitorSetID)
            Dim blnIsActive As Boolean = Nz(drExisting!blnActive, False)
            
            'If we don't have a record at this position, or if current is active and existing is not, use this one
            If Not dictByPosition.ContainsKey(intExistingPosition) Then
               dictByPosition.Add(intExistingPosition, intID)
            ElseIf blnIsActive Then
               'Check if existing record at this position is inactive
               Dim existingID As Integer = dictByPosition(intExistingPosition)
               For Each drCheck In dsExisting.Tables(0).Rows
                  If CInt(drCheck!ProductCompetitorSetID) = existingID AndAlso Not Nz(drCheck!blnActive, False) Then
                     dictByPosition(intExistingPosition) = intID
                     Exit For
                  End If
               Next
            End If
         Next

         'Process each selected comp product by position
         Dim intPosition As Integer = 1
         For Each strCompProd As String In lstCompProducts
            If dictByPosition.ContainsKey(intPosition) Then
               'Update existing record at this position with new comp product code
               Dim intID As Integer = dictByPosition(intPosition)
               sqlDB.doQueryDS(db.sql_update_ProductCompetitorSet(intID, strCompProd, intPosition, strCompSetName, chkActive.Checked, strUserName))
               listProcessedIDs.Add(intID)
               dictByPosition.Remove(intPosition) ' Mark as processed
            Else
               'No record at this position - check if this comp product exists at another position
               Dim intExistingID As Integer = -1
               For Each drExisting In dsExisting.Tables(0).Rows
                  If drExisting!strCompProdCode.ToString() = strCompProd Then
                     intExistingID = CInt(drExisting!ProductCompetitorSetID)
                     Exit For
                  End If
               Next
               
               If intExistingID > 0 Then
                  'Update existing record (move it to this position)
                  sqlDB.doQueryDS(db.sql_update_ProductCompetitorSet(intExistingID, strCompProd, intPosition, strCompSetName, chkActive.Checked, strUserName))
                  listProcessedIDs.Add(intExistingID)
               Else
                  'Insert new record with current active status
                  Dim strInsertSQL As String = "INSERT INTO mstProductCompetitorSet (strPrimaryProdCode, strCompProdCode, intPosition, strCompSetName, blnActive, strLastUser, dtStamp) " & _
                                               "VALUES ('" & sqlDB.CleanString(strPrimaryProd) & "', '" & sqlDB.CleanString(strCompProd) & "', " & intPosition & ", '" & sqlDB.CleanString(strCompSetName) & "', " & CInt(chkActive.Checked) & ", '" & sqlDB.CleanString(strUserName) & "', '" & sqlDB.dbDate() & "')"
                  sqlDB.doQueryDS(strInsertSQL)
               End If
            End If
            intPosition += 1
         Next

         'Soft delete any existing records at positions that are no longer selected
         For Each kvp As KeyValuePair(Of Integer, Integer) In dictByPosition
            sqlDB.doQueryDS(db.sql_delete_ProductCompetitorSet(kvp.Value, strUserName))
         Next

         'Update comp set name for all records (including inactive ones, in case they get reactivated)
         sqlDB.doQueryDS(db.sql_update_ProductCompetitorSetName(strPrimaryProd, strCompSetName, strUserName))

         'Soft delete any duplicate records for comp products we just processed
         'This ensures we only have one record per comp product (the one at the correct position)
         'For each comp product in the current selection, keep only the record at the correct position
         Dim intPosForCleanup As Integer = 1
         For Each strCompProd As String In lstCompProducts
            'Get the record at this position for this comp product
            Dim dsKeepRecord As DataSet = db.doQueryDS("SELECT TOP 1 ProductCompetitorSetID FROM mstProductCompetitorSet WHERE strPrimaryProdCode = '" & sqlDB.CleanString(strPrimaryProd) & "' AND strCompProdCode = '" & sqlDB.CleanString(strCompProd) & "' AND intPosition = " & intPosForCleanup & " ORDER BY blnActive DESC")
            If dsKeepRecord.Tables(0).Rows.Count > 0 Then
               Dim intKeepID As Integer = CInt(dsKeepRecord.Tables(0).Rows(0)!ProductCompetitorSetID)
               'Soft delete all other records for this comp product (at different positions or duplicates)
               sqlDB.doQueryDS("UPDATE mstProductCompetitorSet SET blnActive = 0, strLastUser = '" & sqlDB.CleanString(strUserName) & "', dtStamp = '" & sqlDB.dbDate() & "' WHERE strPrimaryProdCode = '" & sqlDB.CleanString(strPrimaryProd) & "' AND strCompProdCode = '" & sqlDB.CleanString(strCompProd) & "' AND ProductCompetitorSetID <> " & intKeepID)
            End If
            intPosForCleanup += 1
         Next

         'Success message
         lblMessage.Text = "Comp Set Products saved successfully."
         lblLastEdit.Text = strUserName & " - " & Date.Now.ToString("d MMMM yyyy HH:mm")

         'Reload data to show updated info
         LoadCompSetData(strPrimaryProd)

      Catch ex As Exception
         lblMessage.Text = "Error saving comp set: " & ex.Message & "<BR>" & ex.StackTrace
      End Try
   End Sub

   Protected Sub btnClose_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClose.Click
      Response.Redirect("CompSetProductList.aspx")
   End Sub

   'Note: SelectedIndexChanged handler removed - no AutoPostBack to preserve comp product selections
   'Comp set name is updated client-side via JavaScript when primary product changes
End Class

