<%@ Language=VBScript %>
<%
'=============================================================================
' FILE: apiemployeesearch.asp
' PURPOSE: Search employees by name for recognition autocomplete
' RETURNS: JSON array of matching employees with SSO, name, and picture
' USAGE: apiemployeesearch.asp?q=john&limit=10
'=============================================================================

Response.ContentType = "application/json"
Response.Charset = "UTF-8"
Response.AddHeader "Access-Control-Allow-Origin", "*"
Response.AddHeader "Cache-Control", "no-cache, no-store, must-revalidate"
%>
<!--#include file="./includes/sql.asp"-->
<%
On Error Resume Next

Dim searchTerm, maxResults
searchTerm = Trim(Request.QueryString("q"))
maxResults = Request.QueryString("limit")

If maxResults = "" Or Not IsNumeric(maxResults) Then
    maxResults = 10
Else
    maxResults = CLng(maxResults)
    If maxResults > 50 Then maxResults = 50
    If maxResults < 1 Then maxResults = 10
End If

' Validate search term
If Len(searchTerm) < 2 Then
    Response.Write "{""success"":false,""error"":""Search term must be at least 2 characters"",""results"":[]}"
    Response.End
End If

' Connect to employee database
Dim empConn, empCmd, empRs
Set empConn = Server.CreateObject("ADODB.Connection")
empConn.ConnectionString = GetEmployeeConnectionString()
empConn.Open

If Err.Number <> 0 Then
    Response.Write "{""success"":false,""error"":""" & JSEscape(Err.Description) & """,""results"":[]}"
    Response.End
End If

' Search by first name, last name, or full name
' Using parameterized query with LIKE
Set empCmd = Server.CreateObject("ADODB.Command")
empCmd.ActiveConnection = empConn
empCmd.CommandText = "SELECT SSO, First_Name, Last_Name, Team, Picture FROM employees " & _
                     "WHERE First_Name LIKE ? OR Last_Name LIKE ? " & _
                     "OR CONCAT(First_Name, ' ', Last_Name) LIKE ? " & _
                     "ORDER BY Last_Name, First_Name LIMIT ?"
empCmd.CommandType = 1

Dim searchPattern
searchPattern = "%" & searchTerm & "%"

empCmd.Parameters.Append empCmd.CreateParameter("@first", 200, 1, 100, searchPattern)
empCmd.Parameters.Append empCmd.CreateParameter("@last", 200, 1, 100, searchPattern)
empCmd.Parameters.Append empCmd.CreateParameter("@full", 200, 1, 100, searchPattern)
empCmd.Parameters.Append empCmd.CreateParameter("@limit", 3, 1, , maxResults)

Set empRs = empCmd.Execute()

If Err.Number <> 0 Then
    Response.Write "{""success"":false,""error"":""" & JSEscape(Err.Description) & """,""results"":[]}"
    empConn.Close
    Response.End
End If

' Build JSON response
Dim jsonOutput, isFirst
jsonOutput = "{""success"":true,""results"":["
isFirst = True

Do While Not empRs.EOF
    If Not isFirst Then jsonOutput = jsonOutput & ","
    isFirst = False

    Dim sso, firstName, lastName, team, picture, fullName
    sso = empRs("SSO") & ""
    firstName = empRs("First_Name") & ""
    lastName = empRs("Last_Name") & ""
    team = empRs("Team") & ""
    picture = empRs("Picture") & ""
    fullName = firstName & " " & lastName

    jsonOutput = jsonOutput & "{"
    jsonOutput = jsonOutput & """sso"":""" & JSEscape(sso) & ""","
    jsonOutput = jsonOutput & """firstName"":""" & JSEscape(firstName) & ""","
    jsonOutput = jsonOutput & """lastName"":""" & JSEscape(lastName) & ""","
    jsonOutput = jsonOutput & """team"":""" & JSEscape(team) & ""","
    jsonOutput = jsonOutput & """fullName"":""" & JSEscape(fullName) & ""","
    jsonOutput = jsonOutput & """picture"":""" & JSEscape(picture) & """"
    jsonOutput = jsonOutput & "}"

    empRs.MoveNext
Loop

jsonOutput = jsonOutput & "]}"

empRs.Close
empConn.Close
Set empRs = Nothing
Set empCmd = Nothing
Set empConn = Nothing

Response.Write jsonOutput

Function JSEscape(s)
    If IsNull(s) Then
        JSEscape = ""
        Exit Function
    End If
    Dim r
    r = s & ""
    r = Replace(r, "\", "\\")
    r = Replace(r, """", "\""")
    r = Replace(r, Chr(13), "")
    r = Replace(r, Chr(10), "\n")
    r = Replace(r, Chr(9), "\t")
    JSEscape = r
End Function
%>
