<%
'=============================================================================
' FILE: savenetworkdevice.asp
' PURPOSE: Universal save endpoint for all network devices (IDF, Server, Switch, Camera, Access Point)
' SECURITY: Parameterized queries, HTML encoding, input validation
' UPDATED: 2025-11-11 - Updated for Phase 3 Migration (machines table)
'=============================================================================
%>
<!--#include file="./includes/sql.asp"-->
<!--#include file="./includes/response.asp"-->
<%
' Universal save endpoint for all network devices
' Saves to unified machines table with appropriate machinetypeid

' Get device type and ID
Dim deviceType, deviceId, isDelete
deviceType = Trim(Request.Form("type"))
deviceId = Trim(Request.Form("id"))
isDelete = Trim(Request.Form("delete"))

' Validate device type
If deviceType <> "idf" And deviceType <> "server" And deviceType <> "switch" And deviceType <> "camera" And deviceType <> "accesspoint" And deviceType <> "firewall" Then
    objConn.Close
    ShowError "Invalid device type.", "networkdevices.asp"
    Response.End
End If

' Validate device ID
If deviceId = "" Then deviceId = "0"
If Not IsNumeric(deviceId) Then
    objConn.Close
    ShowError "Invalid device ID.", "networkdevices.asp"
    Response.End
End If

' Map type to machinetypeid and display name
Dim machineTypeId, nameField, redirectUrl, deviceDisplayName
Select Case deviceType
    Case "idf"
        machineTypeId = 17
        nameField = "idfname"
        redirectUrl = "networkdevices.asp?filter=IDF"
        deviceDisplayName = "IDF"
    Case "server"
        machineTypeId = 20
        nameField = "servername"
        redirectUrl = "networkdevices.asp?filter=Server"
        deviceDisplayName = "Server"
    Case "switch"
        machineTypeId = 19
        nameField = "switchname"
        redirectUrl = "networkdevices.asp?filter=Switch"
        deviceDisplayName = "Switch"
    Case "firewall"
        machineTypeId = 46
        nameField = "firewallname"
        redirectUrl = "networkdevices.asp?filter=Firewall"
        deviceDisplayName = "Firewall"
    Case "camera"
        machineTypeId = 18
        nameField = "cameraname"
        redirectUrl = "networkdevices.asp?filter=Camera"
        deviceDisplayName = "Camera"
    Case "accesspoint"
        machineTypeId = 16
        nameField = "apname"
        redirectUrl = "networkdevices.asp?filter=Access Point"
        deviceDisplayName = "Access Point"
End Select

' Handle DELETE request
If isDelete = "1" Then
    ' Soft delete - set isactive = 0 using parameterized query
    Dim strDelete, cmdDelete
    strDelete = "UPDATE machines SET isactive = 0 WHERE machineid = ?"
    Set cmdDelete = Server.CreateObject("ADODB.Command")
    cmdDelete.ActiveConnection = objConn
    cmdDelete.CommandText = strDelete
    cmdDelete.CommandType = 1
    cmdDelete.Parameters.Append cmdDelete.CreateParameter("@machineid", 3, 1, , CLng(deviceId))
    cmdDelete.Execute
    Set cmdDelete = Nothing
    objConn.Close
    Response.Redirect(redirectUrl)
    Response.End
End If

' Get form data
Dim deviceName, description, maptop, mapleft, isactiveForm
deviceName = Trim(Request.Form(nameField))
description = Trim(Request.Form("description"))
maptop = Trim(Request.Form("maptop"))
mapleft = Trim(Request.Form("mapleft"))
isactiveForm = Trim(Request.Form("isactive"))

' Handle isactive - checkbox: checked=1, unchecked=empty string
If isactiveForm = "1" Then
    isactiveForm = "1"
Else
    isactiveForm = "0"
End If

' Validate name field (required for all)
If deviceName = "" Then
    objConn.Close
    ShowError deviceDisplayName & " name is required.", "networkdevices.asp"
    Response.End
End If

' Validate field lengths
If Len(deviceName) > 100 Or Len(description) > 255 Then
    objConn.Close
    ShowError "Field length exceeded.", "networkdevices.asp"
    Response.End
End If

' Handle NULL values for optional numeric fields
Dim maptopValue, mapleftValue
If maptop = "" Or Not IsNumeric(maptop) Then
    maptopValue = Null
Else
    maptopValue = CLng(maptop)
End If
If mapleft = "" Or Not IsNumeric(mapleft) Then
    mapleftValue = Null
Else
    mapleftValue = CLng(mapleft)
End If

' Get model and serial number (common fields)
Dim modelid, serialnumber, ipaddress, fqdn, macaddress, logicmonitorurl
modelid = Trim(Request.Form("modelid"))
serialnumber = Trim(Request.Form("serialnumber"))
ipaddress = Trim(Request.Form("ipaddress"))
fqdn = Trim(Request.Form("fqdn"))
macaddress = Trim(Request.Form("macaddress"))
logicmonitorurl = Trim(Request.Form("logicmonitorurl"))

' Handle new model creation
If modelid = "new" Then
    Dim newmodelnumber, newvendorid, newmodelnotes, newmodeldocpath, newvendorname, newmodelmachinetypeid
    newmodelnumber = Trim(Request.Form("newmodelnumber"))
    newvendorid = Trim(Request.Form("newvendorid"))
    newmodelnotes = Trim(Request.Form("newmodelnotes"))
    newmodeldocpath = Trim(Request.Form("newmodeldocpath"))
    newvendorname = Trim(Request.Form("newvendorname"))
    newmodelmachinetypeid = Trim(Request.Form("newmodelmachinetypeid"))

    ' Validate required fields for new model
    If newmodelnumber = "" Then
        objConn.Close
        ShowError "Model number is required.", "networkdevices.asp"
        Response.End
    End If

    If newvendorid = "" Then
        objConn.Close
        ShowError "Vendor is required for new model.", "networkdevices.asp"
        Response.End
    End If

    ' Handle new vendor creation (nested)
    If newvendorid = "new" Then
        If newvendorname = "" Then
            objConn.Close
            ShowError "Vendor name is required.", "networkdevices.asp"
            Response.End
        End If

        ' Insert new vendor using parameterized query
        Dim sqlNewVendor, cmdNewVendor
        sqlNewVendor = "INSERT INTO vendors (vendor, isactive) VALUES (?, 1)"
        Set cmdNewVendor = Server.CreateObject("ADODB.Command")
        cmdNewVendor.ActiveConnection = objConn
        cmdNewVendor.CommandText = sqlNewVendor
        cmdNewVendor.CommandType = 1
        cmdNewVendor.Parameters.Append cmdNewVendor.CreateParameter("@vendor", 200, 1, 50, newvendorname)

        On Error Resume Next
        cmdNewVendor.Execute
        If Err.Number <> 0 Then
            Dim vendorErr
            vendorErr = Err.Description
            Set cmdNewVendor = Nothing
            objConn.Close
            ShowError "Error creating vendor: " & vendorErr, "networkdevices.asp"
            Response.End
        End If

        ' Get newly created vendor ID
        Dim rsNewVendor
        Set rsNewVendor = objConn.Execute("SELECT LAST_INSERT_ID() AS newid")
        newvendorid = rsNewVendor("newid")
        rsNewVendor.Close
        Set rsNewVendor = Nothing
        Set cmdNewVendor = Nothing
        On Error Goto 0
    End If

    ' Handle new machine type creation (nested)
    If newmodelmachinetypeid = "new" Then
        Dim newmachinetypename
        newmachinetypename = Trim(Request.Form("newmachinetypename"))

        If newmachinetypename = "" Then
            objConn.Close
            ShowError "Machine type name is required.", "networkdevices.asp"
            Response.End
        End If

        ' Insert new machine type using parameterized query
        Dim sqlNewMT, cmdNewMT
        sqlNewMT = "INSERT INTO machinetypes (machinetype, isactive) VALUES (?, 1)"
        Set cmdNewMT = Server.CreateObject("ADODB.Command")
        cmdNewMT.ActiveConnection = objConn
        cmdNewMT.CommandText = sqlNewMT
        cmdNewMT.CommandType = 1
        cmdNewMT.Parameters.Append cmdNewMT.CreateParameter("@machinetype", 200, 1, 50, newmachinetypename)

        On Error Resume Next
        cmdNewMT.Execute
        If Err.Number <> 0 Then
            Dim mtErr
            mtErr = Err.Description
            Set cmdNewMT = Nothing
            objConn.Close
            ShowError "Error creating machine type: " & mtErr, "networkdevices.asp"
            Response.End
        End If

        ' Get newly created machine type ID
        Dim rsNewMT
        Set rsNewMT = objConn.Execute("SELECT LAST_INSERT_ID() AS newid")
        newmodelmachinetypeid = CLng(rsNewMT("newid"))
        rsNewMT.Close
        Set rsNewMT = Nothing
        Set cmdNewMT = Nothing
        On Error Goto 0
    End If

    ' Insert new model using parameterized query
    Dim sqlNewModel, cmdNewModel
    sqlNewModel = "INSERT INTO models (modelnumber, vendorid, machinetypeid, notes, documentationpath, isactive) VALUES (?, ?, ?, ?, ?, 1)"
    Set cmdNewModel = Server.CreateObject("ADODB.Command")
    cmdNewModel.ActiveConnection = objConn
    cmdNewModel.CommandText = sqlNewModel
    cmdNewModel.CommandType = 1
    cmdNewModel.Parameters.Append cmdNewModel.CreateParameter("@modelnumber", 200, 1, 50, newmodelnumber)
    cmdNewModel.Parameters.Append cmdNewModel.CreateParameter("@vendorid", 3, 1, , CLng(newvendorid))
    If newmodelmachinetypeid <> "" And IsNumeric(newmodelmachinetypeid) Then
        cmdNewModel.Parameters.Append cmdNewModel.CreateParameter("@machinetypeid", 3, 1, , CLng(newmodelmachinetypeid))
    Else
        cmdNewModel.Parameters.Append cmdNewModel.CreateParameter("@machinetypeid", 3, 1, , Null)
    End If
    cmdNewModel.Parameters.Append cmdNewModel.CreateParameter("@notes", 200, 1, 500, newmodelnotes)
    cmdNewModel.Parameters.Append cmdNewModel.CreateParameter("@documentationpath", 200, 1, 500, newmodeldocpath)

    On Error Resume Next
    cmdNewModel.Execute
    If Err.Number <> 0 Then
        Dim modelErr
        modelErr = Err.Description
        Set cmdNewModel = Nothing
        objConn.Close
        ShowError "Error creating model: " & modelErr, "networkdevices.asp"
        Response.End
    End If

    ' Get newly created model ID
    Dim rsNewModel
    Set rsNewModel = objConn.Execute("SELECT LAST_INSERT_ID() AS newid")
    modelid = rsNewModel("newid")
    rsNewModel.Close
    Set rsNewModel = Nothing
    Set cmdNewModel = Nothing
    On Error Goto 0
End If

' Handle NULL/empty modelid
Dim modelidValue
If modelid = "" Or Not IsNumeric(modelid) Then
    modelidValue = Null
Else
    modelidValue = CLng(modelid)
End If

' Handle camera-specific IDF relationship
Dim idfid, idfRelationshipTypeId
If deviceType = "camera" Then
    idfid = Trim(Request.Form("idfid"))

    ' Handle new IDF creation for camera
    If idfid = "new" Then
        Dim newidfname, newidfdescription
        newidfname = Trim(Request.Form("newidfname"))
        newidfdescription = Trim(Request.Form("newidfdescription"))

        ' Validate required fields for new IDF
        If newidfname = "" Then
            objConn.Close
            ShowError "IDF name is required.", "networkdevices.asp"
            Response.End
        End If

        ' First create the IDF in machines table
        Dim sqlNewIdf, cmdNewIdf
        sqlNewIdf = "INSERT INTO machines (machinenumber, alias, machinetypeid, serialnumber, machinenotes, isactive, lastupdated) VALUES (?, ?, ?, '', ?, 1, NOW())"
        Set cmdNewIdf = Server.CreateObject("ADODB.Command")
        cmdNewIdf.ActiveConnection = objConn
        cmdNewIdf.CommandText = sqlNewIdf
        cmdNewIdf.CommandType = 1
        cmdNewIdf.Parameters.Append cmdNewIdf.CreateParameter("@machinenumber", 200, 1, 100, "IDF-" & Replace(newidfname, " ", "-"))
        cmdNewIdf.Parameters.Append cmdNewIdf.CreateParameter("@alias", 200, 1, 100, newidfname)
        cmdNewIdf.Parameters.Append cmdNewIdf.CreateParameter("@machinetypeid", 3, 1, , machineTypeId)
        cmdNewIdf.Parameters.Append cmdNewIdf.CreateParameter("@machinenotes", 200, 1, 255, newidfdescription)

        On Error Resume Next
        cmdNewIdf.Execute
        If Err.Number <> 0 Then
            Dim idfErr
            idfErr = Err.Description
            Set cmdNewIdf = Nothing
            objConn.Close
            ShowError "Error creating IDF: " & idfErr, "networkdevices.asp"
            Response.End
        End If

        ' Get newly created IDF machine ID
        Dim rsNewIdf
        Set rsNewIdf = objConn.Execute("SELECT LAST_INSERT_ID() AS newid")
        idfid = CLng(rsNewIdf("newid"))
        rsNewIdf.Close
        Set rsNewIdf = Nothing
        Set cmdNewIdf = Nothing
        On Error Goto 0
    End If

    ' Validate required idfid for cameras
    If idfid = "" Or Not IsNumeric(idfid) Or CLng(idfid) < 1 Then
        objConn.Close
        ShowError "IDF location is required for cameras.", "networkdevices.asp"
        Response.End
    End If

    ' Get the "Connected To" relationship type ID for later use
    Dim rsRelType
    Set rsRelType = objConn.Execute("SELECT relationshiptypeid FROM relationshiptypes WHERE relationshiptype = 'Connected To' AND isactive = 1")
    If Not rsRelType.EOF Then
        idfRelationshipTypeId = rsRelType("relationshiptypeid")
    End If
    rsRelType.Close
    Set rsRelType = Nothing
End If

' Generate machinenumber
Dim machinenumber
Select Case deviceType
    Case "server"
        machinenumber = "SVR-" & Replace(deviceName, " ", "-")
    Case "switch"
        machinenumber = "SW-" & Replace(deviceName, " ", "-")
    Case "firewall"
        machinenumber = "FW-" & Replace(deviceName, " ", "-")
    Case "camera"
        machinenumber = "CAM-" & Replace(deviceName, " ", "-")
    Case "accesspoint"
        machinenumber = "AP-" & Replace(deviceName, " ", "-")
    Case "idf"
        machinenumber = "IDF-" & Replace(deviceName, " ", "-")
End Select

' Build SQL for machines table
Dim strSQL, cmdDevice, newMachineId
strSQL = ""

If deviceId = "0" Then
    ' INSERT into machines table
    strSQL = "INSERT INTO machines (machinenumber, alias, modelnumberid, machinetypeid, pctypeid, serialnumber, fqdn, logicmonitorurl, machinenotes, mapleft, maptop, isactive, lastupdated) VALUES (?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, NOW())"
    Set cmdDevice = Server.CreateObject("ADODB.Command")
    cmdDevice.ActiveConnection = objConn
    cmdDevice.CommandText = strSQL
    cmdDevice.CommandType = 1
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@machinenumber", 200, 1, 100, machinenumber)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@alias", 200, 1, 100, deviceName)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@modelnumberid", 3, 1, , modelidValue)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@machinetypeid", 3, 1, , machineTypeId)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@serialnumber", 200, 1, 100, serialnumber)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@fqdn", 200, 1, 255, fqdn)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@logicmonitorurl", 200, 1, 512, logicmonitorurl)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@machinenotes", 200, 1, 255, description)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@mapleft", 3, 1, , mapleftValue)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@maptop", 3, 1, , maptopValue)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@isactive", 3, 1, , CInt(isactiveForm))

    On Error Resume Next
    cmdDevice.Execute
    If Err.Number <> 0 Then
        Dim saveErr
        saveErr = Err.Description
        Set cmdDevice = Nothing
        objConn.Close
        ShowError "Error saving device: " & saveErr, "networkdevices.asp"
        Response.End
    End If
    Set cmdDevice = Nothing
    On Error Goto 0

    ' Get newly created machine ID
    Dim rsNewMachine
    Set rsNewMachine = objConn.Execute("SELECT LAST_INSERT_ID() AS newid")
    newMachineId = rsNewMachine("newid")
    rsNewMachine.Close
    Set rsNewMachine = Nothing

Else
    ' UPDATE machines table
    strSQL = "UPDATE machines SET machinenumber = ?, alias = ?, modelnumberid = ?, serialnumber = ?, fqdn = ?, logicmonitorurl = ?, machinenotes = ?, mapleft = ?, maptop = ?, isactive = ?, lastupdated = NOW() WHERE machineid = ?"
    Set cmdDevice = Server.CreateObject("ADODB.Command")
    cmdDevice.ActiveConnection = objConn
    cmdDevice.CommandText = strSQL
    cmdDevice.CommandType = 1
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@machinenumber", 200, 1, 100, machinenumber)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@alias", 200, 1, 100, deviceName)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@modelnumberid", 3, 1, , modelidValue)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@serialnumber", 200, 1, 100, serialnumber)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@fqdn", 200, 1, 255, fqdn)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@logicmonitorurl", 200, 1, 512, logicmonitorurl)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@machinenotes", 200, 1, 255, description)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@mapleft", 3, 1, , mapleftValue)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@maptop", 3, 1, , maptopValue)
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@isactive", 3, 1, , CInt(isactiveForm))
    cmdDevice.Parameters.Append cmdDevice.CreateParameter("@machineid", 3, 1, , CLng(deviceId))

    On Error Resume Next
    cmdDevice.Execute
    If Err.Number <> 0 Then
        Dim updateErr
        updateErr = Err.Description
        Set cmdDevice = Nothing
        objConn.Close
        ShowError "Error updating device: " & updateErr, "networkdevices.asp"
        Response.End
    End If
    Set cmdDevice = Nothing
    On Error Goto 0

    newMachineId = CLng(deviceId)
End If

' Handle IP address in communications table
If ipaddress <> "" Then
    ' Check if communication record exists
    Dim rsComm, commExists
    Set rsComm = objConn.Execute("SELECT comid FROM communications WHERE machineid = " & newMachineId & " AND comstypeid = 1")
    commExists = Not rsComm.EOF
    If commExists Then
        Dim existingCommId
        existingCommId = rsComm("comid")
    End If
    rsComm.Close
    Set rsComm = Nothing

    If commExists Then
        ' Update existing communication (ensure isprimary=1 so display query finds it)
        Dim sqlUpdateComm, cmdUpdateComm
        sqlUpdateComm = "UPDATE communications SET address = ?, macaddress = ?, isprimary = 1 WHERE comid = ?"
        Set cmdUpdateComm = Server.CreateObject("ADODB.Command")
        cmdUpdateComm.ActiveConnection = objConn
        cmdUpdateComm.CommandText = sqlUpdateComm
        cmdUpdateComm.CommandType = 1
        cmdUpdateComm.Parameters.Append cmdUpdateComm.CreateParameter("@address", 200, 1, 45, ipaddress)
        If macaddress <> "" Then
            cmdUpdateComm.Parameters.Append cmdUpdateComm.CreateParameter("@macaddress", 200, 1, 17, macaddress)
        Else
            cmdUpdateComm.Parameters.Append cmdUpdateComm.CreateParameter("@macaddress", 200, 1, 17, Null)
        End If
        cmdUpdateComm.Parameters.Append cmdUpdateComm.CreateParameter("@communicationsid", 3, 1, , CLng(existingCommId))
        cmdUpdateComm.Execute
        Set cmdUpdateComm = Nothing
    Else
        ' Insert new communication
        Dim sqlInsertComm, cmdInsertComm
        sqlInsertComm = "INSERT INTO communications (machineid, comstypeid, address, macaddress, isprimary, isactive) VALUES (?, 1, ?, ?, 1, 1)"
        Set cmdInsertComm = Server.CreateObject("ADODB.Command")
        cmdInsertComm.ActiveConnection = objConn
        cmdInsertComm.CommandText = sqlInsertComm
        cmdInsertComm.CommandType = 1
        cmdInsertComm.Parameters.Append cmdInsertComm.CreateParameter("@machineid", 3, 1, , CLng(newMachineId))
        cmdInsertComm.Parameters.Append cmdInsertComm.CreateParameter("@address", 200, 1, 45, ipaddress)
        If macaddress <> "" Then
            cmdInsertComm.Parameters.Append cmdInsertComm.CreateParameter("@macaddress", 200, 1, 17, macaddress)
        Else
            cmdInsertComm.Parameters.Append cmdInsertComm.CreateParameter("@macaddress", 200, 1, 17, Null)
        End If
        cmdInsertComm.Execute
        Set cmdInsertComm = Nothing
    End If
End If

' Handle camera -> IDF relationship
If deviceType = "camera" And idfid <> "" And Not IsNull(idfRelationshipTypeId) Then
    ' First remove any existing relationships of this type
    Dim sqlDeleteRel, cmdDeleteRel
    sqlDeleteRel = "DELETE FROM machinerelationships WHERE machineid = ? AND relationshiptypeid = ?"
    Set cmdDeleteRel = Server.CreateObject("ADODB.Command")
    cmdDeleteRel.ActiveConnection = objConn
    cmdDeleteRel.CommandText = sqlDeleteRel
    cmdDeleteRel.CommandType = 1
    cmdDeleteRel.Parameters.Append cmdDeleteRel.CreateParameter("@machineid", 3, 1, , CLng(newMachineId))
    cmdDeleteRel.Parameters.Append cmdDeleteRel.CreateParameter("@relationshiptypeid", 3, 1, , CLng(idfRelationshipTypeId))
    cmdDeleteRel.Execute
    Set cmdDeleteRel = Nothing

    ' Insert new relationship: Camera -> IDF (Connected To)
    Dim sqlInsertRel, cmdInsertRel
    sqlInsertRel = "INSERT INTO machinerelationships (machineid, related_machineid, relationshiptypeid, isactive, dateadded) VALUES (?, ?, ?, 1, NOW())"
    Set cmdInsertRel = Server.CreateObject("ADODB.Command")
    cmdInsertRel.ActiveConnection = objConn
    cmdInsertRel.CommandText = sqlInsertRel
    cmdInsertRel.CommandType = 1
    cmdInsertRel.Parameters.Append cmdInsertRel.CreateParameter("@machineid", 3, 1, , CLng(newMachineId))
    cmdInsertRel.Parameters.Append cmdInsertRel.CreateParameter("@related_machineid", 3, 1, , CLng(idfid))
    cmdInsertRel.Parameters.Append cmdInsertRel.CreateParameter("@relationshiptypeid", 3, 1, , CLng(idfRelationshipTypeId))
    cmdInsertRel.Execute
    Set cmdInsertRel = Nothing
End If

' Handle server application assignments
If deviceType = "server" And deviceId <> "0" Then
    Dim appsToAdd, appsToRemove, appList, appItem, cmdApp, sqlApp

    ' Get apps to add and remove
    appsToAdd = Trim(Request.Form("apps"))
    appsToRemove = Trim(Request.Form("removedapps"))

    ' Remove applications (set isactive = 0)
    If appsToRemove <> "" Then
        appList = Split(appsToRemove, ",")
        For Each appItem In appList
            If IsNumeric(Trim(appItem)) Then
                sqlApp = "UPDATE installedapps SET isactive = 0 WHERE machineid = ? AND appid = ?"
                Set cmdApp = Server.CreateObject("ADODB.Command")
                cmdApp.ActiveConnection = objConn
                cmdApp.CommandText = sqlApp
                cmdApp.CommandType = 1
                cmdApp.Parameters.Append cmdApp.CreateParameter("@machineid", 3, 1, , CLng(newMachineId))
                cmdApp.Parameters.Append cmdApp.CreateParameter("@appid", 3, 1, , CLng(Trim(appItem)))
                cmdApp.Execute
                Set cmdApp = Nothing
            End If
        Next
    End If

    ' Add new applications
    If appsToAdd <> "" Then
        appList = Split(appsToAdd, ",")
        For Each appItem In appList
            If IsNumeric(Trim(appItem)) Then
                ' Check if already exists (but inactive)
                Dim rsExisting
                Set rsExisting = objConn.Execute("SELECT installedappid, isactive FROM installedapps WHERE machineid = " & CLng(newMachineId) & " AND appid = " & CLng(Trim(appItem)))
                If Not rsExisting.EOF Then
                    ' Reactivate existing record
                    sqlApp = "UPDATE installedapps SET isactive = 1 WHERE machineid = ? AND appid = ?"
                    Set cmdApp = Server.CreateObject("ADODB.Command")
                    cmdApp.ActiveConnection = objConn
                    cmdApp.CommandText = sqlApp
                    cmdApp.CommandType = 1
                    cmdApp.Parameters.Append cmdApp.CreateParameter("@machineid", 3, 1, , CLng(newMachineId))
                    cmdApp.Parameters.Append cmdApp.CreateParameter("@appid", 3, 1, , CLng(Trim(appItem)))
                    cmdApp.Execute
                    Set cmdApp = Nothing
                Else
                    ' Insert new record
                    sqlApp = "INSERT INTO installedapps (appid, machineid, isactive) VALUES (?, ?, 1)"
                    Set cmdApp = Server.CreateObject("ADODB.Command")
                    cmdApp.ActiveConnection = objConn
                    cmdApp.CommandText = sqlApp
                    cmdApp.CommandType = 1
                    cmdApp.Parameters.Append cmdApp.CreateParameter("@appid", 3, 1, , CLng(Trim(appItem)))
                    cmdApp.Parameters.Append cmdApp.CreateParameter("@machineid", 3, 1, , CLng(newMachineId))
                    cmdApp.Execute
                    Set cmdApp = Nothing
                End If
                rsExisting.Close
                Set rsExisting = Nothing
            End If
        Next
    End If
End If

' Success - show success message
objConn.Close
ShowSuccess deviceDisplayName & " saved successfully.", redirectUrl, deviceDisplayName
%>
