<%@ Language=VBScript %>
<!--#include file="../includes/sql.asp"-->
<%
' ============================================================================
' API Endpoint: Get Notifications (Safe Version with Parameterized Query)
' Returns current and upcoming notifications in JSON format
' Uses shared sql.asp connection from shopdb project
' ============================================================================

Option Explicit
Response.ContentType = "application/json"
Response.Charset = "UTF-8"

Dim objCmd, objRS
Dim now, future
Dim currentEvents(), upcomingEvents()
Dim currentCount, upcomingCount
Dim jsonOutput

' Initialize
currentCount = 0
upcomingCount = 0
ReDim currentEvents(0)
ReDim upcomingEvents(0)

On Error Resume Next

' Calculate time window
now = Now()
future = DateAdd("h", 72, now)

' objConn is already created and opened by includes/sql.asp
' No need to create our own connection

' Create command with parameters
Set objCmd = Server.CreateObject("ADODB.Command")
Set objCmd.ActiveConnection = objConn
objCmd.CommandText = "SELECT n.notificationid, n.notification, n.starttime, n.endtime, " & _
                     "n.ticketnumber, n.link, n.isactive, n.isshopfloor, " & _
                     "nt.typename, nt.typecolor " & _
                     "FROM notifications n " & _
                     "LEFT JOIN notificationtypes nt ON n.notificationtypeid = nt.notificationtypeid " & _
                     "WHERE n.isactive = 1 AND n.isshopfloor = 1 " & _
                     "AND ((n.starttime <= ? AND (n.endtime IS NULL OR n.endtime >= ?)) " & _
                     "     OR (n.starttime BETWEEN ? AND ?)) " & _
                     "ORDER BY n.starttime ASC"

objCmd.CommandType = 1 ' adCmdText

' Add parameters
objCmd.Parameters.Append objCmd.CreateParameter("future1", 135, 1, , future)  ' adDBTimeStamp
objCmd.Parameters.Append objCmd.CreateParameter("now1", 135, 1, , now)
objCmd.Parameters.Append objCmd.CreateParameter("now2", 135, 1, , now)
objCmd.Parameters.Append objCmd.CreateParameter("future2", 135, 1, , future)

Set objRS = objCmd.Execute

If Err.Number <> 0 Then
    Response.Write "{""success"":false,""error"":""Query error: " & EscapeJSON(Err.Description) & """}"
    Response.End
End If

' Process records
Do While Not objRS.EOF
    Dim startTime, endTime, isCurrent

    startTime = objRS("starttime")
    endTime = objRS("endtime")

    ' Check if current
    isCurrent = False
    If IsDate(startTime) And startTime <= now Then
        If IsNull(endTime) Or endTime >= now Then
            isCurrent = True
        End If
    End If

    ' Build event object
    Dim eventObj
    Set eventObj = BuildEventJSON(objRS)

    ' Add to appropriate array
    If isCurrent Then
        ReDim Preserve currentEvents(currentCount)
        currentEvents(currentCount) = eventObj
        currentCount = currentCount + 1
    Else
        ReDim Preserve upcomingEvents(upcomingCount)
        upcomingEvents(upcomingCount) = eventObj
        upcomingCount = upcomingCount + 1
    End If

    objRS.MoveNext
Loop

objRS.Close
' objConn is managed by sql.asp - don't close it here

' Build JSON response
jsonOutput = "{""success"":true," & _
             """timestamp"":""" & ISO8601(Now()) & """," & _
             """current"":[" & JoinArray(currentEvents, currentCount) & "]," & _
             """upcoming"":[" & JoinArray(upcomingEvents, upcomingCount) & "]}"

Response.Write jsonOutput

' ============================================================================
' Functions
' ============================================================================

Function BuildEventJSON(rs)
    Dim json
    json = "{" & _
        """notificationid"":" & rs("notificationid") & "," & _
        """notification"":""" & EscapeJSON(rs("notification")) & """," & _
        """starttime"":""" & ISO8601(rs("starttime")) & """," & _
        """endtime"":" & NullOrString(rs("endtime")) & "," & _
        """ticketnumber"":" & NullOrString(rs("ticketnumber")) & "," & _
        """link"":" & NullOrString(rs("link")) & "," & _
        """isactive"":" & BoolStr(rs("isactive")) & "," & _
        """isshopfloor"":" & BoolStr(rs("isshopfloor")) & "," & _
        """typename"":""" & EscapeJSON(rs("typename")) & """," & _
        """typecolor"":""" & EscapeJSON(rs("typecolor")) & """" & _
        "}"
    BuildEventJSON = json
End Function

Function JoinArray(arr, count)
    If count = 0 Then
        JoinArray = ""
        Exit Function
    End If
    Dim i, result
    result = ""
    For i = 0 To count - 1
        If i > 0 Then result = result & ","
        result = result & arr(i)
    Next
    JoinArray = result
End Function

Function EscapeJSON(str)
    If IsNull(str) Then
        EscapeJSON = ""
        Exit Function
    End If
    Dim result
    result = CStr(str)
    result = Replace(result, "\", "\\")
    result = Replace(result, """", "\""")
    result = Replace(result, Chr(13), "\r")
    result = Replace(result, Chr(10), "\n")
    result = Replace(result, Chr(9), "\t")
    EscapeJSON = result
End Function

Function ISO8601(dt)
    If IsNull(dt) Or Not IsDate(dt) Then
        ISO8601 = ""
        Exit Function
    End If
    ISO8601 = Year(dt) & "-" & _
              Right("0" & Month(dt), 2) & "-" & _
              Right("0" & Day(dt), 2) & "T" & _
              Right("0" & Hour(dt), 2) & ":" & _
              Right("0" & Minute(dt), 2) & ":" & _
              Right("0" & Second(dt), 2)
End Function

Function NullOrString(val)
    If IsNull(val) Then
        NullOrString = "null"
    Else
        NullOrString = """" & EscapeJSON(val) & """"
    End If
End Function

Function BoolStr(val)
    If CBool(val) Then
        BoolStr = "true"
    Else
        BoolStr = "false"
    End If
End Function
%>
