<%@ Language="VBScript" %>
<%
'=============================================================================
' FILE: api_usb.asp
' PURPOSE: API endpoints for USB device operations
' SECURITY: Parameterized queries, JSON output
' CREATED: 2025-12-07
'=============================================================================
Option Explicit
Response.ContentType = "application/json"
Response.Charset = "utf-8"
Response.Buffer = True

' Create database connection directly (avoid sql.asp scoping issues)
Dim objConn, DB_CONN_STRING
DB_CONN_STRING = "Driver={MySQL ODBC 9.4 Unicode Driver};" & _
                 "Server=192.168.122.1;" & _
                 "Port=3306;" & _
                 "Database=shopdb;" & _
                 "User=570005354;" & _
                 "Password=570005354;" & _
                 "Option=3;" & _
                 "Pooling=True;Max Pool Size=100;"

On Error Resume Next
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.ConnectionString = DB_CONN_STRING
objConn.Open

If Err.Number <> 0 Then
    Response.Write("{""success"":false,""error"":""Database connection error""}")
    Response.End
End If
On Error GoTo 0

Dim action
action = Trim(Request.QueryString("action"))

Select Case action
    Case "lookup"
        Call LookupUSB()
    Case "checkin_lookup"
        Call CheckinLookup()
    Case Else
        Response.Write("{""success"":false,""error"":""Invalid action""}")
End Select

'=============================================================================
' LOOKUP USB - Check if USB exists and get its status
'=============================================================================
Sub LookupUSB()
    Dim serial, strSQL, cmd, rs
    serial = Trim(Request.QueryString("serial"))

    If serial = "" Or Len(serial) < 3 Then
        Response.Write("{""success"":false,""error"":""Invalid serial number""}")
        Exit Sub
    End If

    On Error Resume Next

    ' Look up USB device
    strSQL = "SELECT m.machineid, m.serialnumber, m.alias, bu.businessunit, " & _
             "uc.checkoutid, uc.sso AS current_holder, uc.checkout_time, " & _
             "(SELECT MAX(uc2.checkout_time) FROM usb_checkouts uc2 WHERE uc2.machineid = m.machineid) AS last_checkout " & _
             "FROM machines m " & _
             "LEFT JOIN businessunits bu ON m.businessunitid = bu.businessunitid " & _
             "LEFT JOIN usb_checkouts uc ON m.machineid = uc.machineid AND uc.checkin_time IS NULL " & _
             "WHERE m.machinetypeid = 44 AND m.isactive = 1 AND m.serialnumber = ?"

    Set cmd = Server.CreateObject("ADODB.Command")
    cmd.ActiveConnection = objConn
    cmd.CommandText = strSQL
    cmd.CommandType = 1
    cmd.Parameters.Append cmd.CreateParameter("@serial", 200, 1, 100, serial)

    Set rs = cmd.Execute

    If Err.Number <> 0 Then
        Response.Write("{""success"":false,""error"":""Database query error: " & JSONEscape(Err.Description) & """}")
        Exit Sub
    End If

    On Error GoTo 0

    If rs.EOF Then
        Response.Write("{""success"":false,""error"":""USB device not found with serial: " & JSONEscape(serial) & """}")
        rs.Close
        Set rs = Nothing
        Set cmd = Nothing
        Exit Sub
    End If

    Dim machineId, serialNum, usbAlias, businessUnit, checkoutId, currentHolder, checkoutTime, lastCheckout
    Dim usbStatus

    machineId = rs("machineid")
    serialNum = rs("serialnumber") & ""
    usbAlias = rs("alias") & ""
    businessUnit = rs("businessunit") & ""
    checkoutId = rs("checkoutid")
    currentHolder = rs("current_holder") & ""

    ' Format checkout time (MM/DD/YYYY h:mm AM/PM)
    If Not IsNull(rs("checkout_time")) Then
        checkoutTime = Month(rs("checkout_time")) & "/" & Day(rs("checkout_time")) & "/" & Year(rs("checkout_time")) & " " & FormatDateTime(rs("checkout_time"), 3)
    Else
        checkoutTime = ""
    End If

    ' Format last checkout (MM/DD/YYYY h:mm AM/PM)
    If Not IsNull(rs("last_checkout")) Then
        lastCheckout = Month(rs("last_checkout")) & "/" & Day(rs("last_checkout")) & "/" & Year(rs("last_checkout")) & " " & FormatDateTime(rs("last_checkout"), 3)
    Else
        lastCheckout = ""
    End If

    ' Determine status
    If IsNull(checkoutId) Then
        usbStatus = "available"
    Else
        usbStatus = "checked_out"
    End If

    Response.Write("{""success"":true,")
    Response.Write("""machineid"":" & machineId & ",")
    Response.Write("""serialnumber"":""" & JSONEscape(serialNum) & """,")
    Response.Write("""alias"":""" & JSONEscape(usbAlias) & """,")
    Response.Write("""businessunit"":""" & JSONEscape(businessUnit) & """,")
    Response.Write("""status"":""" & usbStatus & """,")
    Response.Write("""current_holder"":""" & JSONEscape(currentHolder) & """,")
    Response.Write("""checkout_time"":""" & JSONEscape(checkoutTime) & """,")
    Response.Write("""last_checkout"":""" & JSONEscape(lastCheckout) & """}")

    rs.Close
    Set rs = Nothing
    Set cmd = Nothing
End Sub

'=============================================================================
' CHECKIN LOOKUP - Get details for a checked-out USB
'=============================================================================
Sub CheckinLookup()
    Dim serial, strSQL, cmd, rs
    serial = Trim(Request.QueryString("serial"))

    If serial = "" Or Len(serial) < 3 Then
        Response.Write("{""success"":false,""error"":""Invalid serial number""}")
        Exit Sub
    End If

    On Error Resume Next

    ' Look up USB device that is currently checked out
    strSQL = "SELECT m.machineid, m.serialnumber, m.alias, bu.businessunit, " & _
             "uc.checkoutid, uc.sso, uc.checkout_time, uc.checkout_reason " & _
             "FROM machines m " & _
             "LEFT JOIN businessunits bu ON m.businessunitid = bu.businessunitid " & _
             "INNER JOIN usb_checkouts uc ON m.machineid = uc.machineid AND uc.checkin_time IS NULL " & _
             "WHERE m.machinetypeid = 44 AND m.isactive = 1 AND m.serialnumber = ?"

    Set cmd = Server.CreateObject("ADODB.Command")
    cmd.ActiveConnection = objConn
    cmd.CommandText = strSQL
    cmd.CommandType = 1
    cmd.Parameters.Append cmd.CreateParameter("@serial", 200, 1, 100, serial)

    Set rs = cmd.Execute

    If Err.Number <> 0 Then
        Response.Write("{""success"":false,""error"":""Database query error: " & JSONEscape(Err.Description) & """}")
        Exit Sub
    End If

    On Error GoTo 0

    If rs.EOF Then
        rs.Close
        Set rs = Nothing
        Set cmd = Nothing

        ' Check if USB exists at all
        Dim checkSQL, rsCheck, cmdCheck
        checkSQL = "SELECT machineid FROM machines WHERE machinetypeid = 44 AND isactive = 1 AND serialnumber = ?"

        On Error Resume Next
        Set cmdCheck = Server.CreateObject("ADODB.Command")
        cmdCheck.ActiveConnection = objConn
        cmdCheck.CommandText = checkSQL
        cmdCheck.CommandType = 1
        cmdCheck.Parameters.Append cmdCheck.CreateParameter("@serial", 200, 1, 100, serial)
        Set rsCheck = cmdCheck.Execute

        If Err.Number <> 0 Then
            Response.Write("{""success"":false,""error"":""Database error""}")
            Exit Sub
        End If
        On Error GoTo 0

        If rsCheck.EOF Then
            Response.Write("{""success"":false,""error"":""USB device not found""}")
        Else
            Response.Write("{""success"":false,""error"":""USB is not currently checked out""}")
        End If
        rsCheck.Close
        Set rsCheck = Nothing
        Set cmdCheck = Nothing
        Exit Sub
    End If

    Dim machineId, serialNum, usbAlias, businessUnit, checkoutId, sso, checkoutTime, checkoutReason
    Dim duration

    machineId = rs("machineid")
    serialNum = rs("serialnumber") & ""
    usbAlias = rs("alias") & ""
    businessUnit = rs("businessunit") & ""
    checkoutId = rs("checkoutid")
    sso = rs("sso") & ""
    checkoutReason = rs("checkout_reason") & ""

    ' Format checkout time (MM/DD/YYYY h:mm AM/PM)
    If Not IsNull(rs("checkout_time")) Then
        checkoutTime = Month(rs("checkout_time")) & "/" & Day(rs("checkout_time")) & "/" & Year(rs("checkout_time")) & " " & FormatDateTime(rs("checkout_time"), 3)
        ' Calculate duration
        Dim diffMinutes
        diffMinutes = DateDiff("n", rs("checkout_time"), Now())
        If diffMinutes < 60 Then
            duration = diffMinutes & " minutes"
        ElseIf diffMinutes < 1440 Then
            duration = Int(diffMinutes / 60) & " hours " & (diffMinutes Mod 60) & " minutes"
        Else
            duration = Int(diffMinutes / 1440) & " days " & Int((diffMinutes Mod 1440) / 60) & " hours"
        End If
    Else
        checkoutTime = ""
        duration = ""
    End If

    Response.Write("{""success"":true,")
    Response.Write("""machineid"":" & machineId & ",")
    Response.Write("""checkoutid"":" & checkoutId & ",")
    Response.Write("""serialnumber"":""" & JSONEscape(serialNum) & """,")
    Response.Write("""alias"":""" & JSONEscape(usbAlias) & """,")
    Response.Write("""businessunit"":""" & JSONEscape(businessUnit) & """,")
    Response.Write("""sso"":""" & JSONEscape(sso) & """,")
    Response.Write("""checkout_time"":""" & JSONEscape(checkoutTime) & """,")
    Response.Write("""checkout_reason"":""" & JSONEscape(checkoutReason) & """,")
    Response.Write("""duration"":""" & JSONEscape(duration) & """}")

    rs.Close
    Set rs = Nothing
    Set cmd = Nothing
End Sub

'=============================================================================
' JSON ESCAPE - Escape special characters for JSON output
'=============================================================================
Function JSONEscape(str)
    Dim result
    result = 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")
    JSONEscape = result
End Function
%>
