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

Public Const VERSAO_ROBO As String = "1.0 Enterprise"
Public Const DIRETORIO_EXPORTACAO As String = "C:\FastLog_RPA_Saidas"

Public Sub ExecutarCicloCompletoRPA(ByVal strCliente As String, _
                                   ByVal strEmail As String, _
                                   ByVal strPlaca As String, _
                                   ByVal strMotorista As String, _
                                   ByVal strTipoCarga As String, _
                                   ByVal dblPesoKg As Double, _
                                   ByVal dblKm As Double)
    On Error GoTo TratarFalhaRPA
    
    Dim tInicio As Double
    Dim wsBase As Worksheet, wsDash As Worksheet
    Dim curTarifaKm As Currency, curTarifaPeso As Currency, curFatorRisco As Currency, curFreteTotal As Currency
    Dim strIDViagem As String
    Dim lngProximaLinha As Long
    Dim strCaminhoPasta As String, strCaminhoCSV As String, strCaminhoPDF As String
    Dim fso As Object, arqCSV As Object, objOutlook As Object, objMail As Object
    Dim curFaturamentoTotal As Currency, lngTotalOrdens As Long, r As Long
    
    tInicio = Timer
    
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    
    Set wsBase = ThisWorkbook.Worksheets("Base_Expedicoes")
    Set wsDash = ThisWorkbook.Worksheets("Dashboard_Executivo")
    
    ' 1. Precificação
    curTarifaKm = dblKm * 3.8
    curTarifaPeso = dblPesoKg * 0.15
    
    Select Case UCase(Trim(strTipoCarga))
        Case "PERIGOSA", "QUIMICA": curFatorRisco = 1.35
        Case "REFRIGERADA":         curFatorRisco = 1.2
        Case "VALIOSA":             curFatorRisco = 1.5
        Case Else:                  curFatorRisco = 1#
    End Select
    
    curFreteTotal = (curTarifaKm + curTarifaPeso) * curFatorRisco
    
    ' 2. Base Local
    lngProximaLinha = wsBase.Cells(wsBase.Rows.Count, "A").End(xlUp).Row + 1
    strIDViagem = "FL-RPA-" & Format(lngProximaLinha - 1, "0000")
    
    wsBase.Cells(lngProximaLinha, 1).Value = strIDViagem
    wsBase.Cells(lngProximaLinha, 2).Value = UCase(Trim(strCliente))
    wsBase.Cells(lngProximaLinha, 3).Value = UCase(Trim(Replace(strPlaca, "-", "")))
    wsBase.Cells(lngProximaLinha, 4).Value = UCase(Trim(strMotorista))
    wsBase.Cells(lngProximaLinha, 5).Value = UCase(Trim(strTipoCarga))
    wsBase.Cells(lngProximaLinha, 6).Value = dblPesoKg
    wsBase.Cells(lngProximaLinha, 7).Value = dblKm
    wsBase.Cells(lngProximaLinha, 8).Value = curFreteTotal
    wsBase.Cells(lngProximaLinha, 9).Value = Now
    
    wsBase.Cells(lngProximaLinha, 8).NumberFormat = "R$ #,##0.00"
    wsBase.Cells(lngProximaLinha, 9).NumberFormat = "dd/mm/yyyy hh:mm:ss"
    
    ' 3. FSO
    Set fso = CreateObject("Scripting.FileSystemObject")
    strCaminhoPasta = DIRETORIO_EXPORTACAO & "\" & Format(Date, "yyyy-mm")
    
    If Not fso.FolderExists(DIRETORIO_EXPORTACAO) Then fso.CreateFolder DIRETORIO_EXPORTACAO
    If Not fso.FolderExists(strCaminhoPasta) Then fso.CreateFolder strCaminhoPasta
    
    strCaminhoCSV = strCaminhoPasta & "\MDFE_" & strIDViagem & ".csv"
    Set arqCSV = fso.CreateTextFile(strCaminhoCSV, True)
    arqCSV.WriteLine "ID;CLIENTE;PLACA;MOTORISTA;TIPO;FRETE;DATA_REGISTRO"
    arqCSV.WriteLine strIDViagem & ";" & strCliente & ";" & strPlaca & ";" & _
                     strMotorista & ";" & strTipoCarga & ";" & _
                     Replace(FormatNumber(curFreteTotal, 2), ".", "") & ";" & Format(Now, "yyyy-mm-dd hh:nn:ss")
    arqCSV.Close
    Set arqCSV = Nothing
    
    ' 4. PDF e Outlook
    strCaminhoPDF = strCaminhoPasta & "\Fatura_" & strIDViagem & ".pdf"
    wsBase.Range("A" & lngProximaLinha & ":I" & lngProximaLinha).ExportAsFixedFormat _
        Type:=xlTypePDF, Filename:=strCaminhoPDF
        
    Set objOutlook = CreateObject("Outlook.Application")
    Set objMail = objOutlook.CreateItem(0)
    
    With objMail
        .To = strEmail
        .Subject = "FastLog RPA - Conhecimento de Transporte Eletrônico (" & strIDViagem & ")"
        .HTMLBody = "<div style='font-family: Segoe UI, Arial; font-size: 13px; color: #222;'>" & _
                    "<h3 style='color: #003366;'>FASTLOG TRANSPORTES & LOGÍSTICA S.A.</h3>" & _
                    "<p>Prezado cliente <b>" & strCliente & "</b>,</p>" & _
                    "<p>Sua ordem de transporte rodoviário foi homologada com sucesso:</p>" & _
                    "<ul>" & _
                    "<li><b>Ordem de Frete:</b> " & strIDViagem & "</li>" & _
                    "<li><b>Placa Veicular:</b> " & strPlaca & " (Condutor: " & strMotorista & ")</li>" & _
                    "<li><b>Valor Total Liquidado:</b> " & FormatCurrency(curFreteTotal) & "</li>" & _
                    "</ul>" & _
                    "<p>O comprovante oficial e o espelho fiscal constam anexos em PDF.</p>" & _
                    "<p style='color: #888; font-size: 10px;'>Disparado pelo robô corporativo FastLog RPA Enterprise 1.0</p>" & _
                    "</div>"
        .Attachments.Add strCaminhoPDF
        .Send
    End With
    
    Set objMail = Nothing
    Set objOutlook = Nothing
    Set fso = Nothing
    
    ' 5. Dashboard
    lngTotalOrdens = lngProximaLinha - 1
    curFaturamentoTotal = 0
    For r = 2 To lngProximaLinha
        curFaturamentoTotal = curFaturamentoTotal + CCur(wsBase.Cells(r, 8).Value)
    Next r
    
    wsDash.Range("B3").Value = lngTotalOrdens
    wsDash.Range("B4").Value = curFaturamentoTotal
    wsDash.Range("B5").Value = Now
    
    wsDash.Range("B4").NumberFormat = "R$ #,##0.00"
    wsDash.Range("B5").NumberFormat = "dd/mm/yyyy hh:mm:ss"
    
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    
    MsgBox "CICLO DE RPA EXECUTADO COM SUCESSO!" & vbCrLf & vbCrLf & _
           "• Ordem: " & strIDViagem & vbCrLf & _
           "• Frete: " & FormatCurrency(curFreteTotal) & vbCrLf & _
           "• MDF-e CSV e PDF gerados!" & vbCrLf & _
           "• E-mail disparado!" & vbCrLf & _
           "• Tempo de Execução: " & Format(Timer - tInicio, "0.000") & " s!", _
           vbInformation, "FastLog RPA Enterprise 1.0"
    Exit Sub

TratarFalhaRPA:
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    MsgBox "FALHA CRÍTICA NO ROBÔ: " & Err.Description, vbCritical, "Erro de Execução"
End Sub

