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

Sub ExportarLoteFiscalCSV()
    Dim fso As Object
    Dim arqTexto As Object
    Dim ws As Worksheet
    Dim strCaminhoBase As String
    Dim strPastaMes As String
    Dim strNomeArquivo As String
    Dim strCaminhoCompleto As String
    Dim lngUltimaLinha As Long
    Dim i As Long
    Dim strLinhaCSV As String
    
    Set ws = ThisWorkbook.Worksheets(1)
    lngUltimaLinha = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    If lngUltimaLinha < 2 Then Exit Sub
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    strCaminhoBase = "C:\FastLog_Exportacoes"
    strPastaMes = strCaminhoBase & "\" & Format(Date, "yyyy-mm")
    
    If Not fso.FolderExists(strCaminhoBase) Then fso.CreateFolder strCaminhoBase
    If Not fso.FolderExists(strPastaMes) Then fso.CreateFolder strPastaMes
    
    strNomeArquivo = "MDFE_LOTE_" & Format(Now, "yyyymmdd_hhnnss") & ".csv"
    strCaminhoCompleto = strPastaMes & "\" & strNomeArquivo
    
    Set arqTexto = fso.CreateTextFile(strCaminhoCompleto, True)
    arqTexto.WriteLine "ID_MANIFESTO;PLACA_VEICULO;MOTORISTA;VALOR_FRETE;DATA_EMISSAO"
    
    For i = 2 To lngUltimaLinha
        strLinhaCSV = ws.Cells(i, 1).Value & ";" & _
                      ws.Cells(i, 2).Value & ";" & _
                      ws.Cells(i, 3).Value & ";" & _
                      Replace(FormatNumber(ws.Cells(i, 4).Value, 2), ".", "") & ";" & _
                      Format(ws.Cells(i, 5).Value, "yyyy-mm-dd hh:nn:ss")
                      
        arqTexto.WriteLine strLinhaCSV
    Next i
    
    arqTexto.Close
    
    MsgBox "Lote exportado com sucesso para: " & strNomeArquivo, vbInformation, "FSO Sucesso"
End Sub

' Desafio de Fixação: Backup Automático
Sub RealizarBackupDiario()
    Dim fso As Object
    Dim strPastaBackup As String
    Dim strArquivoDestino As String
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    strPastaBackup = "C:\FastLog_Backups"
    
    If Not fso.FolderExists(strPastaBackup) Then fso.CreateFolder strPastaBackup
    
    strArquivoDestino = strPastaBackup & "\Backup_FastLog_" & Format(Now, "yyyymmdd_hhnnss") & ".xlsm"
    fso.CopyFile ThisWorkbook.FullName, strArquivoDestino, True
    
    MsgBox "Backup de contingência concluído com sucesso!" & vbCrLf & strArquivoDestino, _
           vbInformation, "Segurança FastLog"
End Sub

