<%
'=============================================================================
' FILE: savemachineedit.asp
' PURPOSE: Update existing machine with nested entity creation (vendor, model, business unit)
' SECURITY: Parameterized queries, HTML encoding, input validation
' CREATED: 2025-11-07 - Based on savemachinedirect.asp
' NOTE: Machines now inherit machinetypeid from their model. Each model has one machine type.
'=============================================================================
%>
<!--#include file="./includes/sql.asp"-->
<!--#include file="./includes/response.asp"-->
<!--#include file="./includes/db_helpers.asp"-->
<%
	' Get and validate all inputs
	Dim machineid, modelid, businessunitid, alias, machinenotes, mapleft, maptop, fqdn
	machineid = Trim(Request.Form("machineid"))
	modelid = Trim(Request.Form("modelid"))
	businessunitid = Trim(Request.Form("businessunitid"))
	alias = Trim(Request.Form("alias"))
	machinenotes = Trim(Request.Form("machinenotes"))
	mapleft = Trim(Request.Form("mapleft"))
	maptop = Trim(Request.Form("maptop"))
	fqdn = Trim(Request.Form("fqdn"))

	' Get form inputs for new business unit
	Dim newbusinessunit
	newbusinessunit = Trim(Request.Form("newbusinessunit"))

	' Get form inputs for new model
	Dim newmodelnumber, newvendorid, newmodelimage, newmodelmachinetypeid
	newmodelnumber = Trim(Request.Form("newmodelnumber"))
	newvendorid = Trim(Request.Form("newvendorid"))
	newmodelimage = Trim(Request.Form("newmodelimage"))
	newmodelmachinetypeid = Trim(Request.Form("newmodelmachinetypeid"))

	' Get form inputs for new vendor
	Dim newvendorname
	newvendorname = Trim(Request.Form("newvendorname"))

	' Get form inputs for new machine type
	Dim newmachinetype, newmachinedescription, newfunctionalaccountid
	newmachinetype = Trim(Request.Form("newmachinetype"))
	newmachinedescription = Trim(Request.Form("newmachinedescription"))
	newfunctionalaccountid = Trim(Request.Form("newfunctionalaccountid"))

	' Get form inputs for new functional account
	Dim newfunctionalaccount, newfunctionalaccountdescription
	newfunctionalaccount = Trim(Request.Form("newfunctionalaccount"))
	newfunctionalaccountdescription = Trim(Request.Form("newfunctionalaccountdescription"))

	' Validate required field - machineid
	If machineid = "" Or Not IsNumeric(machineid) Then
		objConn.Close
		ShowError "Machine ID is required and must be numeric.", "displaypcs.asp"
		Response.End
	End If

	' Validate machine exists
	Dim checkSQL, rsCheck, cmdCheck
	checkSQL = "SELECT COUNT(*) as cnt FROM machines WHERE machineid = ?"
	Set cmdCheck = Server.CreateObject("ADODB.Command")
	cmdCheck.ActiveConnection = objConn
	cmdCheck.CommandText = checkSQL
	cmdCheck.CommandType = 1
	cmdCheck.Parameters.Append cmdCheck.CreateParameter("@machineid", 3, 1, , CLng(machineid))
	Set rsCheck = cmdCheck.Execute
	If Not rsCheck.EOF Then
		If CLng(rsCheck("cnt")) = 0 Then
			rsCheck.Close
			Set rsCheck = Nothing
			Set cmdCheck = Nothing
			objConn.Close
			ShowError "Machine ID " & machineid & " does not exist.", "displaypcs.asp"
			Response.End
		End If
	End If
	rsCheck.Close
	Set rsCheck = Nothing
	Set cmdCheck = Nothing

	' Validate ID fields - allow "new" as a valid value
	If modelid <> "new" And Not IsNumeric(modelid) Then
		objConn.Close
		ShowError "Invalid model ID.", "editpc.asp?machineid=" & machineid
		Response.End
	End If

	If businessunitid <> "new" And Not IsNumeric(businessunitid) Then
		objConn.Close
		ShowError "Invalid business unit ID.", "editpc.asp?machineid=" & machineid
		Response.End
	End If

	' Validate field lengths
	If Len(alias) > 50 Then
		objConn.Close
		ShowError "Field length exceeded.", "editpc.asp?machineid=" & machineid
		Response.End
	End If

	' Handle new business unit creation
	If businessunitid = "new" Then
		If Len(newbusinessunit) = 0 Then
			objConn.Close
			ShowError "New business unit name is required.", "editpc.asp?machineid=" & machineid
			Response.End
		End If

		If Len(newbusinessunit) > 50 Then
			objConn.Close
			ShowError "Business unit name too long.", "editpc.asp?machineid=" & machineid
			Response.End
		End If

		' Insert new business unit using parameterized query
		Dim sqlNewBU, cmdNewBU
		sqlNewBU = "INSERT INTO businessunits (businessunit, isactive) VALUES (?, 1)"
		Set cmdNewBU = Server.CreateObject("ADODB.Command")
		cmdNewBU.ActiveConnection = objConn
		cmdNewBU.CommandText = sqlNewBU
		cmdNewBU.CommandType = 1
		cmdNewBU.Parameters.Append cmdNewBU.CreateParameter("@businessunit", 200, 1, 50, newbusinessunit)

		On Error Resume Next
		cmdNewBU.Execute

		If Err.Number <> 0 Then
			Dim buErrMsg
			buErrMsg = Err.Description
			Set cmdNewBU = Nothing
			objConn.Close
			ShowError "Error creating new business unit: " & buErrMsg, "editpc.asp?machineid=" & machineid
			Response.End
		End If

		' Get the newly created business unit ID
		Dim rsNewBU
		Set rsNewBU = objConn.Execute("SELECT LAST_INSERT_ID() AS newid")
		businessunitid = CLng(rsNewBU("newid"))
		rsNewBU.Close
		Set rsNewBU = Nothing
		Set cmdNewBU = Nothing
		On Error Goto 0
	End If

	' Handle new model creation
	If modelid = "new" Then
		If Len(newmodelnumber) = 0 Then
			objConn.Close
			ShowError "New model number is required.", "editpc.asp?machineid=" & machineid
			Response.End
		End If

		If Len(newvendorid) = 0 Then
			objConn.Close
			ShowError "Vendor is required for new model.", "editpc.asp?machineid=" & machineid
			Response.End
		End If

		' Handle new machine type creation (nested in new model)
		If newmodelmachinetypeid = "new" Then
			If Len(newmachinetype) = 0 Then
				objConn.Close
				ShowError "New machine type name is required.", "editpc.asp?machineid=" & machineid
				Response.End
			End If

			If Len(newfunctionalaccountid) = 0 Then
				objConn.Close
				ShowError "Functional account is required for new machine type.", "editpc.asp?machineid=" & machineid
				Response.End
			End If

			If Len(newmachinetype) > 50 Or Len(newmachinedescription) > 255 Then
				objConn.Close
				ShowError "Machine type field length exceeded.", "editpc.asp?machineid=" & machineid
				Response.End
			End If

			' Handle new functional account creation (nested in new machine type)
			If newfunctionalaccountid = "new" Then
				If Len(newfunctionalaccount) = 0 Then
					objConn.Close
					ShowError "New functional account name is required.", "editpc.asp?machineid=" & machineid
					Response.End
				End If

				If Len(newfunctionalaccount) > 50 Or Len(newfunctionalaccountdescription) > 255 Then
					objConn.Close
					ShowError "Functional account field length exceeded.", "editpc.asp?machineid=" & machineid
					Response.End
				End If

				' Insert new functional account using parameterized query
				Dim sqlNewFA, cmdNewFA
				sqlNewFA = "INSERT INTO functionalaccounts (functionalaccount, description, isactive) VALUES (?, ?, 1)"
				Set cmdNewFA = Server.CreateObject("ADODB.Command")
				cmdNewFA.ActiveConnection = objConn
				cmdNewFA.CommandText = sqlNewFA
				cmdNewFA.CommandType = 1
				cmdNewFA.Parameters.Append cmdNewFA.CreateParameter("@functionalaccount", 200, 1, 50, newfunctionalaccount)

				' Handle optional description
				If Len(newfunctionalaccountdescription) > 0 Then
					cmdNewFA.Parameters.Append cmdNewFA.CreateParameter("@description", 200, 1, 255, newfunctionalaccountdescription)
				Else
					cmdNewFA.Parameters.Append cmdNewFA.CreateParameter("@description", 200, 1, 255, Null)
				End If

				On Error Resume Next
				cmdNewFA.Execute

				If Err.Number <> 0 Then
					Dim faErrMsg
					faErrMsg = Err.Description
					Set cmdNewFA = Nothing
					objConn.Close
					ShowError "Error creating new functional account: " & faErrMsg, "editpc.asp?machineid=" & machineid
					Response.End
				End If

				' Get the newly created functional account ID
				Dim rsNewFA
				Set rsNewFA = objConn.Execute("SELECT LAST_INSERT_ID() AS newid")
				newfunctionalaccountid = CLng(rsNewFA("newid"))
				rsNewFA.Close
				Set rsNewFA = Nothing
				Set cmdNewFA = Nothing
				On Error Goto 0
			End If

			' Insert new machine type using parameterized query
			Dim sqlNewMT, cmdNewMT
			sqlNewMT = "INSERT INTO machinetypes (machinetype, machinedescription, functionalaccountid, 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, newmachinetype)

			' Handle optional description
			If Len(newmachinedescription) > 0 Then
				cmdNewMT.Parameters.Append cmdNewMT.CreateParameter("@machinedescription", 200, 1, 255, newmachinedescription)
			Else
				cmdNewMT.Parameters.Append cmdNewMT.CreateParameter("@machinedescription", 200, 1, 255, Null)
			End If

			cmdNewMT.Parameters.Append cmdNewMT.CreateParameter("@functionalaccountid", 3, 1, , CLng(newfunctionalaccountid))

			On Error Resume Next
			cmdNewMT.Execute

			If Err.Number <> 0 Then
				Dim mtErrMsg
				mtErrMsg = Err.Description
				Set cmdNewMT = Nothing
				objConn.Close
				ShowError "Error creating new machine type: " & mtErrMsg, "editpc.asp?machineid=" & machineid
				Response.End
			End If

			' Get the 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

		If Len(newmodelmachinetypeid) = 0 Or Not IsNumeric(newmodelmachinetypeid) Then
			objConn.Close
			ShowError "Machine type is required for new model.", "editpc.asp?machineid=" & machineid
			Response.End
		End If

		If Len(newmodelnumber) > 50 Or Len(newmodelimage) > 100 Then
			objConn.Close
			ShowError "Model field length exceeded.", "editpc.asp?machineid=" & machineid
			Response.End
		End If

		' Handle new vendor creation (nested)
		If newvendorid = "new" Then
			If Len(newvendorname) = 0 Then
				objConn.Close
				ShowError "New vendor name is required.", "editpc.asp?machineid=" & machineid
				Response.End
			End If

			If Len(newvendorname) > 50 Then
				objConn.Close
				ShowError "Vendor name too long.", "editpc.asp?machineid=" & machineid
				Response.End
			End If

			' Insert new vendor using parameterized query (with ismachine=1)
			Dim sqlNewVendor, cmdNewVendor
			sqlNewVendor = "INSERT INTO vendors (vendor, isactive, isprinter, ispc, ismachine) VALUES (?, 1, 0, 0, 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 vendorErrMsg
				vendorErrMsg = Err.Description
				Set cmdNewVendor = Nothing
				objConn.Close
				ShowError "Error creating new vendor: " & vendorErrMsg, "editpc.asp?machineid=" & machineid
				Response.End
			End If

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

		' Set default image if not specified
		Dim modelImageValue
		If Len(newmodelimage) > 0 Then
			modelImageValue = newmodelimage
		Else
			modelImageValue = "default.png"
		End If

		' Insert new model using parameterized query (including machinetypeid)
		Dim sqlNewModel, cmdNewModel
		sqlNewModel = "INSERT INTO models (modelnumber, vendorid, machinetypeid, image, 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))
		cmdNewModel.Parameters.Append cmdNewModel.CreateParameter("@machinetypeid", 3, 1, , CLng(newmodelmachinetypeid))
		cmdNewModel.Parameters.Append cmdNewModel.CreateParameter("@image", 200, 1, 100, modelImageValue)

		On Error Resume Next
		cmdNewModel.Execute

		If Err.Number <> 0 Then
			Dim modelErrMsg
			modelErrMsg = Err.Description
			Set cmdNewModel = Nothing
			objConn.Close
			ShowError "Error creating new model: " & modelErrMsg, "editpc.asp?machineid=" & machineid
			Response.End
		End If

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

	'=============================================================================
	' UPDATE MACHINES TABLE
	'=============================================================================
	Dim strSQL, cmdMachine, serialnumberVal, hostnameVal, aliasVal, machinenotesVal, fqdnVal, machinestatusidVal
	If Trim(Request.Form("serialnumber") & "") <> "" Then serialnumberVal = Trim(Request.Form("serialnumber") & "") Else serialnumberVal = Null
	If Trim(Request.Form("hostname") & "") <> "" Then hostnameVal = Trim(Request.Form("hostname") & "") Else hostnameVal = Null
	If alias <> "" Then aliasVal = alias Else aliasVal = Null
	If machinenotes <> "" Then machinenotesVal = machinenotes Else machinenotesVal = Null
	If fqdn <> "" Then fqdnVal = fqdn Else fqdnVal = Null
	machinestatusidVal = Trim(Request.Form("machinestatusid"))
	If machinestatusidVal = "" Or Not IsNumeric(machinestatusidVal) Then machinestatusidVal = 1

	strSQL = "UPDATE machines SET serialnumber = ?, hostname = ?, fqdn = ?, modelnumberid = ?, businessunitid = ?, alias = ?, machinenotes = ?, machinestatusid = ?, mapleft = ?, maptop = ? WHERE machineid = ?"

	Set cmdMachine = Server.CreateObject("ADODB.Command")
	cmdMachine.ActiveConnection = objConn
	cmdMachine.CommandText = strSQL
	cmdMachine.CommandType = 1
	cmdMachine.Parameters.Append cmdMachine.CreateParameter("@serialnumber", 200, 1, 100, serialnumberVal)
	cmdMachine.Parameters.Append cmdMachine.CreateParameter("@hostname", 200, 1, 255, hostnameVal)
	cmdMachine.Parameters.Append cmdMachine.CreateParameter("@fqdn", 200, 1, 255, fqdnVal)
	cmdMachine.Parameters.Append cmdMachine.CreateParameter("@modelnumberid", 3, 1, , CLng(modelid))
	cmdMachine.Parameters.Append cmdMachine.CreateParameter("@businessunitid", 3, 1, , CLng(businessunitid))
	cmdMachine.Parameters.Append cmdMachine.CreateParameter("@alias", 200, 1, 50, aliasVal)
	cmdMachine.Parameters.Append cmdMachine.CreateParameter("@machinenotes", 200, 1, 500, machinenotesVal)
	cmdMachine.Parameters.Append cmdMachine.CreateParameter("@machinestatusid", 3, 1, , CLng(machinestatusidVal))

	' Handle optional map coordinates
	If mapleft <> "" And maptop <> "" And IsNumeric(mapleft) And IsNumeric(maptop) Then
		cmdMachine.Parameters.Append cmdMachine.CreateParameter("@mapleft", 3, 1, , CLng(mapleft))
		cmdMachine.Parameters.Append cmdMachine.CreateParameter("@maptop", 3, 1, , CLng(maptop))
	Else
		cmdMachine.Parameters.Append cmdMachine.CreateParameter("@mapleft", 3, 1, , Null)
		cmdMachine.Parameters.Append cmdMachine.CreateParameter("@maptop", 3, 1, , Null)
	End If

	cmdMachine.Parameters.Append cmdMachine.CreateParameter("@machineid", 3, 1, , CLng(machineid))

	On Error Resume Next
	cmdMachine.Execute

	If Err.Number <> 0 Then
		Dim machineErrMsg
		machineErrMsg = Err.Description
		Set cmdMachine = Nothing
		objConn.Close
		ShowError "Error updating machine: " & machineErrMsg, "editpc.asp?machineid=" & machineid
		Response.End
	End If
	Set cmdMachine = Nothing
	On Error Goto 0

	'=============================================================================
	' DELETE OLD COMMUNICATIONS
	'=============================================================================
	Dim cmdDelComm
	Set cmdDelComm = Server.CreateObject("ADODB.Command")
	cmdDelComm.ActiveConnection = objConn
	cmdDelComm.CommandText = "DELETE FROM communications WHERE machineid = ? AND isactive = 1"
	cmdDelComm.CommandType = 1
	cmdDelComm.Parameters.Append cmdDelComm.CreateParameter("@machineid", 3, 1, , CLng(machineid))

	On Error Resume Next
	cmdDelComm.Execute
	Set cmdDelComm = Nothing
	On Error Goto 0

	'=============================================================================
	' INSERT NEW NETWORK COMMUNICATIONS (up to 3 interfaces)
	'=============================================================================
	' Get Network_Interface communication type ID
	Dim comstypeid
	Set rsCheck = objConn.Execute("SELECT comstypeid FROM comstypes WHERE typename = 'Network_Interface'")
	If Not rsCheck.EOF Then
		comstypeid = rsCheck("comstypeid")
		rsCheck.Close

		' Process up to 3 interfaces
		Dim ip1, mac1, ip2, mac2, ip3, mac3
		ip1 = Trim(Request.Form("ip1"))
		mac1 = Trim(Request.Form("mac1"))
		ip2 = Trim(Request.Form("ip2"))
		mac2 = Trim(Request.Form("mac2"))
		ip3 = Trim(Request.Form("ip3"))
		mac3 = Trim(Request.Form("mac3"))

		' Interface 1 (Primary)
		If ip1 <> "" Or mac1 <> "" Then
			Dim cmdComm1, ip1Val, mac1Val
			If ip1 <> "" Then ip1Val = ip1 Else ip1Val = Null
			If mac1 <> "" Then mac1Val = mac1 Else mac1Val = Null

			Set cmdComm1 = Server.CreateObject("ADODB.Command")
			cmdComm1.ActiveConnection = objConn
			cmdComm1.CommandText = "INSERT INTO communications (machineid, comstypeid, address, macaddress, interfacename, isprimary, isactive) VALUES (?, ?, ?, ?, ?, 1, 1)"
			cmdComm1.CommandType = 1
			cmdComm1.Parameters.Append cmdComm1.CreateParameter("@machineid", 3, 1, , CLng(machineid))
			cmdComm1.Parameters.Append cmdComm1.CreateParameter("@comstypeid", 3, 1, , comstypeid)
			cmdComm1.Parameters.Append cmdComm1.CreateParameter("@address", 200, 1, 50, ip1Val)
			cmdComm1.Parameters.Append cmdComm1.CreateParameter("@macaddress", 200, 1, 50, mac1Val)
			cmdComm1.Parameters.Append cmdComm1.CreateParameter("@interfacename", 200, 1, 50, "Interface 1")

			On Error Resume Next
			cmdComm1.Execute
			Set cmdComm1 = Nothing
			On Error Goto 0
		End If

		' Interface 2 (Optional)
		If ip2 <> "" Or mac2 <> "" Then
			Dim cmdComm2, ip2Val, mac2Val
			If ip2 <> "" Then ip2Val = ip2 Else ip2Val = Null
			If mac2 <> "" Then mac2Val = mac2 Else mac2Val = Null

			Set cmdComm2 = Server.CreateObject("ADODB.Command")
			cmdComm2.ActiveConnection = objConn
			cmdComm2.CommandText = "INSERT INTO communications (machineid, comstypeid, address, macaddress, interfacename, isprimary, isactive) VALUES (?, ?, ?, ?, ?, 0, 1)"
			cmdComm2.CommandType = 1
			cmdComm2.Parameters.Append cmdComm2.CreateParameter("@machineid", 3, 1, , CLng(machineid))
			cmdComm2.Parameters.Append cmdComm2.CreateParameter("@comstypeid", 3, 1, , comstypeid)
			cmdComm2.Parameters.Append cmdComm2.CreateParameter("@address", 200, 1, 50, ip2Val)
			cmdComm2.Parameters.Append cmdComm2.CreateParameter("@macaddress", 200, 1, 50, mac2Val)
			cmdComm2.Parameters.Append cmdComm2.CreateParameter("@interfacename", 200, 1, 50, "Interface 2")

			On Error Resume Next
			cmdComm2.Execute
			Set cmdComm2 = Nothing
			On Error Goto 0
		End If

		' Interface 3 (Optional)
		If ip3 <> "" Or mac3 <> "" Then
			Dim cmdComm3, ip3Val, mac3Val
			If ip3 <> "" Then ip3Val = ip3 Else ip3Val = Null
			If mac3 <> "" Then mac3Val = mac3 Else mac3Val = Null

			Set cmdComm3 = Server.CreateObject("ADODB.Command")
			cmdComm3.ActiveConnection = objConn
			cmdComm3.CommandText = "INSERT INTO communications (machineid, comstypeid, address, macaddress, interfacename, isprimary, isactive) VALUES (?, ?, ?, ?, ?, 0, 1)"
			cmdComm3.CommandType = 1
			cmdComm3.Parameters.Append cmdComm3.CreateParameter("@machineid", 3, 1, , CLng(machineid))
			cmdComm3.Parameters.Append cmdComm3.CreateParameter("@comstypeid", 3, 1, , comstypeid)
			cmdComm3.Parameters.Append cmdComm3.CreateParameter("@address", 200, 1, 50, ip3Val)
			cmdComm3.Parameters.Append cmdComm3.CreateParameter("@macaddress", 200, 1, 50, mac3Val)
			cmdComm3.Parameters.Append cmdComm3.CreateParameter("@interfacename", 200, 1, 50, "Interface 3")

			On Error Resume Next
			cmdComm3.Execute
			Set cmdComm3 = Nothing
			On Error Goto 0
		End If
	End If

	'=============================================================================
	' DELETE OLD MACHINE RELATIONSHIPS
	'=============================================================================
	Dim cmdDelRel
	Set cmdDelRel = Server.CreateObject("ADODB.Command")
	cmdDelRel.ActiveConnection = objConn
	cmdDelRel.CommandText = "DELETE FROM machinerelationships WHERE (machineid = ? OR related_machineid = ?) AND isactive = 1"
	cmdDelRel.CommandType = 1
	cmdDelRel.Parameters.Append cmdDelRel.CreateParameter("@machineid1", 3, 1, , CLng(machineid))
	cmdDelRel.Parameters.Append cmdDelRel.CreateParameter("@machineid2", 3, 1, , CLng(machineid))

	On Error Resume Next
	cmdDelRel.Execute
	Set cmdDelRel = Nothing
	On Error Goto 0

	'=============================================================================
	' INSERT NEW MACHINE RELATIONSHIPS
	'=============================================================================
	Dim controllingpc, dualpathid
	controllingpc = Trim(Request.Form("controllingpc"))
	dualpathid = Trim(Request.Form("dualpathid"))

	' Get relationship type IDs
	Dim controlsTypeID, dualpathTypeID
	Set rsCheck = objConn.Execute("SELECT relationshiptypeid FROM relationshiptypes WHERE relationshiptype = 'Controls'")
	If Not rsCheck.EOF Then controlsTypeID = rsCheck("relationshiptypeid")
	rsCheck.Close

	Set rsCheck = objConn.Execute("SELECT relationshiptypeid FROM relationshiptypes WHERE relationshiptype = 'Dualpath'")
	If Not rsCheck.EOF Then dualpathTypeID = rsCheck("relationshiptypeid")
	rsCheck.Close

	' Check if this machine is a PC (pctypeid IS NOT NULL) to determine relationship direction
	Dim isPC
	isPC = False
	Set rsCheck = objConn.Execute("SELECT pctypeid FROM machines WHERE machineid = " & CLng(machineid))
	If Not rsCheck.EOF Then
		isPC = Not IsNull(rsCheck("pctypeid"))
	End If
	rsCheck.Close

	' Create Controls relationship
	' For PCs: This PC (machineid) controls the selected equipment (controllingpc form value)
	' For Equipment: The selected PC (controllingpc form value) controls this equipment (machineid)
	On Error Resume Next
	Dim tempControllingPC
	tempControllingPC = 0
	If controllingpc <> "" And Len(controllingpc) > 0 Then
		If IsNumeric(controllingpc) Then
			tempControllingPC = CLng(controllingpc)
		End If
	End If
	On Error Goto 0

	If tempControllingPC > 0 Then
		Dim cmdRelPC
		Set cmdRelPC = Server.CreateObject("ADODB.Command")
		cmdRelPC.ActiveConnection = objConn
		cmdRelPC.CommandText = "INSERT INTO machinerelationships (machineid, related_machineid, relationshiptypeid, isactive) VALUES (?, ?, ?, 1)"
		cmdRelPC.CommandType = 1

		If isPC Then
			' PC page: This PC controls the equipment (PC is machineid, equipment is related_machineid)
			cmdRelPC.Parameters.Append cmdRelPC.CreateParameter("@machineid", 3, 1, , CLng(machineid))
			cmdRelPC.Parameters.Append cmdRelPC.CreateParameter("@related_machineid", 3, 1, , tempControllingPC)
		Else
			' Equipment page: The PC controls this equipment (PC is machineid, equipment is related_machineid)
			cmdRelPC.Parameters.Append cmdRelPC.CreateParameter("@machineid", 3, 1, , tempControllingPC)
			cmdRelPC.Parameters.Append cmdRelPC.CreateParameter("@related_machineid", 3, 1, , CLng(machineid))
		End If
		cmdRelPC.Parameters.Append cmdRelPC.CreateParameter("@relationshiptypeid", 3, 1, , controlsTypeID)

		On Error Resume Next
		cmdRelPC.Execute
		Set cmdRelPC = Nothing
		On Error Goto 0

		' Propagate controller to dualpath machines (only for equipment, not PC)
		If Not isPC Then
			Call PropagateControllerToDualpathMachines(objConn, CLng(machineid), tempControllingPC)
		End If
	End If

	' Create Dualpath relationship (bidirectional)
	On Error Resume Next
	Dim tempDualpathID
	tempDualpathID = 0
	If dualpathid <> "" And Len(dualpathid) > 0 Then
		If IsNumeric(dualpathid) Then
			tempDualpathID = CLng(dualpathid)
		End If
	End If
	On Error Goto 0

	If tempDualpathID > 0 Then
		Dim cmdRelDual1, cmdRelDual2
		' Direction 1: this machine -> dualpath machine
		Set cmdRelDual1 = Server.CreateObject("ADODB.Command")
		cmdRelDual1.ActiveConnection = objConn
		cmdRelDual1.CommandText = "INSERT INTO machinerelationships (machineid, related_machineid, relationshiptypeid, isactive) VALUES (?, ?, ?, 1)"
		cmdRelDual1.CommandType = 1
		cmdRelDual1.Parameters.Append cmdRelDual1.CreateParameter("@machineid", 3, 1, , CLng(machineid))
		cmdRelDual1.Parameters.Append cmdRelDual1.CreateParameter("@related_machineid", 3, 1, , tempDualpathID)
		cmdRelDual1.Parameters.Append cmdRelDual1.CreateParameter("@relationshiptypeid", 3, 1, , dualpathTypeID)

		On Error Resume Next
		cmdRelDual1.Execute
		Set cmdRelDual1 = Nothing

		' Direction 2: dualpath machine -> this machine
		Set cmdRelDual2 = Server.CreateObject("ADODB.Command")
		cmdRelDual2.ActiveConnection = objConn
		cmdRelDual2.CommandText = "INSERT INTO machinerelationships (machineid, related_machineid, relationshiptypeid, isactive) VALUES (?, ?, ?, 1)"
		cmdRelDual2.CommandType = 1
		cmdRelDual2.Parameters.Append cmdRelDual2.CreateParameter("@machineid", 3, 1, , tempDualpathID)
		cmdRelDual2.Parameters.Append cmdRelDual2.CreateParameter("@related_machineid", 3, 1, , CLng(machineid))
		cmdRelDual2.Parameters.Append cmdRelDual2.CreateParameter("@relationshiptypeid", 3, 1, , dualpathTypeID)

		cmdRelDual2.Execute
		Set cmdRelDual2 = Nothing
		On Error Goto 0

		' Propagate controller from dualpath partner if exists
		Call PropagateControllerFromDualpathMachine(objConn, CLng(machineid), tempDualpathID)

		' Sync equipment data between dualpath partners (controller type, model, comm config)
		Call SyncDualpathPartnerData(objConn, CLng(machineid), tempDualpathID)
	End If

	'=============================================================================
	' UPDATE OR INSERT COMPLIANCE DATA
	'=============================================================================
	Dim thirdpartymanaged, thirdpartyvendorid, otassetsystem, dodassettype
	thirdpartymanaged = Trim(Request.Form("thirdpartymanaged"))
	thirdpartyvendorid = Trim(Request.Form("thirdpartyvendorid"))
	otassetsystem = Trim(Request.Form("otassetsystem"))
	dodassettype = Trim(Request.Form("dodassettype"))

	' Handle new third party vendor creation
	If thirdpartyvendorid = "new" Then
		Dim newthirdpartyvendorname
		newthirdpartyvendorname = Trim(Request.Form("newthirdpartyvendorname"))

		If Len(newthirdpartyvendorname) = 0 Then
			objConn.Close
			ShowError "New third party vendor name is required.", "editpc.asp?machineid=" & machineid
			Response.End
		End If

		If Len(newthirdpartyvendorname) > 50 Then
			objConn.Close
			ShowError "Third party vendor name too long.", "editpc.asp?machineid=" & machineid
			Response.End
		End If

		' Insert new third party vendor
		Dim sqlNewTPVendor, cmdNewTPVendor
		sqlNewTPVendor = "INSERT INTO vendors (vendor, isactive, isprinter, ispc, ismachine) VALUES (?, 1, 0, 0, 0)"
		Set cmdNewTPVendor = Server.CreateObject("ADODB.Command")
		cmdNewTPVendor.ActiveConnection = objConn
		cmdNewTPVendor.CommandText = sqlNewTPVendor
		cmdNewTPVendor.CommandType = 1
		cmdNewTPVendor.Parameters.Append cmdNewTPVendor.CreateParameter("@vendor", 200, 1, 50, newthirdpartyvendorname)

		On Error Resume Next
		cmdNewTPVendor.Execute

		If Err.Number <> 0 Then
			Dim tpVendorErrMsg
			tpVendorErrMsg = Err.Description
			Set cmdNewTPVendor = Nothing
			objConn.Close
			ShowError "Error creating new third party vendor: " & tpVendorErrMsg, "editpc.asp?machineid=" & machineid
			Response.End
		End If

		' Get the newly created vendor ID
		Dim rsNewTPVendor
		Set rsNewTPVendor = objConn.Execute("SELECT LAST_INSERT_ID() AS newid")
		thirdpartyvendorid = CLng(rsNewTPVendor("newid"))
		rsNewTPVendor.Close
		Set rsNewTPVendor = Nothing
		Set cmdNewTPVendor = Nothing
		On Error Goto 0
	End If

	' Check if compliance record exists
	Dim complianceExists
	complianceExists = False
	Set rsCheck = objConn.Execute("SELECT COUNT(*) as cnt FROM compliance WHERE machineid = " & CLng(machineid))
	If Not rsCheck.EOF Then
		If CLng(rsCheck("cnt")) > 0 Then
			complianceExists = True
		End If
	End If
	rsCheck.Close

	If thirdpartymanaged <> "" Or thirdpartyvendorid <> "" Or otassetsystem <> "" Or dodassettype <> "" Then
		Dim cmdCompliance
		Set cmdCompliance = Server.CreateObject("ADODB.Command")
		cmdCompliance.ActiveConnection = objConn

		' Convert form value to database ENUM value
		Dim dbThirdPartyManaged
		If thirdpartymanaged = "Yes" Then
			dbThirdPartyManaged = "Y"
		Else
			dbThirdPartyManaged = "N"
		End If

		If complianceExists Then
			' UPDATE existing compliance record
			cmdCompliance.CommandText = "UPDATE compliance SET isthirdpartymanaged = ?, thirdpartymanager = ?, otassetdevicetype = ? WHERE machineid = ?"
			cmdCompliance.CommandType = 1
			cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@isthirdpartymanaged", 200, 1, 1, dbThirdPartyManaged)

			' Handle nullable thirdpartymanager
			If thirdpartyvendorid = "" Then
				cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@thirdpartymanager", 200, 1, 255, Null)
			Else
				cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@thirdpartymanager", 200, 1, 255, thirdpartyvendorid)
			End If

			' Handle nullable otassetdevicetype
			If dodassettype = "" Then
				cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@otassetdevicetype", 200, 1, 100, Null)
			Else
				cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@otassetdevicetype", 200, 1, 100, dodassettype)
			End If

			cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@machineid", 3, 1, , CLng(machineid))
		Else
			' INSERT new compliance record
			cmdCompliance.CommandText = "INSERT INTO compliance (machineid, isthirdpartymanaged, thirdpartymanager, otassetdevicetype) VALUES (?, ?, ?, ?)"
			cmdCompliance.CommandType = 1
			cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@machineid", 3, 1, , CLng(machineid))
			cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@isthirdpartymanaged", 200, 1, 1, dbThirdPartyManaged)

			' Handle nullable thirdpartymanager
			If thirdpartyvendorid = "" Then
				cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@thirdpartymanager", 200, 1, 255, Null)
			Else
				cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@thirdpartymanager", 200, 1, 255, thirdpartyvendorid)
			End If

			' Handle nullable otassetdevicetype
			If dodassettype = "" Then
				cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@otassetdevicetype", 200, 1, 100, Null)
			Else
				cmdCompliance.Parameters.Append cmdCompliance.CreateParameter("@otassetdevicetype", 200, 1, 100, dodassettype)
			End If
		End If

		On Error Resume Next
		cmdCompliance.Execute
		Set cmdCompliance = Nothing
		On Error Goto 0
	End If

	' Redirect to appropriate display page based on machine type
	Dim redirectUrl, entityName
	If isPC Then
		redirectUrl = "displaypc.asp?machineid=" & machineid
		entityName = "PC Details"
	Else
		redirectUrl = "displaymachine.asp?machineid=" & machineid
		entityName = "Machine Details"
	End If

	objConn.Close
	ShowSuccess "Machine updated successfully.", redirectUrl, entityName
%>
