<%
'=============================================================================
' FILE: displaymachine.asp
' PURPOSE: Display detailed machine information with edit capability
' SECURITY: Parameterized queries, HTML encoding, input validation
' UPDATED: 2025-10-27 - Migrated to secure patterns
'=============================================================================
%><!DOCTYPE html>
<html lang="en">
<head>
  <!--#include file="./includes/header.asp"-->
  <!--#include file="./includes/sql.asp"-->
  <!--#include file="./includes/validation.asp"-->
  <!--#include file="./includes/db_helpers.asp"-->
  <link rel="stylesheet" href="./leaflet/leaflet.css">
  <script src="./leaflet/leaflet.js"></script>
</head>

<%
	theme = Request.Cookies("theme")
	If theme = "" Then
		theme = "bg-theme1"
	End If

	'=============================================================================
	' SECURITY: Validate machineid or machinenumber parameter
	' NOTE: This handles both database ID and machine number for flexibility
	'=============================================================================
	Dim machineid, machinenumber, paramValue
	machineid = GetSafeInteger("QS", "machineid", 0, 1, 999999)

	' If machineid not provided, try machinenumber parameter
	IF machineid = 0 THEN
		machinenumber = Request.QueryString("machinenumber")
		IF machinenumber <> "" THEN
			' Look up machineid by machinenumber
			Dim rsLookup, strLookupSQL
			strLookupSQL = "SELECT machineid FROM machines WHERE machinenumber = ? AND isactive = 1"
			Set rsLookup = ExecuteParameterizedQuery(objConn, strLookupSQL, Array(machinenumber))
			IF NOT rsLookup.EOF THEN
				machineid = rsLookup("machineid")
			END IF
			rsLookup.Close
			Set rsLookup = Nothing
		END IF
	ELSE
		' We have a machineid, but it might actually be a machine number
		' Try to look it up as a machineid first
		Dim rsCheck
		strLookupSQL = "SELECT machineid FROM machines WHERE machineid = ? AND isactive = 1"
		Set rsCheck = ExecuteParameterizedQuery(objConn, strLookupSQL, Array(machineid))

		' If no machine found with that machineid, try treating it as a machine number
		IF rsCheck.EOF THEN
			rsCheck.Close
			strLookupSQL = "SELECT machineid FROM machines WHERE machinenumber = ? AND isactive = 1"
			Set rsCheck = ExecuteParameterizedQuery(objConn, strLookupSQL, Array(CStr(machineid)))
			IF NOT rsCheck.EOF THEN
				machineid = rsCheck("machineid")
			ELSE
				machineid = 0  ' Not found
			END IF
		END IF
		rsCheck.Close
		Set rsCheck = Nothing
	END IF

	IF machineid = 0 THEN
		objConn.Close
		Response.Redirect("default.asp")
		Response.End
	END IF

	'=============================================================================
	' SECURITY: Use parameterized query to prevent SQL injection
	' PHASE 2: Removed pc and networkinterfaces tables (migrated to machines)
	' NOTE: Use explicit column names to avoid wildcard conflicts between tables
	'=============================================================================
	' Phase 2: Only query columns that actually exist in machines table
	' NOTE: machinetypeid is now sourced from models table (models.machinetypeid) not machines table
	strSQL = "SELECT machines.machineid, machines.machinenumber, machines.alias, machines.hostname, " & _
			"machines.serialnumber, machines.machinenotes, machines.mapleft, machines.maptop, " & _
			"machines.modelnumberid, machines.businessunitid, machines.printerid, machines.pctypeid, " & _
			"machines.loggedinuser, machines.osid, machines.machinestatusid, " & _
			"machines.controllertypeid, machines.controllerosid, machines.requires_manual_machine_config, " & _
			"machines.lastupdated, machines.fqdn, " & _
			"machinetypes.machinetype, " & _
			"models.modelnumber, models.image, models.machinetypeid, " & _
			"businessunits.businessunit, " & _
			"functionalaccounts.functionalaccount, functionalaccounts.functionalaccountid, " & _
			"vendors.vendor, vendors.vendorid, " & _
			"printers.ipaddress AS printerip, " & _
			"printers.printercsfname, printers.printerwindowsname, " & _
			"machinestatus.machinestatus " & _
			"FROM machines " & _
			"LEFT JOIN models ON machines.modelnumberid = models.modelnumberid " & _
			"LEFT JOIN machinetypes ON models.machinetypeid = machinetypes.machinetypeid " & _
			"LEFT JOIN businessunits ON machines.businessunitid = businessunits.businessunitid " & _
			"LEFT JOIN functionalaccounts ON machinetypes.functionalaccountid = functionalaccounts.functionalaccountid " & _
			"LEFT JOIN vendors ON models.vendorid = vendors.vendorid " & _
			"LEFT JOIN printers ON machines.printerid = printers.printerid " & _
			"LEFT JOIN machinestatus ON machines.machinestatusid = machinestatus.machinestatusid " & _
			"WHERE machines.machineid = " & CLng(machineid)

	Set rs = objConn.Execute(strSQL)

	' Check if machine exists
	If rs.EOF Then
		rs.Close
		Set rs = Nothing
		objConn.Close
		Response.Redirect("default.asp")
		Response.End
	End If
%>

<body class="bg-theme <%=Server.HTMLEncode(theme)%>">

<!-- start loader -->
   <div id="pageloader-overlay" class="visible incoming"><div class="loader-wrapper-outer"><div class="loader-wrapper-inner" ><div class="loader"></div></div></div></div>
   <!-- end loader -->
<!-- Start wrapper-->
 <div id="wrapper">
  <!--#include file="./includes/leftsidebar.asp"-->
<!--Start topbar header-->
  <!--#include file="./includes/topbarheader.asp"-->
<!--End topbar header-->
<div class="clearfix"></div>

  <div class="content-wrapper">
    <div class="container-fluid">

      <div class="row mt-3">
        <div class="col-lg-4">
           <div class="card profile-card-2">
            <div class="card-img-block">
                <img class="img-fluid" src="./images/machines/<%If Not IsNull(rs("image")) Then Response.Write(Server.HTMLEncode(rs("image") & "")) Else Response.Write("default.png") End If%>" alt="Card image cap">
            </div>
            <div class="card-body pt-5">
                <img src="./images/machines/<%If Not IsNull(rs("image")) Then Response.Write(Server.HTMLEncode(rs("image") & "")) Else Response.Write("default.png") End If%>" alt="profile-image" class="profile">
                <h5 class="card-title"><%=Server.HTMLEncode(rs("machinenumber") & "")%></h5>
          	<h5 class="card-title"><%=Server.HTMLEncode(rs("vendor") & "")%></h5>
                <h5 class="card-text"><%=Server.HTMLEncode(rs("machinetype") & "")%></h5>
                <%' machinedescription column doesn't exist in Phase 2 schema %>
                <p class="card-text"><%=Server.HTMLEncode(rs("machinenotes") & "")%></p>
            </div>

        </div>
        </div>

        <div class="col-lg-8">
           <div class="card">
            <div class="card-body">
            <ul class="nav nav-tabs nav-tabs-primary top-icon nav-justified">
                <li class="nav-item">
                    <a href="javascript:void();" data-target="#profile" data-toggle="pill" class="nav-link active"><i class="icon-wrench"></i> <span class="hidden-xs">Settings</span></a>
                </li>
                <li class="nav-item">
                    <a href="javascript:void();" data-target="#communications" data-toggle="pill" class="nav-link"><i class="zmdi zmdi-network"></i> <span class="hidden-xs">Network</span></a>
                </li>
                <li class="nav-item">
                    <a href="javascript:void();" data-target="#relationships" data-toggle="pill" class="nav-link"><i class="zmdi zmdi-link"></i> <span class="hidden-xs">Relationships</span></a>
                </li>
                <li class="nav-item">
                    <a href="javascript:void();" data-target="#compliance" data-toggle="pill" class="nav-link"><i class="zmdi zmdi-shield-security"></i> <span class="hidden-xs">Compliance</span></a>
                </li>
<% If Not IsNull(rs("pctypeid")) Then %>
                <li class="nav-item">
                    <a href="javascript:void();" data-target="#applications" data-toggle="pill" class="nav-link"><i class="zmdi zmdi-apps"></i> <span class="hidden-xs">Applications</span></a>
                </li>
<% End If %>
                <li class="nav-item">
                    <a href="./machineedit.asp?machineid=<%=Server.HTMLEncode(machineid)%>" class="nav-link" style="background: linear-gradient(45deg, #667eea 0%, #764ba2 100%); color: white;"><i class="zmdi zmdi-edit"></i> <span class="hidden-xs">Edit Machine</span></a>
                </li>
            </ul>
            <div class="tab-content p-3">
                <div class="tab-pane active" id="profile">
                    <h5 class="mb-3">Configuration</h5>
                    <div class="row">
                        <div class="col-md-3">
                            <p class="mb-2"><strong>Location:</strong></p>
                            <p class="mb-2"><strong>Status:</strong></p>
                            <p class="mb-2"><strong>Vendor:</strong></p>
                            <p class="mb-2"><strong>Model:</strong></p>
                            <p class="mb-2"><strong>Function:</strong></p>
                            <p class="mb-2"><strong>BU:</strong></p>
                            <p class="mb-2"><strong>IP Address:</strong></p>
                            <p class="mb-2"><strong>MAC Address:</strong></p>
                            <p class="mb-2"><strong>FQDN:</strong></p>
                            <p class="mb-2"><strong>Controlling PC:</strong></p>
                            <p class="mb-2"><strong>Printer:</strong></p>
                            <p>

                            </p>
                        </div>
                        <div class="col-md-5">
<%
Dim machineNumVal, vendorValM, modelValM, machineTypeVal, buVal, statusValM

' Get values and default to N/A if empty
machineNumVal = rs("machinenumber") & ""
If machineNumVal = "" Then machineNumVal = "N/A"

statusValM = rs("machinestatus") & ""
If statusValM = "" Then statusValM = "N/A"

vendorValM = rs("vendor") & ""
If vendorValM = "" Then vendorValM = "N/A"

modelValM = rs("modelnumber") & ""
If modelValM = "" Then modelValM = "N/A"

machineTypeVal = rs("machinetype") & ""
If machineTypeVal = "" Then machineTypeVal = "N/A"

buVal = rs("businessunit") & ""
If buVal = "" Then buVal = "N/A"
%>
                            <p class="mb-2">
<%
If machineNumVal <> "N/A" Then
%>
                                <span class="location-link" data-machineid="<%=Server.HTMLEncode(machineid)%>" style="cursor:pointer; color:#007bff;">
                                    <i class="zmdi zmdi-pin" style="margin-right:4px;"></i><%=Server.HTMLEncode(machineNumVal)%>
                                </span>
<%
Else
    Response.Write("N/A")
End If
%>
                            </p>
                            <p class="mb-2"><%=Server.HTMLEncode(statusValM)%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(vendorValM)%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(modelValM)%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(machineTypeVal)%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(buVal)%></p>
<%
' Get primary communication (IP and MAC) from communications table
Dim rsPrimaryCom, strPrimaryComSQL, primaryIP, primaryMAC
strPrimaryComSQL = "SELECT address, macaddress FROM communications WHERE machineid = ? AND isprimary = 1 AND isactive = 1 LIMIT 1"
Set rsPrimaryCom = ExecuteParameterizedQuery(objConn, strPrimaryComSQL, Array(machineid))

If Not rsPrimaryCom.EOF Then
    primaryIP = rsPrimaryCom("address") & ""
    primaryMAC = rsPrimaryCom("macaddress") & ""
Else
    ' Try to get first active communication if no primary set
    rsPrimaryCom.Close
    strPrimaryComSQL = "SELECT address, macaddress FROM communications WHERE machineid = ? AND isactive = 1 ORDER BY comid LIMIT 1"
    Set rsPrimaryCom = ExecuteParameterizedQuery(objConn, strPrimaryComSQL, Array(machineid))
    If Not rsPrimaryCom.EOF Then
        primaryIP = rsPrimaryCom("address") & ""
        primaryMAC = rsPrimaryCom("macaddress") & ""
    Else
        primaryIP = ""
        primaryMAC = ""
    End If
End If
rsPrimaryCom.Close
Set rsPrimaryCom = Nothing

' Display IP Address
If primaryIP <> "" Then
    Response.Write("<p class='mb-2'>" & Server.HTMLEncode(primaryIP) & "</p>")
Else
    Response.Write("<p class='mb-2'><span class='text-muted'>N/A</span></p>")
End If

' Display MAC Address
If primaryMAC <> "" Then
    Response.Write("<p class='mb-2'>" & Server.HTMLEncode(primaryMAC) & "</p>")
Else
    Response.Write("<p class='mb-2'><span class='text-muted'>N/A</span></p>")
End If

' Display FQDN
Dim fqdnVal
fqdnVal = rs("fqdn") & ""
If fqdnVal <> "" Then
    Response.Write("<p class='mb-2'>" & Server.HTMLEncode(fqdnVal) & "</p>")
Else
    Response.Write("<p class='mb-2'><span class='text-muted'>N/A</span></p>")
End If

' Get controlling PC from relationships - check both directions
' Direction 1: PC (machineid) controls this equipment (related_machineid)
' Direction 2: This equipment (machineid) is controlled by PC (related_machineid)
Dim rsControlPC, strControlPCSQL, controlPCHostname, controlPCID

' First check: PC controls this equipment (standard direction)
strControlPCSQL = "SELECT m.machineid, m.hostname, m.machinenumber FROM machinerelationships mr " & _
                  "JOIN relationshiptypes rt ON mr.relationshiptypeid = rt.relationshiptypeid " & _
                  "JOIN machines m ON mr.machineid = m.machineid " & _
                  "WHERE mr.related_machineid = ? AND rt.relationshiptype = 'Controls' AND mr.isactive = 1 " & _
                  "AND m.pctypeid IS NOT NULL LIMIT 1"
Set rsControlPC = ExecuteParameterizedQuery(objConn, strControlPCSQL, Array(machineid))

If rsControlPC.EOF Then
    rsControlPC.Close
    ' Second check: This equipment has relationship to PC (reverse direction)
    strControlPCSQL = "SELECT m.machineid, m.hostname, m.machinenumber FROM machinerelationships mr " & _
                      "JOIN relationshiptypes rt ON mr.relationshiptypeid = rt.relationshiptypeid " & _
                      "JOIN machines m ON mr.related_machineid = m.machineid " & _
                      "WHERE mr.machineid = ? AND rt.relationshiptype = 'Controls' AND mr.isactive = 1 " & _
                      "AND m.pctypeid IS NOT NULL LIMIT 1"
    Set rsControlPC = ExecuteParameterizedQuery(objConn, strControlPCSQL, Array(machineid))
End If

If Not rsControlPC.EOF Then
    controlPCHostname = rsControlPC("hostname") & ""
    controlPCID = rsControlPC("machineid")
    If controlPCHostname = "" Then controlPCHostname = rsControlPC("machinenumber") & ""
    Response.Write("<p class='mb-2'><a href='./displaypc.asp?machineid=" & controlPCID & "'>" & Server.HTMLEncode(controlPCHostname) & "</a></p>")
Else
    Response.Write("<p class='mb-2'><span class='text-muted'>N/A</span></p>")
End If
rsControlPC.Close
Set rsControlPC = Nothing

' SECURITY: HTML encode printer data to prevent XSS
' Printer data - check if exists (LEFT JOIN may return NULL)
If Not IsNull(rs("printerid")) And rs("printerid") <> "" Then
    Dim printerNameVal
    printerNameVal = rs("printerwindowsname") & ""
    If printerNameVal = "" Then printerNameVal = "Printer #" & rs("printerid")

    Response.Write("<p class='mb-2'><a href='./displayprinter.asp?printerid=" & Server.HTMLEncode(rs("printerid") & "") & "'>" & Server.HTMLEncode(printerNameVal) & "</a></p>")
Else
    Response.Write("<p class='mb-2'>N/A</p>")
End If
%>
                        </div>
                        <div class="col-md-12">
                             <div class="table-responsive">
                          </div>
                        </div>
                    </div>
                    <!--/row-->
                </div>
                <div class="tab-pane" id="communications">
                    <h5 class="mb-3">Network Communications</h5>
                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>IP Address</th>
                                    <th>MAC Address</th>
                                    <th>Interface</th>
                                    <th>Primary</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
<%
    ' Query communications for this machine
    strSQL2 = "SELECT c.*, ct.typename FROM communications c " & _
              "JOIN comstypes ct ON c.comstypeid = ct.comstypeid " & _
              "WHERE c.machineid = ? AND c.isactive = 1 ORDER BY c.isprimary DESC, c.comid ASC"
    Set rs2 = ExecuteParameterizedQuery(objConn, strSQL2, Array(machineid))

    If rs2.EOF Then
        Response.Write("<tr><td colspan='6' class='text-muted text-center'>No network communications configured</td></tr>")
    Else
        Do While Not rs2.EOF
            Dim ipAddr, macAddr, ifaceName, isPrimary, statusBadge
            ipAddr = rs2("address") & ""
            macAddr = rs2("macaddress") & ""
            ifaceName = rs2("interfacename") & ""
            isPrimary = rs2("isprimary")

            If ipAddr = "" Then ipAddr = "<span class='text-muted'>N/A</span>"
            If macAddr = "" Then macAddr = "<span class='text-muted'>N/A</span>"
            If ifaceName = "" Then ifaceName = "<span class='text-muted'>N/A</span>"

            If isPrimary Then
                statusBadge = "<span class='badge badge-success'>Primary</span>"
            Else
                statusBadge = ""
            End If

            Response.Write("<tr>")
            Response.Write("<td>" & Server.HTMLEncode(rs2("typename") & "") & "</td>")
            Response.Write("<td>" & ipAddr & "</td>")
            Response.Write("<td>" & macAddr & "</td>")
            Response.Write("<td>" & ifaceName & "</td>")
            Response.Write("<td>" & statusBadge & "</td>")
            Response.Write("<td><span class='badge badge-info'>Active</span></td>")
            Response.Write("</tr>")
            rs2.MoveNext
        Loop
    End If
    rs2.Close
    Set rs2 = Nothing
%>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="tab-pane" id="relationships">
                    <h5 class="mb-3">Machine Relationships</h5>

                    <!-- Controlling PCs -->
                    <h6 class="mt-3 mb-2"><i class="zmdi zmdi-desktop-mac"></i> Controlled By PC</h6>
                    <div class="table-responsive mb-4">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>PC Hostname</th>
                                    <th>IP Address</th>
                                    <th>Relationship</th>
                                </tr>
                            </thead>
                            <tbody>
<%
    ' Query PCs that control this machine (directly or via dualpath)
    ' Check both directions - the PC is identified by pctypeid IS NOT NULL
    ' Use GROUP_CONCAT to combine multiple IPs into one row per PC
    strSQL2 = "SELECT m.machineid, m.machinenumber, m.hostname, GROUP_CONCAT(DISTINCT c.address ORDER BY c.address SEPARATOR ', ') as address, 'Controls' as relationshiptype " & _
              "FROM machinerelationships mr " & _
              "JOIN machines m ON (mr.machineid = m.machineid OR mr.related_machineid = m.machineid) " & _
              "LEFT JOIN communications c ON m.machineid = c.machineid AND c.comstypeid IN (1, 3) AND c.isactive = 1 " & _
              "WHERE (mr.machineid = ? OR mr.related_machineid = ?) AND mr.relationshiptypeid = 3 " & _
              "  AND m.pctypeid IS NOT NULL AND m.machineid <> ? AND mr.isactive = 1 " & _
              "GROUP BY m.machineid, m.machinenumber, m.hostname"
    Set rs2 = ExecuteParameterizedQuery(objConn, strSQL2, Array(machineid, machineid, machineid))

    If rs2.EOF Then
        Response.Write("<tr><td colspan='3' class='text-muted text-center'>No controlling PC assigned</td></tr>")
    Else
        Do While Not rs2.EOF
            Dim pcHostname, pcIP, pcMachineID
            pcHostname = rs2("hostname") & ""
            pcIP = rs2("address") & ""
            pcMachineID = rs2("machineid")

            If pcHostname = "" Then pcHostname = rs2("machinenumber") & ""
            If pcIP = "" Then pcIP = "<span class='text-muted'>N/A</span>"

            Response.Write("<tr>")
            Response.Write("<td><a href='./displaypc.asp?machineid=" & pcMachineID & "'>" & Server.HTMLEncode(pcHostname) & "</a></td>")
            Response.Write("<td>" & pcIP & "</td>")
            Response.Write("<td><span class='badge badge-primary'>" & Server.HTMLEncode(rs2("relationshiptype") & "") & "</span></td>")
            Response.Write("</tr>")
            rs2.MoveNext
        Loop
    End If
    rs2.Close
    Set rs2 = Nothing
%>
                            </tbody>
                        </table>
                    </div>

                    <!-- Machines This Machine Controls -->
                    <h6 class="mt-3 mb-2"><i class="zmdi zmdi-arrow-right-top"></i> Machines Controlled by This Machine</h6>
                    <div class="table-responsive mb-4">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>Machine Number</th>
                                    <th>Type</th>
                                    <th>Model</th>
                                    <th>Relationship</th>
                                </tr>
                            </thead>
                            <tbody>
<%
    ' Query other machines related to this one (excluding Controls which is shown in "Controlled By PC" section)
    ' This shows relationships like Cluster Member, Backup For, Master-Slave, etc.
    strSQL2 = "SELECT m.machineid, m.machinenumber, mt.machinetype, mo.modelnumber, rt.relationshiptype " & _
              "FROM machinerelationships mr " & _
              "JOIN relationshiptypes rt ON mr.relationshiptypeid = rt.relationshiptypeid " & _
              "JOIN machines m ON mr.related_machineid = m.machineid " & _
              "LEFT JOIN models mo ON m.modelnumberid = mo.modelnumberid " & _
              "LEFT JOIN machinetypes mt ON mo.machinetypeid = mt.machinetypeid " & _
              "WHERE mr.machineid = ? AND rt.relationshiptype NOT IN ('Controls', 'Dualpath', 'Connected To') AND mr.isactive = 1"
    Set rs2 = ExecuteParameterizedQuery(objConn, strSQL2, Array(machineid))

    If rs2.EOF Then
        Response.Write("<tr><td colspan='4' class='text-muted text-center'>This machine does not control any other machines</td></tr>")
    Else
        Do While Not rs2.EOF
            Dim ctrlMachineNum, ctrlType, ctrlModel, ctrlMachineID
            ctrlMachineNum = rs2("machinenumber") & ""
            ctrlType = rs2("machinetype") & ""
            ctrlModel = rs2("modelnumber") & ""
            ctrlMachineID = rs2("machineid")

            If ctrlType = "" Then ctrlType = "<span class='text-muted'>N/A</span>"
            If ctrlModel = "" Then ctrlModel = "<span class='text-muted'>N/A</span>"

            Response.Write("<tr>")
            Response.Write("<td><a href='./displaymachine.asp?machineid=" & ctrlMachineID & "'>" & Server.HTMLEncode(ctrlMachineNum) & "</a></td>")
            Response.Write("<td>" & ctrlType & "</td>")
            Response.Write("<td>" & ctrlModel & "</td>")
            Response.Write("<td><span class='badge badge-info'>" & Server.HTMLEncode(rs2("relationshiptype") & "") & "</span></td>")
            Response.Write("</tr>")
            rs2.MoveNext
        Loop
    End If
    rs2.Close
    Set rs2 = Nothing
%>
                            </tbody>
                        </table>
                    </div>

                    <!-- Dualpath Relationships -->
                    <h6 class="mt-3 mb-2"><i class="zmdi zmdi-swap"></i> Dualpath / Redundant Machines</h6>
                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>Machine Number</th>
                                    <th>Type</th>
                                    <th>Model</th>
                                    <th>Relationship</th>
                                </tr>
                            </thead>
                            <tbody>
<%
    ' Query dualpath relationships
    strSQL2 = "SELECT m.machineid, m.machinenumber, mt.machinetype, mo.modelnumber, rt.relationshiptype " & _
              "FROM machinerelationships mr " & _
              "JOIN relationshiptypes rt ON mr.relationshiptypeid = rt.relationshiptypeid " & _
              "JOIN machines m ON mr.related_machineid = m.machineid " & _
              "LEFT JOIN models mo ON m.modelnumberid = mo.modelnumberid " & _
              "LEFT JOIN machinetypes mt ON mo.machinetypeid = mt.machinetypeid " & _
              "WHERE mr.machineid = ? AND rt.relationshiptype = 'Dualpath' AND mr.isactive = 1"
    Set rs2 = ExecuteParameterizedQuery(objConn, strSQL2, Array(machineid))

    If rs2.EOF Then
        Response.Write("<tr><td colspan='4' class='text-muted text-center'>No dualpath relationships</td></tr>")
    Else
        Do While Not rs2.EOF
            Dim dualMachineNum, dualType, dualModel, dualMachineID
            dualMachineNum = rs2("machinenumber") & ""
            dualType = rs2("machinetype") & ""
            dualModel = rs2("modelnumber") & ""
            dualMachineID = rs2("machineid")

            If dualType = "" Then dualType = "<span class='text-muted'>N/A</span>"
            If dualModel = "" Then dualModel = "<span class='text-muted'>N/A</span>"

            Response.Write("<tr>")
            Response.Write("<td><a href='./displaymachine.asp?machineid=" & dualMachineID & "'>" & Server.HTMLEncode(dualMachineNum) & "</a></td>")
            Response.Write("<td>" & dualType & "</td>")
            Response.Write("<td>" & dualModel & "</td>")
            Response.Write("<td><span class='badge badge-warning'>" & Server.HTMLEncode(rs2("relationshiptype") & "") & "</span></td>")
            Response.Write("</tr>")
            rs2.MoveNext
        Loop
    End If
    rs2.Close
    Set rs2 = Nothing
%>
                            </tbody>
                        </table>
                    </div>

                    <!-- Network Device Connections (Connected To) -->
                    <h6 class="mt-3 mb-2"><i class="zmdi zmdi-network"></i> Network Connections</h6>
                    <div class="table-responsive">
                        <table class="table table-hover table-sm">
                            <thead>
                                <tr>
                                    <th>Machine #</th>
                                    <th>Name/Description</th>
                                    <th>Type</th>
                                    <th>Relationship</th>
                                </tr>
                            </thead>
                            <tbody>
<%
    ' Query devices this machine is connected to (e.g., Camera -> IDF)
    strSQL2 = "SELECT m.machineid, m.machinenumber, m.alias, mt.machinetype, rt.relationshiptype " & _
              "FROM machinerelationships mr " & _
              "JOIN relationshiptypes rt ON mr.relationshiptypeid = rt.relationshiptypeid " & _
              "LEFT JOIN machines m ON mr.related_machineid = m.machineid " & _
              "LEFT JOIN models mo ON m.modelnumberid = mo.modelnumberid " & _
              "LEFT JOIN machinetypes mt ON mo.machinetypeid = mt.machinetypeid " & _
              "WHERE mr.machineid = ? AND rt.relationshiptype = 'Connected To' AND mr.isactive = 1"
    Set rs2 = ExecuteParameterizedQuery(objConn, strSQL2, Array(machineid))

    If Not rs2.EOF Then
        While Not rs2.EOF
            Dim connAlias, connType
            connAlias = "" : If Not IsNull(rs2("alias")) Then connAlias = rs2("alias") & ""
            connType = "" : If Not IsNull(rs2("machinetype")) Then connType = rs2("machinetype") & ""

            Response.Write("<tr>")
            Response.Write("<td><a href='displaymachine.asp?machineid=" & rs2("machineid") & "'>" & Server.HTMLEncode(rs2("machinenumber") & "") & "</a></td>")
            Response.Write("<td>" & Server.HTMLEncode(connAlias) & "</td>")
            Response.Write("<td>" & Server.HTMLEncode(connType) & "</td>")
            Response.Write("<td><span class='badge badge-success'>" & Server.HTMLEncode(rs2("relationshiptype") & "") & "</span></td>")
            Response.Write("</tr>")
            rs2.MoveNext
        Wend
    Else
        Response.Write("<tr><td colspan='4' class='text-muted'>No network connections</td></tr>")
    End If
    rs2.Close

    ' Query devices connected to this machine (e.g., IDF -> Cameras)
    strSQL2 = "SELECT m.machineid, m.machinenumber, m.alias, mt.machinetype, rt.relationshiptype " & _
              "FROM machinerelationships mr " & _
              "JOIN relationshiptypes rt ON mr.relationshiptypeid = rt.relationshiptypeid " & _
              "LEFT JOIN machines m ON mr.machineid = m.machineid " & _
              "LEFT JOIN models mo ON m.modelnumberid = mo.modelnumberid " & _
              "LEFT JOIN machinetypes mt ON mo.machinetypeid = mt.machinetypeid " & _
              "WHERE mr.related_machineid = ? AND rt.relationshiptype = 'Connected To' AND mr.isactive = 1"
    Set rs2 = ExecuteParameterizedQuery(objConn, strSQL2, Array(machineid))

    If Not rs2.EOF Then
        While Not rs2.EOF
            Dim connToAlias, connToType
            connToAlias = "" : If Not IsNull(rs2("alias")) Then connToAlias = rs2("alias") & ""
            connToType = "" : If Not IsNull(rs2("machinetype")) Then connToType = rs2("machinetype") & ""

            Response.Write("<tr>")
            Response.Write("<td><a href='displaymachine.asp?machineid=" & rs2("machineid") & "'>" & Server.HTMLEncode(rs2("machinenumber") & "") & "</a></td>")
            Response.Write("<td>" & Server.HTMLEncode(connToAlias) & "</td>")
            Response.Write("<td>" & Server.HTMLEncode(connToType) & "</td>")
            Response.Write("<td><span class='badge badge-info'>Connected From</span></td>")
            Response.Write("</tr>")
            rs2.MoveNext
        Wend
    End If
    rs2.Close
    Set rs2 = Nothing
%>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="tab-pane" id="compliance">
                    <h5 class="mb-3">Compliance & Security</h5>
<%
    ' Query compliance data
    strSQL2 = "SELECT * FROM compliance WHERE machineid = ?"
    Set rs2 = ExecuteParameterizedQuery(objConn, strSQL2, Array(machineid))

    If Not rs2.EOF Then
%>
                    <div class="row">
                        <div class="col-md-4">
                            <p class="mb-2"><strong>Third Party Managed:</strong></p>
                            <p class="mb-2"><strong>Third Party Manager:</strong></p>
                            <p class="mb-2"><strong>OT Asset System:</strong></p>
                            <p class="mb-2"><strong>DoD Asset Device Type:</strong></p>
                            <p class="mb-2"><strong>Compliant:</strong></p>
                        </div>
                        <div class="col-md-8">
<%
        Dim thirdPartyManaged, thirdPartyManager, otAssetSystem, dodAssetDeviceType, isCompliant
        thirdPartyManaged = rs2("isthirdpartymanaged") & ""
        thirdPartyManager = rs2("thirdpartymanager") & ""
        otAssetSystem = rs2("otenvironment") & ""
        dodAssetDeviceType = rs2("otassetdevicetype") & ""
        isCompliant = rs2("ischangerestricted") & ""

        ' Third party managed badge
        Dim tpmBadge
        If thirdPartyManaged = "Y" Then
            tpmBadge = "<span class='badge badge-warning'>Yes</span>"
        ElseIf thirdPartyManaged = "N" Then
            tpmBadge = "<span class='badge badge-success'>No</span>"
        Else
            tpmBadge = "<span class='badge badge-secondary'>N/A</span>"
        End If
%>
                            <p class="mb-2"><%=tpmBadge%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(thirdPartyManager)%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(otAssetSystem)%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(dodAssetDeviceType)%></p>
                            <p class="mb-2">
<%
        If isCompliant = "Y" Then
            Response.Write("<span class='badge badge-success'>Yes</span>")
        ElseIf isCompliant = "N" Then
            Response.Write("<span class='badge badge-danger'>No</span>")
        Else
            Response.Write("<span class='badge badge-secondary'>Not Assessed</span>")
        End If
%>
                            </p>
                        </div>
                    </div>

                    <hr style="margin:20px 0;">

                    <h6 class="mb-3"><i class="zmdi zmdi-shield-check"></i> Security Scans</h6>
                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>Scan Name</th>
                                    <th>Date</th>
                                    <th>Result</th>
                                    <th>Details</th>
                                </tr>
                            </thead>
                            <tbody>
<%
        rs2.Close
        Set rs2 = Nothing

        ' Query security scans
        strSQL2 = "SELECT * FROM compliancescans WHERE machineid = ? ORDER BY scandate DESC LIMIT 10"
        Set rs2 = ExecuteParameterizedQuery(objConn, strSQL2, Array(machineid))

        If rs2.EOF Then
            Response.Write("<tr><td colspan='4' class='text-muted text-center'>No security scans recorded</td></tr>")
        Else
            Do While Not rs2.EOF
                Dim scanName, scanDate, scanResult, scanDetails, resultBadge
                scanName = rs2("scanname") & ""
                scanDate = rs2("scandate") & ""
                scanResult = rs2("scanresult") & ""
                scanDetails = rs2("scandetails") & ""

                If scanName = "" Then scanName = "Security Scan"
                If scanDetails = "" Then scanDetails = "<span class='text-muted'>No details</span>"

                ' Result badge
                Select Case LCase(scanResult)
                    Case "pass"
                        resultBadge = "<span class='badge badge-success'>Pass</span>"
                    Case "fail"
                        resultBadge = "<span class='badge badge-danger'>Fail</span>"
                    Case "warning"
                        resultBadge = "<span class='badge badge-warning'>Warning</span>"
                    Case Else
                        resultBadge = "<span class='badge badge-info'>Info</span>"
                End Select

                Response.Write("<tr>")
                Response.Write("<td>" & Server.HTMLEncode(scanName) & "</td>")
                Response.Write("<td>" & Server.HTMLEncode(scanDate) & "</td>")
                Response.Write("<td>" & resultBadge & "</td>")
                Response.Write("<td>" & scanDetails & "</td>")
                Response.Write("</tr>")
                rs2.MoveNext
            Loop
        End If
        rs2.Close
        Set rs2 = Nothing
%>
                            </tbody>
                        </table>
                    </div>
<%
    Else
        Response.Write("<p class='text-muted'>No compliance data available for this machine.</p>")
        rs2.Close
        Set rs2 = Nothing
    End If
%>
                </div>
<% If Not IsNull(rs("pctypeid")) Then %>
                <div class="tab-pane" id="applications">
                  <div class="table-responsive">
                    <table class="table table-hover table-striped">
                        <tbody>
<%
	'=============================================================================
	' SECURITY: Use parameterized query for installed applications
	'=============================================================================
	Dim appDisplay, appVer
	strSQL2 = "SELECT a.appname, av.version FROM installedapps ia " & _
			"JOIN applications a ON ia.appid = a.appid " & _
			"LEFT JOIN appversions av ON ia.appversionid = av.appversionid " & _
			"WHERE ia.isactive = 1 AND ia.machineid = ? ORDER BY a.appname ASC"
	Set rs2 = ExecuteParameterizedQuery(objConn, strSQL2, Array(machineid))
	Do While Not rs2.EOF
		appDisplay = Server.HTMLEncode(rs2("appname") & "")
		appVer = rs2("version") & ""
		If appVer <> "" Then appDisplay = appDisplay & " <span class='text-muted'>v" & Server.HTMLEncode(appVer) & "</span>"
		Response.Write("<tr><td><span class='float-left font-weight-bold'>" & appDisplay & "</span></td></tr>")
		rs2.MoveNext
	Loop
	rs2.Close
	Set rs2 = Nothing
%>
                        </tbody>
                    </table>
                  </div>
                </div>
<% End If %>
      </div>
      </div>

    </div>

	<!--start overlay-->
		  <div class="overlay toggle-menu"></div>
		<!--end overlay-->

    </div>
    <!-- End container-fluid-->
   </div><!--End content-wrapper-->
   <!--Start Back To Top Button-->
    <a href="javaScript:void();" class="back-to-top"><i class="fa fa-angle-double-up"></i> </a>
    <!--End Back To Top Button-->

	<!--Start footer-->
	<footer class="footer">
      <div class="container">
        <div class="text-center">
        </div>
      </div>
    </footer>
	<!--End footer-->
  </div><!--End wrapper-->


  <!-- Bootstrap core JavaScript-->
  <script src="assets/js/jquery.min.js"></script>
  <script src="assets/js/popper.min.js"></script>
  <script src="assets/js/bootstrap.min.js"></script>

  <!-- simplebar js -->
  <script src="assets/plugins/simplebar/js/simplebar.js"></script>
  <!-- sidebar-menu js -->
  <script src="assets/js/sidebar-menu.js"></script>

  <!-- Custom scripts -->
  <script src="assets/js/app-script.js"></script>

  <!-- Location map popup modal -->
  <style>
  .content-wrapper {
      padding-bottom: 80px;
  }
  .footer {
      position: relative !important;
      bottom: auto !important;
  }

  /* Theme-specific styling for better visibility */
  body.bg-theme1 .location-link,
  body.bg-theme2 .location-link,
  body.bg-theme3 .location-link,
  body.bg-theme4 .location-link,
  body.bg-theme5 .location-link,
  body.bg-theme6 .location-link,
  body.bg-theme7 .location-link,
  body.bg-theme8 .location-link,
  body.bg-theme9 .location-link,
  body.bg-theme10 .location-link,
  body.bg-theme11 .location-link,
  body.bg-theme12 .location-link,
  body.bg-theme13 .location-link,
  body.bg-theme14 .location-link,
  body.bg-theme15 .location-link,
  body.bg-theme16 .location-link {
      color: #fff !important;
  }

  /* Theme-specific popup header colors */
  body.bg-theme1 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme2 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme3 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme4 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme5 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme6 .location-popup-header { background: linear-gradient(45deg, #3a3a3a, #4a4a4a); }
  body.bg-theme7 .location-popup-header { background: linear-gradient(45deg, #0c675e, #069e90); }
  body.bg-theme8 .location-popup-header { background: linear-gradient(45deg, #a52a04, #4f5f58); }
  body.bg-theme9 .location-popup-header { background: linear-gradient(45deg, #29323c, #485563); }
  body.bg-theme10 .location-popup-header { background: linear-gradient(45deg, #795548, #945c48); }
  body.bg-theme11 .location-popup-header { background: linear-gradient(45deg, #1565C0, #1E88E5); }
  body.bg-theme12 .location-popup-header { background: linear-gradient(45deg, #65379b, #886aea); }
  body.bg-theme13 .location-popup-header { background: linear-gradient(45deg, #ff5447, #f1076f); }
  body.bg-theme14 .location-popup-header { background: linear-gradient(45deg, #08a50e, #69bb03); }
  body.bg-theme15 .location-popup-header { background: linear-gradient(45deg, #6a11cb, #2575fc); }
  body.bg-theme16 .location-popup-header { background: linear-gradient(45deg, #6a11cb, #cccccc); }

  .location-popup-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      z-index: 9998;
      display: none;
  }
  .location-popup {
      position: fixed;
      background: #1f1f1f;
      border: 2px solid #667eea;
      border-radius: 8px;
      box-shadow: 0 10px 40px rgba(0, 0, 0, 0.8);
      z-index: 9999;
      display: none;
      max-width: 90vw;
      max-height: 90vh;
  }
  .location-popup-header {
      background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 12px 15px;
      border-radius: 6px 6px 0 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
  }
  .location-popup-close {
      background: none;
      border: none;
      color: white;
      font-size: 24px;
      cursor: pointer;
      padding: 0;
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
  }
  .location-popup-close:hover {
      background: rgba(255, 255, 255, 0.2);
  }
  .location-popup-body {
      padding: 0;
      background: #2a2a2a;
  }
  .location-popup iframe {
      display: block;
      border: none;
      border-radius: 0 0 6px 6px;
  }
  .location-link:hover {
      text-decoration: underline;
  }
  </style>

  <script>
  $(document).ready(function() {
      var $overlay = $('<div class="location-popup-overlay"></div>').appendTo('body');
      var $popup = $('<div class="location-popup"></div>').appendTo('body');

      $popup.html(
          '<div class="location-popup-header">' +
              '<h6 style="margin:0; font-size:16px;"><i class="zmdi zmdi-pin"></i> <span class="location-title">Loading...</span></h6>' +
              '<button class="location-popup-close" title="Close (Esc)">&times;</button>' +
          '</div>' +
          '<div class="location-popup-body">' +
              '<iframe src="" width="440" height="340"></iframe>' +
          '</div>'
      );

      var $iframe = $popup.find('iframe');
      var $title = $popup.find('.location-title');
      var currentMachineId = null;

      function showLocationPopup(machineId, locationName, mouseEvent) {
          if (currentMachineId === machineId && $popup.is(':visible')) {
              return;
          }

          currentMachineId = machineId;
          $title.text('Machine ' + locationName);
          $iframe.attr('src', './displaylocation.asp?machineid=' + machineId);

          var popupWidth = 440;
          var popupHeight = 400;
          var mouseX = mouseEvent.clientX;
          var mouseY = mouseEvent.clientY;
          var windowWidth = window.innerWidth;
          var windowHeight = window.innerHeight;

          var left, top;

          left = mouseX + 10;
          if (left + popupWidth > windowWidth - 10) {
              left = mouseX - popupWidth - 10;
          }
          if (left < 10) {
              left = 10;
          }

          var spaceBelow = windowHeight - mouseY;
          var spaceAbove = mouseY;

          if (spaceBelow >= popupHeight + 20) {
              top = mouseY + 10;
          } else if (spaceAbove >= popupHeight + 20) {
              top = mouseY - popupHeight - 10;
          } else {
              top = Math.max(10, (windowHeight - popupHeight) / 2);
          }

          if (top < 10) {
              top = 10;
          }
          if (top + popupHeight > windowHeight - 10) {
              top = windowHeight - popupHeight - 10;
          }

          $popup.css({
              left: left + 'px',
              top: top + 'px',
              display: 'block'
          });

          $overlay.fadeIn(200);
          $popup.fadeIn(200);
      }

      function hideLocationPopup() {
          $overlay.fadeOut(200);
          $popup.fadeOut(200);
          setTimeout(function() {
              $iframe.attr('src', '');
              currentMachineId = null;
          }, 200);
      }

      var hoverTimer = null;

      $('.location-link').on('mouseenter', function(e) {
          var $link = $(this);
          var machineId = $link.data('machineid');
          var locationName = $link.text().trim();
          var mouseEvent = e;

          if (hoverTimer) {
              clearTimeout(hoverTimer);
          }

          hoverTimer = setTimeout(function() {
              showLocationPopup(machineId, locationName, mouseEvent);
          }, 300);
      });

      $('.location-link').on('mouseleave', function() {
          if (hoverTimer) {
              clearTimeout(hoverTimer);
              hoverTimer = null;
          }
      });

      $popup.on('mouseenter', function() {});
      $popup.on('mouseleave', function() {
          hideLocationPopup();
      });

      $overlay.on('click', hideLocationPopup);
      $popup.find('.location-popup-close').on('click', hideLocationPopup);

      $(document).on('keydown', function(e) {
          if (e.key === 'Escape' && $popup.is(':visible')) {
              hideLocationPopup();
          }
      });
  });
  </script>

  <!-- Map Location Picker Modal -->
  <style>
  #mapPickerModal {
      display: none;
      position: fixed;
      z-index: 10000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.7);
  }
  #mapPickerContent {
      background-color: #1f1f1f;
      margin: 2% auto;
      padding: 0;
      border: 2px solid #667eea;
      border-radius: 8px;
      width: 70%;
      max-width: 900px;
      box-shadow: 0 10px 40px rgba(0,0,0,0.8);
  }
  #mapPickerHeader {
      background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 6px 12px;
      border-radius: 6px 6px 0 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
  }
  #mapPickerClose {
      background: none;
      border: none;
      color: white;
      font-size: 24px;
      cursor: pointer;
      padding: 0;
      width: 28px;
      height: 28px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
  }
  #mapPickerClose:hover {
      background: rgba(255, 255, 255, 0.2);
  }
  #mapPickerBody {
      padding: 12px;
      background: #2a2a2a;
  }
  #locationPickerMap {
      width: 100%;
      height: 400px;
      background: #1a1a1a;
      border-radius: 4px;
  }
  #mapPickerFooter {
      padding: 10px 15px;
      background: #1f1f1f;
      border-top: 1px solid #444;
      border-radius: 0 0 6px 6px;
      display: flex;
      justify-content: space-between;
      align-items: center;
  }
  #selectedCoords {
      color: #aaa;
      font-size: 14px;
  }
  .map-picker-btn {
      padding: 8px 20px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-left: 10px;
  }
  #confirmLocationBtn {
      background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
      color: white;
  }
  #confirmLocationBtn:hover {
      opacity: 0.9;
  }
  #cancelLocationBtn {
      background: #555;
      color: white;
  }
  #cancelLocationBtn:hover {
      background: #666;
  }
  </style>

  <div id="mapPickerModal">
      <div id="mapPickerContent">
          <div id="mapPickerHeader">
              <span style="font-size:14px; font-weight:600;"><i class="zmdi zmdi-pin"></i> Select Machine Location</span>
              <button id="mapPickerClose">&times;</button>
          </div>
          <div id="mapPickerBody">
              <div id="locationPickerMap"></div>
          </div>
          <div id="mapPickerFooter">
              <span id="selectedCoords">Click on the map to select a location</span>
              <div>
                  <button id="cancelLocationBtn" class="map-picker-btn">Cancel</button>
                  <button id="confirmLocationBtn" class="map-picker-btn">Confirm Location</button>
              </div>
          </div>
      </div>
  </div>

  <script>
  $(document).ready(function() {
      var pickerMap = null;
      var currentMarker = null;
      var selectedX = null;
      var selectedY = null;

      // Get current theme
      var bodyClass = document.body.className;
      var themeMatch = bodyClass.match(/bg-theme(\d+)/);
      var theme = themeMatch ? 'bg-theme' + themeMatch[1] : 'bg-theme1';

      // Theme-specific configurations
      var themeConfig = {
          'bg-theme1': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme2': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme3': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme4': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme5': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme6': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme7': { bg: '#0c675e', filter: 'brightness(0.8) contrast(1.1) hue-rotate(-10deg)' },
          'bg-theme8': { bg: '#4a3020', filter: 'brightness(0.75) contrast(1.1) saturate(0.8)' },
          'bg-theme9': { bg: '#29323c', filter: 'brightness(0.7) contrast(1.1)' },
          'bg-theme10': { bg: '#795548', filter: 'brightness(0.8) contrast(1.05) sepia(0.2)' },
          'bg-theme11': { bg: '#1565C0', filter: 'brightness(0.85) contrast(1.05) hue-rotate(-5deg)' },
          'bg-theme12': { bg: '#65379b', filter: 'brightness(0.8) contrast(1.1) hue-rotate(5deg)' },
          'bg-theme13': { bg: '#d03050', filter: 'brightness(0.85) contrast(1.05) saturate(0.9)' },
          'bg-theme14': { bg: '#2a7a2e', filter: 'brightness(0.8) contrast(1.1) saturate(0.95)' },
          'bg-theme15': { bg: '#4643d3', filter: 'brightness(0.85) contrast(1.05) hue-rotate(-5deg)' },
          'bg-theme16': { bg: '#6a11cb', filter: 'brightness(0.8) contrast(1.1)' }
      };

      var config = themeConfig[theme] || { bg: '#1a1a1a', filter: 'brightness(0.7) contrast(1.1)' };

      // Determine which map image to use based on theme
      var lightThemes = ['bg-theme11', 'bg-theme13'];
      var mapImage = lightThemes.includes(theme) ? './images/sitemap2025-light.png' : './images/sitemap2025-dark.png';

      function updateCoordinateDisplay() {
          if (selectedX !== null && selectedY !== null) {
              var displayY = 2550 - selectedY;
              $('#selectedCoords').text('Selected: X=' + Math.round(selectedX) + ', Y=' + Math.round(displayY));
          } else {
              $('#selectedCoords').text('Click on the map to select a location');
          }
      }

      $('#selectLocationBtn').click(function() {
          $('#mapPickerModal').fadeIn(200);

          if (!pickerMap) {
              // Initialize map
              pickerMap = L.map('locationPickerMap', {
                  crs: L.CRS.Simple,
                  minZoom: -3
              });

              var bounds = [[0, 0], [2550, 3300]];
              var image = L.imageOverlay(mapImage, bounds);

              // Apply theme-specific filter
              image.on('load', function() {
                  var imgElement = this.getElement();
                  if (imgElement) {
                      imgElement.style.filter = config.filter;
                  }
              });

              image.addTo(pickerMap);
              pickerMap.fitBounds(bounds);

              // Add click handler
              pickerMap.on('click', function(e) {
                  selectedX = e.latlng.lng;
                  selectedY = e.latlng.lat;

                  // Remove existing marker
                  if (currentMarker) {
                      pickerMap.removeLayer(currentMarker);
                  }

                  // Add new marker
                  currentMarker = L.circleMarker([selectedY, selectedX], {
                      radius: 8,
                      fillColor: '#667eea',
                      color: '#fff',
                      weight: 2,
                      opacity: 1,
                      fillOpacity: 0.8
                  }).addTo(pickerMap);

                  updateCoordinateDisplay();
              });
          }

          // Load existing coordinates if available
          var existingLeft = $('#mapleft').val();
          var existingTop = $('#maptop').val();

          if (existingLeft && existingTop && existingLeft != '' && existingTop != '') {
              selectedX = parseFloat(existingLeft);
              selectedY = 2550 - parseFloat(existingTop);

              if (currentMarker) {
                  pickerMap.removeLayer(currentMarker);
              }

              currentMarker = L.circleMarker([selectedY, selectedX], {
                  radius: 8,
                  fillColor: '#667eea',
                  color: '#fff',
                  weight: 2,
                  opacity: 1,
                  fillOpacity: 0.8
              }).addTo(pickerMap);

              // Pan to marker
              pickerMap.panTo([selectedY, selectedX]);

              updateCoordinateDisplay();
          }

          setTimeout(function() {
              pickerMap.invalidateSize();
          }, 250);
      });

      $('#confirmLocationBtn').click(function() {
          if (selectedX !== null && selectedY !== null) {
              var convertedY = 2550 - selectedY;
              $('#mapleft').val(Math.round(selectedX));
              $('#maptop').val(Math.round(convertedY));

              // Update the display on the form
              $('#coordinateDisplay').html('Current position: X=' + Math.round(selectedX) + ', Y=' + Math.round(convertedY));

              updateCoordinateDisplay();
              $('#mapPickerModal').fadeOut(200);
          } else {
              alert('Please select a location on the map first.');
          }
      });

      $('#cancelLocationBtn, #mapPickerClose').click(function() {
          $('#mapPickerModal').fadeOut(200);
      });

      // ========================================
      // Nested Creation Form Handlers
      // ========================================

      // Button handlers to trigger dropdown selection
      $('#addModelBtn').on('click', function() {
          $('#modelid').val('new').trigger('change');
      });

      $('#addVendorBtn').on('click', function() {
          $('#newvendorid').val('new').trigger('change');
      });

      $('#addMachineTypeBtn').on('click', function() {
          $('#newmodelmachinetypeid').val('new').trigger('change');
      });

      $('#addFunctionalAccountBtn').on('click', function() {
          $('#newfunctionalaccountid').val('new').trigger('change');
      });

      $('#addBusinessUnitBtn').on('click', function() {
          $('#businessunitid').val('new').trigger('change');
      });

      // Handle Model dropdown - show/hide new model section
      $('#modelid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newModelSection').slideDown();
              $('#newmodelnumber').prop('required', true);
              $('#newvendorid').prop('required', true);
              $('#newmodelmachinetypeid').prop('required', true);
          } else {
              $('#newModelSection').slideUp();
              $('#newVendorSection').slideUp();
              $('#newMachineTypeSection').slideUp();
              $('#newFunctionalAccountSection').slideUp();
              $('#newmodelnumber').val('').prop('required', false);
              $('#newvendorid').val('').prop('required', false);
              $('#newmodelmachinetypeid').val('').prop('required', false);
              $('#newmodelimage').val('');
              $('#newvendorname').val('').prop('required', false);
              $('#newmachinetype').val('').prop('required', false);
              $('#newmachinedescription').val('');
              $('#newfunctionalaccountid').val('').prop('required', false);
              $('#newfunctionalaccount').val('').prop('required', false);
              $('#newfunctionalaccountdescription').val('');
          }
      });

      // Cancel new model
      $('#cancelNewModel').on('click', function() {
          $('#newModelSection').slideUp();
          $('#newVendorSection').slideUp();
          $('#newMachineTypeSection').slideUp();
          $('#newFunctionalAccountSection').slideUp();
          $('#modelid').val($('#modelid option:first').val());
          $('#newmodelnumber').val('').prop('required', false);
          $('#newvendorid').val('').prop('required', false);
          $('#newmodelmachinetypeid').val('').prop('required', false);
          $('#newmodelimage').val('');
          $('#newvendorname').val('').prop('required', false);
          $('#newmachinetype').val('').prop('required', false);
          $('#newmachinedescription').val('');
          $('#newfunctionalaccountid').val('').prop('required', false);
          $('#newfunctionalaccount').val('').prop('required', false);
          $('#newfunctionalaccountdescription').val('');
      });

      // Handle Vendor dropdown within new model section
      $('#newvendorid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newVendorSection').slideDown();
              $('#newvendorname').prop('required', true);
          } else {
              $('#newVendorSection').slideUp();
              $('#newvendorname').val('').prop('required', false);
          }
      });

      // Cancel new vendor
      $('#cancelNewVendor').on('click', function() {
          $('#newVendorSection').slideUp();
          $('#newvendorid').val('');
          $('#newvendorname').val('').prop('required', false);
      });

      // Handle Machine Type dropdown (nested in New Model) - show/hide new machine type section
      $('#newmodelmachinetypeid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newMachineTypeSection').slideDown();
              $('#newmachinetype').prop('required', true);
              $('#newfunctionalaccountid').prop('required', true);
          } else {
              $('#newMachineTypeSection').slideUp();
              $('#newFunctionalAccountSection').slideUp();
              $('#newmachinetype').val('').prop('required', false);
              $('#newmachinedescription').val('');
              $('#newfunctionalaccountid').val('').prop('required', false);
              $('#newfunctionalaccount').val('').prop('required', false);
              $('#newfunctionalaccountdescription').val('');
          }
      });

      // Cancel new machine type
      $('#cancelNewMachineType').on('click', function() {
          $('#newMachineTypeSection').slideUp();
          $('#newFunctionalAccountSection').slideUp();
          $('#newmodelmachinetypeid').val('');
          $('#newmachinetype').val('').prop('required', false);
          $('#newmachinedescription').val('');
          $('#newfunctionalaccountid').val('').prop('required', false);
          $('#newfunctionalaccount').val('').prop('required', false);
          $('#newfunctionalaccountdescription').val('');
      });

      // Handle Functional Account dropdown within new machine type section
      $('#newfunctionalaccountid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newFunctionalAccountSection').slideDown();
              $('#newfunctionalaccount').prop('required', true);
          } else {
              $('#newFunctionalAccountSection').slideUp();
              $('#newfunctionalaccount').val('').prop('required', false);
              $('#newfunctionalaccountdescription').val('');
          }
      });

      // Cancel new functional account
      $('#cancelNewFunctionalAccount').on('click', function() {
          $('#newFunctionalAccountSection').slideUp();
          $('#newfunctionalaccountid').val('');
          $('#newfunctionalaccount').val('').prop('required', false);
          $('#newfunctionalaccountdescription').val('');
      });

      // Handle Business Unit dropdown - show/hide new business unit section
      $('#businessunitid').on('change', function() {
          if ($(this).val() === 'new') {
              $('#newBusinessUnitSection').slideDown();
              $('#newbusinessunitname').prop('required', true);
          } else {
              $('#newBusinessUnitSection').slideUp();
              $('#newbusinessunitname').val('').prop('required', false);
          }
      });

      // Cancel new business unit
      $('#cancelNewBusinessUnit').on('click', function() {
          $('#newBusinessUnitSection').slideUp();
          $('#businessunitid').val($('#businessunitid option:first').val());
          $('#newbusinessunitname').val('').prop('required', false);
      });

      // Form validation for edit form
      $('form[action*="editmacine.asp"]').on('submit', function(e) {
          // Validate new model section
          if ($('#modelid').val() === 'new') {
              if ($('#newmodelnumber').val().trim() === '') {
                  e.preventDefault();
                  alert('Please enter a model number or select an existing model');
                  $('#newmodelnumber').focus();
                  return false;
              }
              if ($('#newvendorid').val() === '' || $('#newvendorid').val() === 'new') {
                  if ($('#newvendorid').val() === 'new') {
                      if ($('#newvendorname').val().trim() === '') {
                          e.preventDefault();
                          alert('Please enter a vendor name or select an existing vendor');
                          $('#newvendorname').focus();
                          return false;
                      }
                  } else {
                      e.preventDefault();
                      alert('Please select a vendor for the new model');
                      $('#newvendorid').focus();
                      return false;
                  }
              }
          }

          // Validate new machine type section (nested in new model)
          if ($('#modelid').val() === 'new' && $('#newmodelmachinetypeid').val() === 'new') {
              if ($('#newmachinetype').val().trim() === '') {
                  e.preventDefault();
                  alert('Please enter a machine type name or select an existing machine type');
                  $('#newmachinetype').focus();
                  return false;
              }
              if ($('#newfunctionalaccountid').val() === '' || $('#newfunctionalaccountid').val() === 'new') {
                  if ($('#newfunctionalaccountid').val() === 'new') {
                      if ($('#newfunctionalaccount').val().trim() === '') {
                          e.preventDefault();
                          alert('Please enter a functional account name or select an existing functional account');
                          $('#newfunctionalaccount').focus();
                          return false;
                      }
                  } else {
                      e.preventDefault();
                      alert('Please select a functional account for the new machine type');
                      $('#newfunctionalaccountid').focus();
                      return false;
                  }
              }
          }

          // Validate new business unit section
          if ($('#businessunitid').val() === 'new') {
              if ($('#newbusinessunitname').val().trim() === '') {
                  e.preventDefault();
                  alert('Please enter a business unit name or select an existing business unit');
                  $('#newbusinessunitname').focus();
                  return false;
              }
          }
      });
  });
  </script>

</body>
</html>
<%
'=============================================================================
' CLEANUP
'=============================================================================
objConn.Close
%>
