' ============================================================
' Module Name: Master_246
' Module Desc: T3 master data management (246)
' Module Methods:
'   - Worksheet_Change
'   - Validate
' ============================================================

' ============================================================
' Event Handlers
' ============================================================
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim HasHeaderEdit As Boolean: HasHeaderEdit = CheckHeaderEdit(Me, Target)
    If HasHeaderEdit = True Then Exit Sub

    Application.EnableEvents = False
    On Error GoTo Finally

    ' === Column C changes: Create D column dropdown ===
    If Target.Column = 3 And Target.Row >= 7 Then
        Dim cell As Range
        For Each cell In Target
            If Trim(cell.Value) = "" Then
                Call ClearDataRow(Me, cell.Row)
            Else
                Call BuildDisplayDropdown(Me, cell.Row)
            End If
        Next
    End If

    ' === Column G changes: Fill E column ===
    If Target.Column = 7 And Target.Row >= 7 Then
        Dim cellG As Range
        For Each cellG In Target
            Dim displayValue As String: displayValue = Trim(cellG.Value)
            If displayValue <> "" Then
                cellG.Value = GetCode(displayValue)
            End If
        Next
    End If

    Application.EnableEvents = True
    Exit Sub

Finally:
    HandleError "Worksheet_Change"
    Application.EnableEvents = True
End Sub

' Prevent insert/delete row in header area
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
    Dim sheetConfDict As Object: Set sheetConfDict = GetSheetConfig()
    Dim sheetConf As Object: Set sheetConf = sheetConfDict(Me.CodeName)
    Dim filterRow As Long: filterRow = sheetConf("FilterRow")

    If Target.Row < filterRow + 1 Then
        Cancel = True
        MsgBox "Cannot insert or delete row in header area.", vbExclamation
    End If
End Sub

'
Public Sub Validate(ws As Worksheet, ByVal rowNum As Long, ByVal lastDataRow As Long)
    On Error GoTo ErrHandler

    Dim engine As ValidationRuleEngine: Set engine = New ValidationRuleEngine
    With engine
        .AddRequired "C"
        .AddChar "C", 3
        .AddAlphanumeric "C"
        .AddDuplicate "C"
        .AddRequired "D"
        .AddVarchar "D", 80
        .AddVarchar "E", 80
        .AddVarchar "F", 80
        .AddCheck01 "G"
        .AddRequired "H"
        .AddNumber "H", 6
        .AddRequired "I"
        .AddNumber "I", 6
    End With

    Call engine.ValidateRow(ws, rowNum, lastDataRow)

    Exit Sub

ErrHandler:
    SetLastErrorMsg Err.Description
End Sub