<%
'=============================================================================
' FILE: error_handler.asp
' PURPOSE: Centralized error handling and logging for the application
' CREATED: 2025-10-10
'=============================================================================

'-----------------------------------------------------------------------------
' FUNCTION: InitializeErrorHandling
' PURPOSE: Sets up error handling for a page
' PARAMETERS:
'   pageName (String) - Name of the current page for logging
'-----------------------------------------------------------------------------
Sub InitializeErrorHandling(pageName)
    On Error Resume Next
    Session("CurrentPage") = pageName
    Session("ErrorCount") = 0
End Sub

'-----------------------------------------------------------------------------
' FUNCTION: CheckForErrors
' PURPOSE: Checks if an error occurred and handles it appropriately
' NOTES: Call this after each critical database operation
'-----------------------------------------------------------------------------
Sub CheckForErrors()
    If Err.Number <> 0 Then
        Dim errNum, errDesc, errSource, pageName
        errNum = Err.Number
        errDesc = Err.Description
        errSource = Err.Source
        pageName = Session("CurrentPage")

        ' Log the error
        Call LogError(pageName, errNum, errDesc, errSource, Request.ServerVariables("REMOTE_ADDR"))

        ' Cleanup resources
        Call CleanupResources()

        ' Clear the error
        Err.Clear

        ' Redirect to error page with generic message
        Response.Redirect("error.asp?code=DATABASE_ERROR")
        Response.End
    End If
End Sub

'-----------------------------------------------------------------------------
' FUNCTION: HandleValidationError
' PURPOSE: Handles input validation errors
' PARAMETERS:
'   returnPage (String) - Page to redirect back to
'   errorCode (String) - Error code for user message
'-----------------------------------------------------------------------------
Sub HandleValidationError(returnPage, errorCode)
    Call CleanupResources()
    Response.Redirect(returnPage & "?error=" & Server.URLEncode(errorCode))
    Response.End
End Sub

'-----------------------------------------------------------------------------
' FUNCTION: LogError
' PURPOSE: Logs error details to a file
' PARAMETERS:
'   pageName (String) - Name of the page where error occurred
'   errNum (Integer) - Error number
'   errDesc (String) - Error description
'   errSource (String) - Error source
'   ipAddress (String) - IP address of the user
'-----------------------------------------------------------------------------
Function LogError(pageName, errNum, errDesc, errSource, ipAddress)
    On Error Resume Next

    Dim objFSO, objFile, logPath, logEntry, logFolder

    ' Create FileSystemObject
    Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

    ' Ensure logs directory exists
    logFolder = Server.MapPath("/logs")
    If Not objFSO.FolderExists(logFolder) Then
        objFSO.CreateFolder(logFolder)
    End If

    ' Set log file path
    logPath = logFolder & "\error_log_" & Year(Now()) & Right("0" & Month(Now()), 2) & ".txt"

    ' Open log file for appending
    Set objFile = objFSO.OpenTextFile(logPath, 8, True)

    ' Format log entry
    logEntry = Now() & " | " & _
               pageName & " | " & _
               "Error " & errNum & " | " & _
               errDesc & " | " & _
               errSource & " | " & _
               ipAddress

    ' Write to log
    objFile.WriteLine(logEntry)

    ' Cleanup
    objFile.Close
    Set objFile = Nothing
    Set objFSO = Nothing

    On Error Goto 0
End Function

'-----------------------------------------------------------------------------
' FUNCTION: CleanupResources
' PURPOSE: Closes all database connections and recordsets
' NOTES: This should be called before any Response.Redirect or Response.End
'-----------------------------------------------------------------------------
Sub CleanupResources()
    On Error Resume Next
    Dim objVar

    ' Try to close all possible recordsets
    ' Using Execute to avoid "variable is undefined" errors
    On Error Resume Next
    Execute("If IsObject(rs) Then: If rs.State = 1 Then rs.Close: Set rs = Nothing: End If")
    On Error Resume Next
    Execute("If IsObject(rs2) Then: If rs2.State = 1 Then rs2.Close: Set rs2 = Nothing: End If")
    On Error Resume Next
    Execute("If IsObject(rsCheck) Then: If rsCheck.State = 1 Then rsCheck.Close: Set rsCheck = Nothing: End If")
    On Error Resume Next
    Execute("If IsObject(rsStatus) Then: If rsStatus.State = 1 Then rsStatus.Close: Set rsStatus = Nothing: End If")
    On Error Resume Next
    Execute("If IsObject(rsApps) Then: If rsApps.State = 1 Then rsApps.Close: Set rsApps = Nothing: End If")
    On Error Resume Next
    Execute("If IsObject(rsSupportTeams) Then: If rsSupportTeams.State = 1 Then rsSupportTeams.Close: Set rsSupportTeams = Nothing: End If")

    ' Close database connection
    On Error Resume Next
    Execute("If IsObject(objConn) Then: If objConn.State = 1 Then objConn.Close: Set objConn = Nothing: End If")

    On Error Goto 0
End Sub

'-----------------------------------------------------------------------------
' FUNCTION: GetErrorMessage
' PURPOSE: Returns user-friendly error message based on error code
' PARAMETERS:
'   errorCode (String) - Error code
' RETURNS: String - User-friendly error message
'-----------------------------------------------------------------------------
Function GetErrorMessage(errorCode)
    Select Case UCase(errorCode)
        Case "INVALID_INPUT"
            GetErrorMessage = "The information you entered is invalid. Please check your input and try again."
        Case "NOT_FOUND"
            GetErrorMessage = "The requested item could not be found."
        Case "UNAUTHORIZED"
            GetErrorMessage = "You do not have permission to perform this action."
        Case "DATABASE_ERROR"
            GetErrorMessage = "A database error occurred. The error has been logged and will be investigated."
        Case "GENERAL_ERROR"
            GetErrorMessage = "An unexpected error occurred. Please try again later."
        Case "INVALID_ID"
            GetErrorMessage = "Invalid ID parameter provided."
        Case "REQUIRED_FIELD"
            GetErrorMessage = "Please fill in all required fields."
        Case "INVALID_EMAIL"
            GetErrorMessage = "Please enter a valid email address."
        Case "INVALID_IP"
            GetErrorMessage = "Please enter a valid IP address."
        Case "INVALID_SERIAL"
            GetErrorMessage = "Please enter a valid serial number (7-50 alphanumeric characters)."
        Case Else
            GetErrorMessage = "An error occurred. Please contact support if this problem persists."
    End Select
End Function
%>
