<!--#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"-->
<%
	' Initialize error handling
	Call InitializeErrorHandling("updatelink.asp")

	' Get form inputs
	Dim linkid, linkurl, shortdescription, keywords, appid
	linkid = Trim(Request.Form("linkid"))
	linkurl = Trim(Request.Form("linkurl"))
	shortdescription = Trim(Request.Form("shortdescription"))
	keywords = Trim(Request.Form("keywords"))
	appid = Trim(Request.Form("appid"))

	' Validate linkid
	If Not ValidateID(linkid) Then
		Call HandleValidationError("displayknowledgebase.asp", "INVALID_ID")
	End If

	' Validate required fields
	If Len(linkurl) = 0 Or Len(shortdescription) = 0 Or Len(appid) = 0 Then
		Call HandleValidationError("editlink.asp?linkid=" & Server.URLEncode(linkid), "REQUIRED_FIELD")
	End If

	' Validate URL format
	If Not ValidateURL(linkurl) Then
		Call HandleValidationError("editlink.asp?linkid=" & Server.URLEncode(linkid), "INVALID_INPUT")
	End If

	' Validate field lengths
	If Len(linkurl) > 2000 Then
		Call HandleValidationError("editlink.asp?linkid=" & Server.URLEncode(linkid), "INVALID_INPUT")
	End If

	If Len(shortdescription) > 500 Then
		Call HandleValidationError("editlink.asp?linkid=" & Server.URLEncode(linkid), "INVALID_INPUT")
	End If

	If Len(keywords) > 500 Then
		Call HandleValidationError("editlink.asp?linkid=" & Server.URLEncode(linkid), "INVALID_INPUT")
	End If

	' Validate appid is numeric
	If Not ValidateID(appid) Then
		Call HandleValidationError("editlink.asp?linkid=" & Server.URLEncode(linkid), "INVALID_ID")
	End If

	' Verify the application exists
	If Not RecordExists(objConn, "applications", "appid", appid) Then
		Call HandleValidationError("editlink.asp?linkid=" & Server.URLEncode(linkid), "NOT_FOUND")
	End If

	' Verify the knowledge base article exists
	If Not RecordExists(objConn, "knowledgebase", "linkid", linkid) Then
		Call HandleValidationError("displayknowledgebase.asp", "NOT_FOUND")
	End If

	' Update using parameterized query
	Dim strSQL, recordsAffected
	strSQL = "UPDATE knowledgebase SET linkurl = ?, shortdescription = ?, keywords = ?, appid = ?, lastupdated = NOW() WHERE linkid = ?"
	recordsAffected = ExecuteParameterizedUpdate(objConn, strSQL, Array(linkurl, shortdescription, keywords, appid, linkid))

	' Cleanup and redirect
	Call CleanupResources()

	If recordsAffected > 0 Then
		Response.Redirect("displayknowledgearticle.asp?linkid=" & Server.URLEncode(linkid) & "&status=updated")
	Else
		Response.Redirect("displayknowledgearticle.asp?linkid=" & Server.URLEncode(linkid) & "&status=error&msg=Could+not+update+article")
	End If
%>
