<%
'=============================================================================
' FILE: save_network_device.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" Then
    objConn.Close
    ShowError "Invalid device type.", "network_devices.asp"
    Response.End
End If

' Validate device ID
If deviceId = "" Then deviceId = "0"
If Not IsNumeric(deviceId) Then
    objConn.Close
    ShowError "Invalid device ID.", "network_devices.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 = "network_devices.asp?filter=IDF"
        deviceDisplayName = "IDF"
    Case "server"
        machineTypeId = 20
        nameField = "servername"
        redirectUrl = "network_devices.asp?filter=Server"
        deviceDisplayName = "Server"
    Case "switch"
        machineTypeId = 19
        nameField = "switchname"
        redirectUrl = "network_devices.asp?filter=Switch"
        deviceDisplayName = "Switch"
    Case "camera"
        machineTypeId = 18
        nameField = "cameraname"
        redirectUrl = "network_devices.asp?filter=Camera"
        deviceDisplayName = "Camera"
    Case "accesspoint"
        machineTypeId = 16
        nameField = "apname"
        redirectUrl = "network_devices.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.", "network_devices.asp"
    Response.End
End If

' Validate field lengths
If Len(deviceName) > 100 Or Len(description) > 255 Then
    objConn.Close
    ShowError "Field length exceeded.", "network_devices.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
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"))

' 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.", "network_devices.asp"
        Response.End
    End If

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

    ' Handle new vendor creation (nested)
    If newvendorid = "new" Then
        If newvendorname = "" Then
            objConn.Close
            ShowError "Vendor name is required.", "network_devices.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, "network_devices.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

    ' 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 <> "" 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, "network_devices.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.", "network_devices.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, "network_devices.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.", "network_devices.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 "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, 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("@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, "network_devices.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 = ?, 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("@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, "network_devices.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
        Dim sqlUpdateComm, cmdUpdateComm
        sqlUpdateComm = "UPDATE communications SET address = ?, macaddress = ? 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

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