<!DOCTYPE html>
<html lang="en">
<head>
  <!--#include file="./includes/header.asp"-->
  <!--#include file="./includes/sql.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
%>
<body class="bg-theme <%Response.Write(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="row">
        <div class="col-lg-9">
          <div class="card">
            <div class="card-body" style="padding:0;">
              <div style="padding:15px; border-bottom:1px solid #444;">
                <h5 class="card-title" style="margin:0; display:inline-block;">
                  <i class='zmdi zmdi-reader'></i>&nbsp;&nbsp;Machine Map
                </h5>
                <div style="float:right;">
                  <input type="text" id="machineSearch" class="form-control form-control-sm" placeholder="Search by name, serial, vendor, model..." style="display:inline-block; width:200px; margin-right:10px;">
                  <label style="margin-right:5px; display:inline-block; color:#aaa;">BU:</label>
                  <select id="businessUnitFilter" class="form-control form-control-sm" style="display:inline-block; width:120px; margin-right:10px;">
                    <option value="all">All</option>
<%
' Get business units for dropdown
Dim rsBU, strBUSQL
strBUSQL = "SELECT businessunitid, businessunit FROM businessunits WHERE isactive = 1 ORDER BY businessunit"
Set rsBU = objConn.Execute(strBUSQL)
Do While Not rsBU.EOF
    Response.Write("<option value='" & rsBU("businessunitid") & "'>" & Server.HTMLEncode(rsBU("businessunit")) & "</option>")
    rsBU.MoveNext
Loop
rsBU.Close
Set rsBU = Nothing
%>
                  </select>
                  <label style="margin-right:5px; display:inline-block; color:#aaa;">Type:</label>
                  <select id="machineTypeFilter" class="form-control form-control-sm" style="display:inline-block; width:140px; margin-right:10px;">
                    <option value="all">All Types</option>
<%
' Get machine types for dropdown (exclude PC types and network device types)
Dim rsMT, strMTSQL
strMTSQL = "SELECT machinetypeid, machinetype FROM machinetypes WHERE machinetypeid < 16 AND isactive = 1 ORDER BY machinetype"
Set rsMT = objConn.Execute(strMTSQL)
Do While Not rsMT.EOF
    Response.Write("<option value='" & rsMT("machinetypeid") & "'>" & Server.HTMLEncode(rsMT("machinetype")) & "</option>")
    rsMT.MoveNext
Loop
rsMT.Close
Set rsMT = Nothing
%>
                  </select>
                  <label style="margin-right:5px; display:inline-block; color:#aaa;">Status:</label>
                  <select id="machineStatusFilter" class="form-control form-control-sm" style="display:inline-block; width:120px;">
                    <option value="all">All</option>
<%
' Get machine statuses for dropdown
Dim rsMS, strMSSQL
strMSSQL = "SELECT machinestatusid, machinestatus FROM machinestatus ORDER BY machinestatus"
Set rsMS = objConn.Execute(strMSSQL)
Do While Not rsMS.EOF
    Response.Write("<option value='" & rsMS("machinestatusid") & "'>" & Server.HTMLEncode(rsMS("machinestatus")) & "</option>")
    rsMS.MoveNext
Loop
rsMS.Close
Set rsMS = Nothing
%>
                  </select>
                </div>
              </div>
              <div id="map"></div>
            </div>
          </div>
        </div>

        <div class="col-lg-3">
          <div class="card">
            <div class="card-header" style="background: linear-gradient(45deg, #667eea, #764ba2); color: white;">
              <i class="zmdi zmdi-info"></i> Legend
            </div>
            <div class="card-body">
              <p style="font-size:12px; color:#aaa; margin-bottom:15px;">
                Machine type color codes:
              </p>

              <div style="margin-bottom:20px;">
<%
' Get machine types with colors for legend
Dim rsLegend, strLegendSQL
strLegendSQL = "SELECT machinetypeid, machinetype FROM machinetypes WHERE machinetypeid < 16 AND isactive = 1 ORDER BY machinetype"
Set rsLegend = objConn.Execute(strLegendSQL)
Do While Not rsLegend.EOF
    Dim legendColor
    Select Case rsLegend("machinetypeid")
        Case 1: legendColor = "#4CAF50"  ' CNC
        Case 2: legendColor = "#2196F3"  ' Grinder
        Case 3: legendColor = "#FF9800"  ' Lathe
        Case 4: legendColor = "#F44336"  ' Mill
        Case 5: legendColor = "#9C27B0"  ' CMM
        Case 6: legendColor = "#00BCD4"  ' EDM
        Case 7: legendColor = "#E91E63"  ' Press
        Case 8: legendColor = "#607D8B"  ' Saw
        Case 9: legendColor = "#795548"  ' Welder
        Case 10: legendColor = "#FF5722" ' Drill
        Case 11: legendColor = "#3F51B5" ' Robot
        Case 12: legendColor = "#8BC34A" ' Inspection
        Case 13: legendColor = "#CDDC39" ' Assembly
        Case 14: legendColor = "#FFC107" ' Other
        Case 15: legendColor = "#009688" ' Wash
        Case Else: legendColor = "#FFC107"
    End Select
    Response.Write("<div style='margin:8px 0; display:flex; align-items:center;'>")
    Response.Write("<span style='display:inline-block; width:16px; height:16px; background:" & legendColor & "; border-radius:50%; margin-right:10px; border:2px solid #fff; box-shadow:0 2px 5px rgba(0,0,0,0.5);'></span>")
    Response.Write("<span style='font-size:13px; color:#fff;'>" & Server.HTMLEncode(rsLegend("machinetype")) & "</span>")
    Response.Write("</div>")
    rsLegend.MoveNext
Loop
rsLegend.Close
Set rsLegend = Nothing
%>
              </div>

              <div style="margin-top:20px; padding:15px; background:#2a2a2a; border-radius:4px; font-size:12px;">
                <strong style="color:#4fc3f7;">Tips:</strong>
                <ul style="margin:8px 0; padding-left:20px; color:#aaa;">
                  <li style="margin:5px 0;">Hover over markers for details</li>
                  <li style="margin:5px 0;">Use search to find specific machines</li>
                  <li style="margin:5px 0;">Filter by BU, type, or status</li>
                  <li style="margin:5px 0;">Click "View Details" for full information</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div><!--End Row-->

    </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>
    </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>
  <script src="assets/plugins/simplebar/js/simplebar.js"></script>
  <script src="assets/js/sidebar-menu.js"></script>
  <script src="assets/js/app-script.js"></script>

<style>
#map {
	width: 100%;
	height: calc(100vh - 250px);
	min-height: 600px;
	background-color: #1a1a1a;
}

.leaflet-control-zoom a {
	background-color: #2a2a2a !important;
	color: #fff !important;
	border-color: #444 !important;
}
.leaflet-control-zoom a:hover {
	background-color: #3a3a3a !important;
}
.leaflet-bar {
	border: 1px solid #444 !important;
}

.leaflet-popup-content-wrapper {
	background: #1f1f1f !important;
	color: #fff !important;
	box-shadow: 0 3px 14px rgba(0,0,0,0.6) !important;
	border-radius: 4px !important;
	padding: 0 !important;
}
.leaflet-popup-content {
	margin: 0 !important;
}
.leaflet-popup-tip-container {
	display: none !important;
}
.leaflet-popup-close-button {
	color: #fff !important;
	font-size: 24px !important;
	padding: 4px 8px 0 0 !important;
}

.leaflet-control-attribution {
	display: none !important;
}
</style>

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

var themeConfig = {
    'bg-theme1': { bg: '#2a2a2a', filter: 'brightness(0.7) contrast(1.1)', gradient: 'linear-gradient(45deg, #3a3a3a, #4a4a4a)' },
    'bg-theme7': { bg: '#0c675e', filter: 'brightness(0.8) contrast(1.1) hue-rotate(-10deg)', gradient: 'linear-gradient(45deg, #0c675e, #069e90)' },
    'bg-theme11': { bg: '#1565C0', filter: 'brightness(0.85) contrast(1.05) hue-rotate(-5deg)', gradient: 'linear-gradient(45deg, #1565C0, #1E88E5)' }
};

var config = themeConfig[theme] || { bg: '#1a1a1a', filter: 'brightness(0.7) contrast(1.1)', gradient: 'linear-gradient(45deg, #667eea, #764ba2)' };

document.getElementById('map').style.backgroundColor = config.bg;

var map = L.map('map', {
    crs: L.CRS.Simple,
	minZoom: -3
});
var bounds = [[0,0], [2550,3300]];

var lightThemes = ['bg-theme11', 'bg-theme13'];
var mapImage = lightThemes.includes(theme) ? './images/sitemap2025-light.png' : './images/sitemap2025-dark.png';
var image = L.imageOverlay(mapImage, bounds);

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

image.addTo(map);
var center = [1275, 1650];
map.setView(center, -2.3);

// Store machine data and markers
var machineMarkers = [];

// Machine type colors
var machineTypeColors = {
    '1': '#4CAF50',   // CNC
    '2': '#2196F3',   // Grinder
    '3': '#FF9800',   // Lathe
    '4': '#F44336',   // Mill
    '5': '#9C27B0',   // CMM
    '6': '#00BCD4',   // EDM
    '7': '#E91E63',   // Press
    '8': '#607D8B',   // Saw
    '9': '#795548',   // Welder
    '10': '#FF5722', // Drill
    '11': '#3F51B5', // Robot
    '12': '#8BC34A', // Inspection
    '13': '#CDDC39', // Assembly
    '14': '#FFC107', // Other
    '15': '#009688', // Wash
    'default': '#FFC107'
};

<%
' Query active machines with map coordinates (equipment only, not PCs or network devices)
Dim strSQL, rs, mapleft, maptop, machineid, machinenumber, machineType, machineTypeId
Dim modelnumber, vendor, alias, serialnumber, businessunitid, businessunit, machinestatusid, machinestatus

strSQL = "SELECT m.machineid, m.machinenumber, m.alias, m.serialnumber, " &_
         "m.mapleft, m.maptop, m.businessunitid, m.machinestatusid, " &_
         "mt.machinetypeid, mt.machinetype, " &_
         "mo.modelnumber, v.vendor, " &_
         "bu.businessunit, ms.machinestatus " &_
         "FROM machines m " &_
         "LEFT JOIN models mo ON m.modelnumberid = mo.modelnumberid " &_
         "LEFT JOIN machinetypes mt ON mo.machinetypeid = mt.machinetypeid " &_
         "LEFT JOIN vendors v ON mo.vendorid = v.vendorid " &_
         "LEFT JOIN businessunits bu ON m.businessunitid = bu.businessunitid " &_
         "LEFT JOIN machinestatus ms ON m.machinestatusid = ms.machinestatusid " &_
         "WHERE m.pctypeid IS NULL " &_
         "AND m.isactive = 1 " &_
         "AND m.mapleft IS NOT NULL " &_
         "AND m.maptop IS NOT NULL " &_
         "ORDER BY mt.machinetype, m.machinenumber ASC"

Set rs = objConn.Execute(strSQL)

Do While Not rs.EOF
    mapleft = rs("mapleft")
    maptop = rs("maptop")
    maptop = 2550 - maptop
    machineid = rs("machineid")
    machinenumber = rs("machinenumber") & ""

    If Not IsNull(rs("machinetypeid")) Then
        machineTypeId = rs("machinetypeid")
    Else
        machineTypeId = 0
    End If

    If Not IsNull(rs("machinetype")) Then
        machineType = rs("machinetype")
    Else
        machineType = "Unknown"
    End If

    If Not IsNull(rs("alias")) And rs("alias") <> "" Then
        alias = rs("alias")
    Else
        alias = machinenumber
    End If

    If Not IsNull(rs("modelnumber")) Then
        modelnumber = rs("modelnumber")
    Else
        modelnumber = "N/A"
    End If

    If Not IsNull(rs("vendor")) Then
        vendor = rs("vendor")
    Else
        vendor = "N/A"
    End If

    If Not IsNull(rs("serialnumber")) And rs("serialnumber") <> "" Then
        serialnumber = rs("serialnumber")
    Else
        serialnumber = "N/A"
    End If

    If Not IsNull(rs("businessunitid")) Then
        businessunitid = rs("businessunitid")
    Else
        businessunitid = 0
    End If

    If Not IsNull(rs("businessunit")) Then
        businessunit = rs("businessunit")
    Else
        businessunit = "N/A"
    End If

    If Not IsNull(rs("machinestatusid")) Then
        machinestatusid = rs("machinestatusid")
    Else
        machinestatusid = 0
    End If

    If Not IsNull(rs("machinestatus")) Then
        machinestatus = rs("machinestatus")
    Else
        machinestatus = "N/A"
    End If
%>
(function() {
    var machineId = '<%=machineid%>';
    var machineName = '<%=Server.HTMLEncode(alias)%>';
    var machineNumber = '<%=Server.HTMLEncode(machinenumber)%>';
    var machineType = '<%=Server.HTMLEncode(machineType)%>';
    var machineTypeId = '<%=machineTypeId%>';
    var model = '<%=Server.HTMLEncode(modelnumber)%>';
    var vendor = '<%=Server.HTMLEncode(vendor)%>';
    var serialNumber = '<%=Server.HTMLEncode(serialnumber)%>';
    var businessUnitId = '<%=businessunitid%>';
    var businessUnit = '<%=Server.HTMLEncode(businessunit)%>';
    var machineStatusId = '<%=machinestatusid%>';
    var machineStatus = '<%=Server.HTMLEncode(machinestatus)%>';

    // Get color for this machine type
    var color = machineTypeColors[machineTypeId] || machineTypeColors['default'];

    // Create custom marker icon
    var icon = L.divIcon({
        html: '<div style="background:' + color + '; width:20px; height:20px; border-radius:50%; border:2px solid #fff; box-shadow:0 2px 5px rgba(0,0,0,0.5);"></div>',
        iconSize: [20, 20],
        iconAnchor: [10, 10],
        popupAnchor: [0, -5],
        className: 'custom-marker'
    });

    var marker = L.marker([<%=maptop%>, <%=mapleft%>], {
        title: machineName,
        icon: icon,
        machineId: machineId,
        machineTypeId: machineTypeId
    }).addTo(map);

    // Store marker with searchable data for filtering
    machineMarkers.push({
        marker: marker,
        machineTypeId: machineTypeId,
        businessUnitId: businessUnitId,
        machineStatusId: machineStatusId,
        searchData: {
            name: machineName.toLowerCase(),
            number: machineNumber.toLowerCase(),
            type: machineType.toLowerCase(),
            vendor: vendor.toLowerCase(),
            model: model.toLowerCase(),
            serial: serialNumber.toLowerCase(),
            bu: businessUnit.toLowerCase()
        }
    });

    // Open popup on hover
    var popupTimeout;

    marker.on('mouseover', function() {
        clearTimeout(popupTimeout);
        this.openPopup();
    });

    marker.on('mouseout', function(e) {
        var popup = this.getPopup();
        var popupElement = popup.getElement();

        popupTimeout = setTimeout(function() {
            marker.closePopup();
        }, 800);

        if (popupElement) {
            popupElement.addEventListener('mouseenter', function() {
                clearTimeout(popupTimeout);
            });

            popupElement.addEventListener('mouseleave', function() {
                marker.closePopup();
            });
        }
    });

    var detailUrl = './displaymachine.asp?machineid=' + machineId;

    var popupContent = '<div style="background:#1f1f1f; color:#fff; min-width:250px; border-radius:4px; overflow:hidden;">' +
        '<div style="background:' + config.gradient + '; padding:10px 15px; border-bottom:1px solid #444;">' +
        '<h6 style="margin:0; color:#fff; font-size:14px;">' + machineName + '</h6>' +
        '</div>' +
        '<div style="padding:10px 15px; font-size:12px;">' +
        '<div style="margin:5px 0;"><strong style="color:#aaa;">Number:</strong> <span style="color:#fff;">' + machineNumber + '</span></div>' +
        '<div style="margin:5px 0;"><strong style="color:#aaa;">Type:</strong> <span style="color:' + color + '; font-weight:bold;">' + machineType + '</span></div>' +
        '<div style="margin:5px 0;"><strong style="color:#aaa;">Status:</strong> <span style="color:#fff;">' + machineStatus + '</span></div>' +
        (businessUnit !== 'N/A' ? '<div style="margin:5px 0;"><strong style="color:#aaa;">Business Unit:</strong> <span style="color:#fff;">' + businessUnit + '</span></div>' : '') +
        (vendor !== 'N/A' ? '<div style="margin:5px 0;"><strong style="color:#aaa;">Vendor:</strong> <span style="color:#fff;">' + vendor + '</span></div>' : '') +
        (model !== 'N/A' ? '<div style="margin:5px 0;"><strong style="color:#aaa;">Model:</strong> <span style="color:#fff;">' + model + '</span></div>' : '') +
        (serialNumber !== 'N/A' ? '<div style="margin:5px 0;"><strong style="color:#aaa;">Serial:</strong> <span style="color:#fff;">' + serialNumber + '</span></div>' : '') +
        '</div>' +
        '<div style="padding:10px 15px; border-top:1px solid #444; text-align:center;">' +
        '<a href="' + detailUrl + '" style="display:inline-block; background:' + config.gradient + '; color:#fff; padding:8px 18px; border-radius:4px; text-decoration:none; font-size:13px; font-weight:500; transition:all 0.2s;" target="_blank" onmouseover="this.style.opacity=\'0.9\'" onmouseout="this.style.opacity=\'1\'"><i class="zmdi zmdi-eye"></i> View Details</a>' +
        '</div>' +
        '</div>';

    marker.bindPopup(popupContent);
})();
<%
    rs.MoveNext
Loop
rs.Close
Set rs = Nothing
objConn.Close
%>

// Combined filter functionality (type + BU + status + search)
function applyFilters() {
    var selectedType = document.getElementById('machineTypeFilter').value;
    var selectedBU = document.getElementById('businessUnitFilter').value;
    var selectedStatus = document.getElementById('machineStatusFilter').value;
    var searchTerm = document.getElementById('machineSearch').value.toLowerCase().trim();

    machineMarkers.forEach(function(item) {
        var typeMatch = (selectedType === 'all' || item.machineTypeId == selectedType);
        var buMatch = (selectedBU === 'all' || item.businessUnitId == selectedBU);
        var statusMatch = (selectedStatus === 'all' || item.machineStatusId == selectedStatus);
        var searchMatch = true;

        if (searchTerm !== '') {
            searchMatch = item.searchData.name.indexOf(searchTerm) > -1 ||
                         item.searchData.number.indexOf(searchTerm) > -1 ||
                         item.searchData.type.indexOf(searchTerm) > -1 ||
                         item.searchData.vendor.indexOf(searchTerm) > -1 ||
                         item.searchData.model.indexOf(searchTerm) > -1 ||
                         item.searchData.serial.indexOf(searchTerm) > -1 ||
                         item.searchData.bu.indexOf(searchTerm) > -1;
        }

        // Show marker only if it matches all filters
        if (typeMatch && buMatch && statusMatch && searchMatch) {
            item.marker.setOpacity(1);
        } else {
            item.marker.setOpacity(0.15);
        }
    });
}

// Listen to filter changes
document.getElementById('machineTypeFilter').addEventListener('change', applyFilters);
document.getElementById('businessUnitFilter').addEventListener('change', applyFilters);
document.getElementById('machineStatusFilter').addEventListener('change', applyFilters);

// Listen to search input with debouncing
var searchTimeout;
document.getElementById('machineSearch').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(applyFilters, 300);
});
</script>

</body>
</html>
