' === Pratica Obrigatoria 1 (ATIVO) ===
Option Explicit

Private Sub UserForm_Initialize()
    cboDestino.Clear
    cboDestino.AddItem "São Paulo - Matriz (SP)"
    cboDestino.AddItem "Rio de Janeiro - Filial (RJ)"
    cboDestino.AddItem "Belo Horizonte - Filial (MG)"
    cboDestino.AddItem "Curitiba - Filial (PR)"
    cboDestino.AddItem "Salvador - Hub Nordeste (BA)"
    cboDestino.ListIndex = 0
    
    Call AtualizarGradeHistorico
End Sub

Private Sub AtualizarGradeHistorico()
    Dim ws As Worksheet
    Dim lngUltimaLinha As Long
    Dim varMatriz As Variant
    Dim i As Long
    Dim curTotal As Currency
    
    Set ws = ThisWorkbook.Worksheets(1)
    lngUltimaLinha = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    lstHistorico.Clear
    
    If lngUltimaLinha >= 2 Then
        varMatriz = ws.Range("A2:D" & lngUltimaLinha).Value
        lstHistorico.List = varMatriz
        
        ' Totalizador do Desafio de Fixação
        curTotal = 0
        For i = 0 To lstHistorico.ListCount - 1
            curTotal = curTotal + CCur(lstHistorico.List(i, 3))
        Next i
        lblTotalDespachado.Caption = "Total Expedido: " & FormatCurrency(curTotal)
    Else
        lblTotalDespachado.Caption = "Nenhum despacho registrado."
    End If
End Sub

Private Sub cmdDespachar_Click()
    Dim ws As Worksheet
    Dim lngLinha As Long
    Dim strDestino As String
    Dim strModalidade As String
    Dim curValor As Currency
    Dim strSeguro As String
    
    Set ws = ThisWorkbook.Worksheets(1)
    
    If cboDestino.Text = "" Then Exit Sub
    If Not IsNumeric(txtValorFrete.Text) Then Exit Sub
    
    strDestino = cboDestino.Text
    curValor = CCur(txtValorFrete.Text)
    
    If optPropria.Value = True Then
        strModalidade = "FROTA PRÓPRIA"
    Else
        strModalidade = "TERCEIRIZADO"
    End If
    
    If chkSeguroEspecial.Value = True Then
        strSeguro = "COM SEGURO AD VALOREM"
    Else
        strSeguro = "SEGURO PADRÃO"
    End If
    
    lngLinha = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1
    ws.Cells(lngLinha, 1).Value = "DSP-" & Format(lngLinha - 1, "000")
    ws.Cells(lngLinha, 2).Value = strDestino
    ws.Cells(lngLinha, 3).Value = strModalidade
    ws.Cells(lngLinha, 4).Value = curValor
    ws.Cells(lngLinha, 5).Value = strSeguro
    ws.Cells(lngLinha, 6).Value = Now
    
    ws.Range("D2:D" & lngLinha).NumberFormat = "R$ #,##0.00"
    ws.Columns("A:F").AutoFit
    
    Call AtualizarGradeHistorico
    txtValorFrete.Text = ""
    txtValorFrete.SetFocus
End Sub

