<%@ Language=VBScript %>
<%
Response.ContentType = "application/json"
%>
<!--#include file="./includes/sql.asp"-->
<%
' Get form inputs
Dim appname, appdescription
appname = Trim(Request.Form("appname"))
appdescription = Trim(Request.Form("appdescription"))

' Basic validation
If Len(appname) = 0 Then
	Response.Write("{""success"":false,""error"":""Application name is required""}")
	objConn.Close
	Response.End
End If

If Len(appname) > 50 Then
	Response.Write("{""success"":false,""error"":""Application name too long (max 50 characters)""}")
	objConn.Close
	Response.End
End If

If Len(appdescription) > 255 Then
	Response.Write("{""success"":false,""error"":""Description too long (max 255 characters)""}")
	objConn.Close
	Response.End
End If

' Escape single quotes
appname = Replace(appname, "'", "''")
appdescription = Replace(appdescription, "'", "''")

' Check if application already exists
Dim checkSQL, rsCheck
checkSQL = "SELECT appid FROM applications WHERE appname = '" & appname & "'"
Set rsCheck = objConn.Execute(checkSQL)

If Not rsCheck.EOF Then
	Response.Write("{""success"":false,""error"":""An application with this name already exists""}")
	rsCheck.Close
	Set rsCheck = Nothing
	objConn.Close
	Response.End
End If
rsCheck.Close
Set rsCheck = Nothing

' Get default support team ID (use 1 as default)
Dim defaultSupportTeamId
defaultSupportTeamId = 1

' Build INSERT statement with minimal required fields
Dim strSQL
strSQL = "INSERT INTO applications (appname, appdescription, supportteamid, isactive, isinstallable, ishidden, isprinter, islicenced) " & _
         "VALUES ('" & appname & "', '" & appdescription & "', " & defaultSupportTeamId & ", 1, 0, 0, 0, 0)"

On Error Resume Next
objConn.Execute strSQL

If Err.Number <> 0 Then
	Response.Write("{""success"":false,""error"":""Database error: " & Replace(Err.Description, """", "'") & """}")
	objConn.Close
	Response.End
End If

' Get the newly inserted ID
Dim newId, rsNewId
Set rsNewId = objConn.Execute("SELECT LAST_INSERT_ID() AS newid")
newId = rsNewId("newid")
rsNewId.Close
Set rsNewId = Nothing

' Return success with new ID
Response.Write("{""success"":true,""appid"":" & newId & ",""appname"":""" & Replace(appname, """", "'") & """}")

objConn.Close
%>
