<!--#include file="./includes/sql.asp"-->
<%
	' Get the serial number from the form
	Dim serialnumber
	serialnumber = Trim(Request.Form("serialnumber"))

	' Basic validation - serial number should not be empty and should be alphanumeric-ish
	If serialnumber = "" Or Len(serialnumber) < 3 Or Len(serialnumber) > 100 Then
		objConn.Close
		Response.Redirect("./adddevice.asp?error=INVALID_SERIAL")
		Response.End
	End If

	' Escape quotes
	serialnumber = Replace(serialnumber, "'", "''")

	' Check if serial number already exists
	Dim checkSQL, rsCheck, existingPCID
	checkSQL = "SELECT pcid FROM pc WHERE serialnumber = '" & serialnumber & "'"
	Set rsCheck = objConn.Execute(checkSQL)

	If Not rsCheck.EOF Then
		' Serial number already exists - redirect to edit page
		existingPCID = rsCheck("pcid")
		rsCheck.Close
		objConn.Close
		Response.Redirect("./editdevice.asp?pcid=" & existingPCID & "&scanned=1")
		Response.End
	End If

	rsCheck.Close

	' Insert new device with minimal required fields and defaults
	' pcstatusid = 2 (Inventory)
	' isactive = 1
	' modelnumberid = 1 (default model)
	' requires_manual_machine_config = 0 (no manual config needed)
	' osid = 1 (default OS)
	' machinenumber = 'IT Closet' (default location for new devices)
	Dim insertSQL
	insertSQL = "INSERT INTO pc (serialnumber, pcstatusid, isactive, modelnumberid, requires_manual_machine_config, osid, machinenumber, dateadded) " & _
				"VALUES ('" & serialnumber & "', 2, 1, 1, 0, 1, 'IT Closet', NOW())"

	On Error Resume Next
	objConn.Execute insertSQL

	If Err.Number = 0 Then
		objConn.Close
		' Success - redirect back with success message
		Response.Redirect("./adddevice.asp?added=" & Server.URLEncode(Request.Form("serialnumber")))
	Else
		objConn.Close
		Response.Redirect("./adddevice.asp?error=db")
	End If
%>
