Attribute VB_Name = "Module_JSON"
' 360LM BTL Add-in — JSON Generator
' Reads all tagged shapes and exports machine-readable JSON
Option Explicit

' Item types recognised by 360LM PWA
Private Const VALID_TYPES As String = _
    "Glow Sign Board,Backlit Board,Flex Banner,ACP Board," & _
    "One Way Vision,Window Decal,Floor Graphic,Translit," & _
    "Fabric Board,Lollypop,Clip on Board,Vinyl Print,Inshop Branding"

Public Function ExportToFile() As String
    ExportToFile = ""
    Dim jsonStr As String
    jsonStr = BuildJSON()
    If jsonStr = "" Then Exit Function

    ' Save alongside the PPTX
    Dim pptxDir As String
    pptxDir = Left(ActivePresentation.FullName, _
                   InStrRev(ActivePresentation.FullName, "\"))
    Dim brand As String
    brand = CleanFilename(Module_Main.GetCoverField("lm360_brand"))
    Dim campaign As String
    campaign = CleanFilename(Module_Main.GetCoverField("lm360_campaign"))
    Dim fname As String
    fname = pptxDir & "360LM_BTL_" & brand & "_" & campaign & "_" & _
            Format(Now, "YYYYMMDD") & ".json"

    Dim fnum As Integer
    fnum = FreeFile
    Open fname For Output As #fnum
    Print #fnum, jsonStr
    Close #fnum

    ExportToFile = fname
End Function

Public Function BuildJSON() As String
    Dim prs As Presentation
    Set prs = ActivePresentation

    ' Cover metadata
    Dim brand As String:    brand    = Module_Main.GetCoverField("lm360_brand")
    Dim campaign As String: campaign = Module_Main.GetCoverField("lm360_campaign")
    Dim dt As String:       dt       = Module_Main.GetCoverField("lm360_date")
    Dim prepBy As String:   prepBy   = Module_Main.GetCoverField("lm360_prepared_by")

    Dim counters() As String
    Dim count As Integer: count = 0

    Dim sl As slide
    For Each sl In prs.Slides
        If Module_Main.IsCounterSlide(sl) Then
            Dim cno As String: cno = Module_Main.GetCounterNo(sl)
            Dim cname As String: cname = Module_Main.GetShapeText(sl, "lm360_counter_" & cno)
            Dim cityState As String: cityState = Module_Main.GetShapeText(sl, "lm360_city_state_" & cno)
            Dim brandTag As String: brandTag = Module_Main.GetShapeText(sl, "lm360_brand_tag_" & cno)

            ' Parse city | state
            Dim city As String: city = ""
            Dim state As String: state = ""
            Dim sep As Integer: sep = InStr(cityState, "|")
            If sep > 0 Then
                city  = Trim(Left(cityState, sep - 1))
                state = Trim(Mid(cityState, sep + 1))
            Else
                city = Trim(cityState)
            End If

            ' Collect item rows
            Dim items As String: items = ""
            Dim ri As Integer: ri = 0
            Do
                Dim itype As String: itype = Module_Main.GetShapeText(sl, "lm360_" & cno & "_" & ri & "_type")
                If itype = "" And ri > 0 Then Exit Do
                If itype <> "" Then
                    Dim mat As String:      mat      = Module_Main.GetShapeText(sl, "lm360_" & cno & "_" & ri & "_material")
                    Dim sz As String:       sz       = Module_Main.GetShapeText(sl, "lm360_" & cno & "_" & ri & "_size")
                    Dim qty As String:      qty      = Module_Main.GetShapeText(sl, "lm360_" & cno & "_" & ri & "_qty")
                    Dim remP As String:     remP     = Module_Main.GetShapeText(sl, "lm360_" & cno & "_" & ri & "_rem_prod")
                    Dim remI As String:     remI     = Module_Main.GetShapeText(sl, "lm360_" & cno & "_" & ri & "_rem_inst")
                    Dim qtyNum As Integer
                    qtyNum = 1
                    If IsNumeric(qty) Then qtyNum = CInt(qty)
                    If items <> "" Then items = items & ","
                    items = items & vbNewLine & "      {" & _
                        """type"":"      & JsonStr(itype) & "," & _
                        """material"":"  & JsonStr(mat)   & "," & _
                        """size"":"      & JsonStr(sz)    & "," & _
                        """qty"":"       & qtyNum         & "," & _
                        """rem_prod"":"  & JsonStr(remP)  & "," & _
                        """rem_inst"":"  & JsonStr(remI)  & "," & _
                        """status"":"    & JsonStr(ItemStatus(itype, sz)) & _
                        "}"
                End If
                ri = ri + 1
                If ri > 20 Then Exit Do
            Loop

            Dim entry As String
            entry = "  {" & vbNewLine & _
                "    ""lm360_schema"":""v1""," & vbNewLine & _
                "    ""counter_no"":" & cno & "," & vbNewLine & _
                "    ""counter_name"":" & JsonStr(cname) & "," & vbNewLine & _
                "    ""city"":" & JsonStr(city) & "," & vbNewLine & _
                "    ""state"":" & JsonStr(state) & "," & vbNewLine & _
                "    ""brand"":" & JsonStr(brandTag) & "," & vbNewLine & _
                "    ""campaign"":" & JsonStr(campaign) & "," & vbNewLine & _
                "    ""items"":[" & items & vbNewLine & "    ]" & vbNewLine & _
                "  }"

            If count > 0 Then
                ReDim Preserve counters(count)
            Else
                ReDim counters(0)
            End If
            counters(count) = entry
            count = count + 1
        End If
    Next sl

    If count = 0 Then
        MsgBox "No counter slides found. Add counters using the New Counter button.", vbExclamation
        BuildJSON = ""
        Exit Function
    End If

    Dim body As String
    body = Join(counters, "," & vbNewLine)

    BuildJSON = "{" & vbNewLine & _
        "  ""lm360_schema"":""v1""," & vbNewLine & _
        "  ""generated"":""" & Format(Now, "YYYY-MM-DD HH:MM:SS") & """," & vbNewLine & _
        "  ""brand"":" & JsonStr(brand) & "," & vbNewLine & _
        "  ""campaign"":" & JsonStr(campaign) & "," & vbNewLine & _
        "  ""date"":" & JsonStr(dt) & "," & vbNewLine & _
        "  ""prepared_by"":" & JsonStr(prepBy) & "," & vbNewLine & _
        "  ""counters"":[" & vbNewLine & body & vbNewLine & "  ]" & vbNewLine & _
        "}"
End Function

Private Function JsonStr(s As String) As String
    JsonStr = """" & Replace(Replace(s, "\", "\\"), """", "\""") & """"
End Function

Private Function ItemStatus(itype As String, sz As String) As String
    If itype = "" Then
        ItemStatus = "unclear"
    ElseIf sz = "" Or sz = "[ W × H ]" Then
        ItemStatus = "recce_pending"
    ElseIf InStr(LCase(sz), "pending") > 0 Or InStr(LCase(sz), "mockup") > 0 Then
        ItemStatus = "mockup_pending"
    Else
        ItemStatus = "ready"
    End If
End Function

Private Function CleanFilename(s As String) As String
    Dim result As String: result = s
    Dim bad As String: bad = "\/:*?""<>|"
    Dim i As Integer
    For i = 1 To Len(bad)
        result = Replace(result, Mid(bad, i, 1), "_")
    Next i
    CleanFilename = result
End Function
