<html>
<head>
<link rel="stylesheet" href="./style.css" type="text/css">
<!--#include file="./includes/sql.asp"-->
<!--#include file="./includes/validation.asp"-->
<!--#include file="./includes/encoding.asp"-->
<!--#include file="./includes/error_handler.asp"-->
<!--#include file="./includes/db_helpers.asp"-->
</head>

<body>
<div class="page">
<%
	'=============================================================================
	' FILE: savemachine.asp
	' PURPOSE: Create new machine with nested entity creation
	' REFACTORED: 2025-10-27 - Removed machinetypeid (now inherited from models table)
	' NOTE: Machines now inherit machinetypeid from their model. Each model has one machine type.
	'=============================================================================

	' Initialize error handling
	Call InitializeErrorHandling("savemachine.asp")

	' Get and validate all inputs
	Dim machinenumber, modelid, businessunitid, alias, machinenotes, mapleft, maptop
	machinenumber = Trim(Request.Form("machinenumber"))
	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"))

	' Validate required fields
	If machinenumber = "" Then
		Call HandleValidationError("addmachine.asp", "INVALID_INPUT")
	End If

	If Not ValidateID(modelid) Then
		Call HandleValidationError("addmachine.asp", "INVALID_ID")
	End If

	If Not ValidateID(businessunitid) Then
		Call HandleValidationError("addmachine.asp", "INVALID_ID")
	End If

	' Validate field lengths
	If Len(machinenumber) > 50 Then
		Call HandleValidationError("addmachine.asp", "INVALID_INPUT")
	End If

	If Len(alias) > 50 Then
		Call HandleValidationError("addmachine.asp", "INVALID_INPUT")
	End If

	' machinenotes is TEXT field, no length validation needed

	' Check if machine number already exists
	Dim checkSQL, rsCheck
	checkSQL = "SELECT COUNT(*) as cnt FROM machines WHERE machinenumber = ?"
	Set rsCheck = ExecuteParameterizedQuery(objConn, checkSQL, Array(machinenumber))
	If Not rsCheck.EOF Then
		If Not IsNull(rsCheck("cnt")) Then
			If CLng(rsCheck("cnt")) > 0 Then
				rsCheck.Close
				Set rsCheck = Nothing
				Response.Write("<div class='alert alert-danger'>Error: Machine number '" & Server.HTMLEncode(machinenumber) & "' already exists.</div>")
				Response.Write("<a href='addmachine.asp'>Go back</a>")
				Call CleanupResources()
				Response.End
			End If
		End If
	End If
	rsCheck.Close
	Set rsCheck = Nothing

	' Build INSERT statement with parameterized query
	' NOTE: machinetypeid is now inherited from models table and doesn't need to be specified
	Dim params, paramList
	strSQL = "INSERT INTO machines (machinenumber, modelnumberid, businessunitid"

	' Add optional fields to SQL
	If alias <> "" Then
		strSQL = strSQL & ", alias"
	End If
	If machinenotes <> "" Then
		strSQL = strSQL & ", machinenotes"
	End If
	If mapleft <> "" And maptop <> "" Then
		If IsNumeric(mapleft) And IsNumeric(maptop) Then
			strSQL = strSQL & ", mapleft, maptop"
		End If
	End If

	strSQL = strSQL & ", isactive, islocationonly) VALUES (?, ?, ?"

	' Build param list dynamically
	Dim paramCount
	paramCount = 3  ' Start with 3 required params

	' Count optional params
	If alias <> "" Then paramCount = paramCount + 1
	If machinenotes <> "" Then paramCount = paramCount + 1
	If mapleft <> "" And maptop <> "" Then
		If IsNumeric(mapleft) And IsNumeric(maptop) Then
			paramCount = paramCount + 2
		End If
	End If
	paramCount = paramCount + 2  ' For isactive and islocationonly

	' Initialize array with correct size
	ReDim paramList(paramCount - 1)
	Dim paramIndex
	paramIndex = 0

	' Add required fields
	paramList(paramIndex) = machinenumber
	paramIndex = paramIndex + 1
	paramList(paramIndex) = modelid
	paramIndex = paramIndex + 1
	paramList(paramIndex) = businessunitid
	paramIndex = paramIndex + 1

	' Add optional fields to param list
	If alias <> "" Then
		strSQL = strSQL & ", ?"
		paramList(paramIndex) = alias
		paramIndex = paramIndex + 1
	End If
	If machinenotes <> "" Then
		strSQL = strSQL & ", ?"
		paramList(paramIndex) = machinenotes
		paramIndex = paramIndex + 1
	End If
	If mapleft <> "" And maptop <> "" Then
		If IsNumeric(mapleft) And IsNumeric(maptop) Then
			strSQL = strSQL & ", ?, ?"
			paramList(paramIndex) = mapleft
			paramIndex = paramIndex + 1
			paramList(paramIndex) = maptop
			paramIndex = paramIndex + 1
		End If
	End If

	' Add isactive and islocationonly values
	strSQL = strSQL & ", ?, ?)"
	paramList(paramIndex) = 1  ' isactive = 1
	paramIndex = paramIndex + 1
	paramList(paramIndex) = 0  ' islocationonly = 0

	' Execute parameterized insert
	Dim recordsAffected
	recordsAffected = ExecuteParameterizedInsert(objConn, strSQL, paramList)

	' Get the new machine ID
	Dim newMachineId
	Set rsCheck = objConn.Execute("SELECT LAST_INSERT_ID() as newid")
	newMachineId = 0
	If Not rsCheck.EOF Then
		If Not IsNull(rsCheck("newid")) Then
			newMachineId = CLng(rsCheck("newid"))
		End If
	End If
	rsCheck.Close
	Set rsCheck = Nothing

	' Cleanup resources
	Call CleanupResources()

	' Redirect to display page
	If recordsAffected > 0 And newMachineId > 0 Then
%>
<meta http-equiv="refresh" content="0; url=./displaymachine.asp?machineid=<%=Server.HTMLEncode(newMachineId)%>">
<%
	Else
		Response.Write("Error: Machine was not added successfully.")
	End If
%>
</div>
</body>
</html>
