<%@ Language=VBScript %>
<%
Option Explicit
Dim theme, strSQL, rs, displayName, uptimeDays, hasVnc, hasWinrm, vncHost, objConn
%>
<!DOCTYPE html>
<html lang="en">
<head>
  <!--#include file="./includes/header.asp"-->
  <!--#include file="./includes/sql.asp"-->
</head>

<%
	' displaypcs.asp - PC List Page (Phase 2 Schema)
	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-xl-auto">
          <div class="card">
            <div class="card-body">
              <div style="margin-bottom:15px;">
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px;">
                  <h5 class="card-title" style="margin:0;">PCs</h5>
                  <div>
                    <a href="./adddevice.asp" class="btn btn-primary">
                      <i class="zmdi zmdi-plus-circle"></i> Add Device
                    </a>
                  </div>
                </div>
<%
Dim currentPCStatus, winrmFilter, deviceTypeFilter, pcTypeFilter, uptimeFilter, sel
currentPCStatus = Request.QueryString("pcstatus")
winrmFilter = Request.QueryString("winrm")
deviceTypeFilter = Request.QueryString("devicetype")
pcTypeFilter = Request.QueryString("pctype")
uptimeFilter = Request.QueryString("uptime")

' Check for specialized PCs (CMM, Wax Trace, Measuring Tool) without equipment relationships
Dim rsUnlinked, unlinkedCount
unlinkedCount = 0
Set rsUnlinked = objConn.Execute("SELECT COUNT(*) as cnt FROM machines m " & _
    "WHERE m.pctypeid = 7 AND m.isactive = 1 " & _
    "AND NOT EXISTS (SELECT 1 FROM machinerelationships mr WHERE (mr.machineid = m.machineid OR mr.related_machineid = m.machineid) AND mr.relationshiptypeid = 3 AND mr.isactive = 1)")
If Not rsUnlinked.EOF Then
    unlinkedCount = CLng(rsUnlinked("cnt") & "")
End If
rsUnlinked.Close
Set rsUnlinked = Nothing

If unlinkedCount > 0 Then
%>
                <div class="alert alert-warning" role="alert" style="margin-bottom:15px;">
                  <i class="zmdi zmdi-alert-triangle"></i> <strong><%=unlinkedCount%> specialized PC(s)</strong> (CMM, Wax Trace, or Measuring Tool) need equipment relationships.
                  <a href="displaypcs.asp?needsrelationship=1" class="alert-link">View them</a>
                </div>
<%
End If
%>
                <div style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
                  <select id="deviceTypeFilter" class="btn btn-secondary btn-sm" onchange="updateFilter('devicetype', this.value)">
                    <option value="">All Device Types</option>
                    <option value="laptop"<% If deviceTypeFilter = "laptop" Then Response.Write(" selected") End If%>>Laptops</option>
                    <option value="desktop"<% If deviceTypeFilter = "desktop" Then Response.Write(" selected") End If%>>Desktops</option>
                  </select>
                  <select id="pcTypeFilter" class="btn btn-secondary btn-sm" onchange="updateFilter('pctype', this.value)">
                    <option value="">All PC Types</option>
<%
Dim rsPCType, pcTypeSelectedAttr
Set rsPCType = objConn.Execute("SELECT pctypeid, typename FROM pctype WHERE isactive = 1 ORDER BY typename")
While Not rsPCType.EOF
    pcTypeSelectedAttr = ""
    If CStr(rsPCType("pctypeid")) = CStr(pcTypeFilter) Then
        pcTypeSelectedAttr = " selected"
    End If
    Response.Write "                    <option value=""" & rsPCType("pctypeid") & """" & pcTypeSelectedAttr & ">" & rsPCType("typename") & "</option>" & vbCrLf
    rsPCType.MoveNext
Wend
rsPCType.Close
Set rsPCType = Nothing
%>
                  </select>
                  <select id="pcStatusSelect" class="btn btn-secondary btn-sm" onchange="updateFilter('pcstatus', this.value)">
                    <option value="">All Statuses</option>
<%
Dim rsStatus, selectedAttr
Set rsStatus = objConn.Execute("SELECT machinestatusid, machinestatus FROM machinestatus WHERE isactive = 1 ORDER BY machinestatusid")
While Not rsStatus.EOF
    selectedAttr = ""
    If CStr(rsStatus("machinestatusid")) = CStr(currentPCStatus) Then
        selectedAttr = " selected"
    End If
    Response.Write "<option value=""" & rsStatus("machinestatusid") & """" & selectedAttr & ">" & rsStatus("machinestatus") & "</option>" & vbCrLf
    rsStatus.MoveNext
Wend
rsStatus.Close
Set rsStatus = Nothing
%>
                  </select>
                  <select id="winrmFilter" class="btn btn-secondary btn-sm" onchange="updateFilter('winrm', this.value)">
                    <option value="">All WinRM</option>
                    <option value="needswinrm"<% If Request.QueryString("winrm") = "needswinrm" Then Response.Write(" selected") End If%>>Needs WinRM (Has Equipment)</option>
                    <option value="haswinrm"<% If Request.QueryString("winrm") = "haswinrm" Then Response.Write(" selected") End If%>>Has WinRM</option>
                    <option value="nowinrm"<% If Request.QueryString("winrm") = "nowinrm" Then Response.Write(" selected") End If%>>No WinRM</option>
                  </select>
                  <select id="uptimeFilter" class="btn btn-secondary btn-sm" onchange="updateFilter('uptime', this.value)">
                    <option value="">All Uptimes</option>
                    <option value="7"<% If uptimeFilter = "7" Then Response.Write(" selected") End If%>>Uptime > 7 Days</option>
                    <option value="30"<% If uptimeFilter = "30" Then Response.Write(" selected") End If%>>Uptime > 30 Days</option>
                    <option value="90"<% If uptimeFilter = "90" Then Response.Write(" selected") End If%>>Uptime > 90 Days</option>
                  </select>
                  <% If currentPCStatus <> "" Or winrmFilter <> "" Or deviceTypeFilter <> "" Or pcTypeFilter <> "" Or uptimeFilter <> "" Or Request.QueryString("needsrelationship") <> "" Then %>
                  <a href="displaypcs.asp" class="btn btn-outline-secondary btn-sm">
                    <i class="zmdi zmdi-close"></i> Clear
                  </a>
                  <% End If %>
                  <button id="checkAllWarrantiesBtn" class="btn btn-info btn-sm" title="Check Dell warranty API for all PCs without warranty information" disabled>
                    <i class="zmdi zmdi-refresh"></i> Check Warranties
                  </button>
                </div>
              </div>
			  <div class="table-responsive">
              <table class="table table-hover">
                <thead>
                  <tr>
                    <th scope="col">Hostname</th>
                    <th scope="col">Serial</th>
                    <th scope="col">Model</th>
                    <th scope="col">OS</th>
                    <th scope="col">Equipment</th>
                    <th scope="col">Uptime</th>
                    <th scope="col">VNC</th>
                    <th scope="col">WinRM</th>
                  </tr>
                </thead>
                <tbody>

<%
	' Build query based on filters
	Dim pcStatusFilter, winrmFilterSQL, deviceTypeFilterSQL, pcTypeFilterSQL, uptimeFilterSQL, needsRelationshipFilter, whereClause
	pcStatusFilter = Request.QueryString("pcstatus")
	winrmFilterSQL = Request.QueryString("winrm")
	deviceTypeFilterSQL = Request.QueryString("devicetype")
	pcTypeFilterSQL = Request.QueryString("pctype")
	uptimeFilterSQL = Request.QueryString("uptime")
	needsRelationshipFilter = Request.QueryString("needsrelationship")

	' Base query with LEFT JOINs to show all PCs
	strSQL = "SELECT m.machineid, m.hostname, m.serialnumber, m.machinenumber, m.machinestatusid, " & _
	         "m.modelnumberid, m.osid, m.loggedinuser, m.lastupdated, m.isvnc, m.iswinrm, m.lastboottime, " & _
	         "DATEDIFF(NOW(), m.lastboottime) AS uptime_days, " & _
	         "vendors.vendor, models.modelnumber, operatingsystems.operatingsystem, " & _
	         "c.address AS ipaddress, c.macaddress, " & _
	         "machinestatus.machinestatus, " & _
	         "eq.machineid AS equipment_id, eq.machinenumber AS equipment_number " & _
	         "FROM machines m " & _
	         "LEFT JOIN models ON m.modelnumberid = models.modelnumberid " & _
	         "LEFT JOIN vendors ON models.vendorid = vendors.vendorid " & _
	         "LEFT JOIN operatingsystems ON m.osid = operatingsystems.osid " & _
	         "LEFT JOIN communications c ON c.machineid = m.machineid AND c.isprimary = 1 " & _
	         "LEFT JOIN machinestatus ON m.machinestatusid = machinestatus.machinestatusid " & _
	         "LEFT JOIN machinerelationships mr ON (mr.machineid = m.machineid OR mr.related_machineid = m.machineid) AND mr.isactive = 1 AND mr.relationshiptypeid = 3 " & _
	         "LEFT JOIN machines eq ON (eq.machineid = mr.related_machineid OR eq.machineid = mr.machineid) AND eq.machineid <> m.machineid AND eq.pctypeid IS NULL " & _
	         "WHERE m.isactive = 1 AND m.pctypeid IS NOT NULL "

	' Apply filters
	whereClause = ""
	If pcStatusFilter <> "" Then
		whereClause = whereClause & " AND m.machinestatusid = " & pcStatusFilter
	End If

	' Filter by WinRM status
	If winrmFilterSQL = "needswinrm" Then
		' PCs with equipment relationships but no WinRM
		whereClause = whereClause & " AND (m.iswinrm = 0 OR m.iswinrm IS NULL)" & _
		              " AND EXISTS (SELECT 1 FROM machinerelationships mr2 WHERE (mr2.machineid = m.machineid OR mr2.related_machineid = m.machineid) AND mr2.isactive = 1 AND mr2.relationshiptypeid = 3)"
	ElseIf winrmFilterSQL = "haswinrm" Then
		whereClause = whereClause & " AND m.iswinrm = 1"
	ElseIf winrmFilterSQL = "nowinrm" Then
		whereClause = whereClause & " AND (m.iswinrm = 0 OR m.iswinrm IS NULL)"
	End If

	' Filter by device type (laptop vs desktop) based on model name patterns
	If deviceTypeFilterSQL = "laptop" Then
		whereClause = whereClause & " AND (models.modelnumber LIKE '%Latitude%' OR models.modelnumber LIKE '%Precision%' AND (models.modelnumber NOT LIKE '%Tower%'))"
	ElseIf deviceTypeFilterSQL = "desktop" Then
		whereClause = whereClause & " AND (models.modelnumber LIKE '%OptiPlex%' OR models.modelnumber LIKE '%Tower%' OR models.modelnumber LIKE '%Micro%')"
	End If

	' Filter by PC type (pctypeid)
	If pcTypeFilterSQL <> "" And IsNumeric(pcTypeFilterSQL) Then
		whereClause = whereClause & " AND m.pctypeid = " & pcTypeFilterSQL
	End If

	' Filter by uptime (days since last boot)
	If uptimeFilterSQL <> "" And IsNumeric(uptimeFilterSQL) Then
		whereClause = whereClause & " AND m.lastboottime IS NOT NULL AND DATEDIFF(NOW(), m.lastboottime) > " & uptimeFilterSQL
	End If

	' Filter for specialized PCs needing equipment relationships
	If needsRelationshipFilter = "1" Then
		whereClause = whereClause & " AND m.pctypeid = 7" & _
		              " AND NOT EXISTS (SELECT 1 FROM machinerelationships mr WHERE (mr.machineid = m.machineid OR mr.related_machineid = m.machineid) AND mr.relationshiptypeid = 3 AND mr.isactive = 1)"
	End If

	strSQL = strSQL & whereClause & " GROUP BY m.machineid ORDER BY m.machinenumber ASC, m.hostname ASC"

	set rs = objconn.Execute(strSQL)
	while not rs.eof

%>
                  <tr>
                    <td><a href="./displaypc.asp?machineid=<%=rs("machineid")%>" title="Click to Show PC Details"><%
						If IsNull(rs("hostname")) Or rs("hostname") = "" Then
							displayName = rs("serialnumber") & ""
						Else
							displayName = rs("hostname") & ""
						End If
						Response.Write(Server.HTMLEncode(displayName))
					%></a></td>
                    <td><%=Server.HTMLEncode(rs("serialnumber") & "")%></td>
                    <td><%=Server.HTMLEncode(rs("modelnumber") & "")%></td>
                    <td><%=Server.HTMLEncode(rs("operatingsystem") & "")%></td>
                    <td><%
						' Equipment relationship column
						If Not IsNull(rs("equipment_id")) And rs("equipment_id") <> "" Then
							Response.Write("<a href=""./displaymachine.asp?machineid=" & rs("equipment_id") & """ title=""View Equipment"">" & Server.HTMLEncode(rs("equipment_number") & "") & "</a>")
						Else
							Response.Write("<span class='text-muted'>-</span>")
						End If
					%></td>
                    <td><%
						' Uptime column - show days since last boot
						If Not IsNull(rs("uptime_days")) And rs("uptime_days") <> "" Then
							uptimeDays = CLng(rs("uptime_days") & "")
							If uptimeDays > 90 Then
								Response.Write("<span class='badge badge-danger' title='Last boot: " & rs("lastboottime") & "'>" & uptimeDays & "d</span>")
							ElseIf uptimeDays > 30 Then
								Response.Write("<span class='badge badge-warning' title='Last boot: " & rs("lastboottime") & "'>" & uptimeDays & "d</span>")
							ElseIf uptimeDays > 7 Then
								Response.Write("<span class='badge badge-info' title='Last boot: " & rs("lastboottime") & "'>" & uptimeDays & "d</span>")
							Else
								Response.Write("<span class='text-muted' title='Last boot: " & rs("lastboottime") & "'>" & uptimeDays & "d</span>")
							End If
						Else
							Response.Write("<span class='text-muted'>-</span>")
						End If
					%></td>
                    <td><%
						' VNC column with link
						hasVnc = False
						If Not IsNull(rs("isvnc")) Then
							If rs("isvnc") = True Or rs("isvnc") = 1 Or rs("isvnc") = -1 Then
								hasVnc = True
							End If
						End If
						If hasVnc And Not IsNull(rs("hostname")) And rs("hostname") <> "" Then
							vncHost = rs("hostname") & ".logon.ds.ge.com"
							Response.Write("<a href=""com.realvnc.vncviewer.connect://" & Server.HTMLEncode(vncHost) & """ title=""Connect via VNC""><span class='badge badge-success'>VNC</span></a>")
						ElseIf hasVnc And Not IsNull(rs("ipaddress")) And rs("ipaddress") <> "" Then
							' Fallback to IP address if no hostname
							Response.Write("<a href=""com.realvnc.vncviewer.connect://" & Server.HTMLEncode(rs("ipaddress") & "") & """ title=""Connect via VNC (IP)""><span class='badge badge-info'>VNC</span></a>")
						ElseIf hasVnc Then
							Response.Write("<span class='badge badge-warning' title='VNC enabled but no hostname or IP'>VNC</span>")
						Else
							Response.Write("<span class='text-muted'>-</span>")
						End If
					%></td>
                    <td><%
						' WinRM column
						hasWinrm = False
						If Not IsNull(rs("iswinrm")) Then
							If rs("iswinrm") = True Or rs("iswinrm") = 1 Or rs("iswinrm") = -1 Then
								hasWinrm = True
							End If
						End If
						If hasWinrm Then
							Response.Write("<span class='badge badge-success' title='WinRM enabled'>WinRM</span>")
						Else
							Response.Write("<span class='text-muted'>-</span>")
						End If
					%></td>
                  </tr>

<%
	rs.movenext
	wend
	objConn.Close 
%>
                </tbody>
              </table>
            </div>
            </div>
          </div>
        </div>
      </div><!--End Row-->

    <!-- 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>
    </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>

  <!-- Filter Update Script -->
  <script>
  function updateFilter(param, value) {
      var url = new URL(window.location.href);
      var params = new URLSearchParams(url.search);

      if (value === '') {
          params.delete(param);
      } else {
          params.set(param, value);
      }

      window.location.href = 'displaypcs.asp' + (params.toString() ? '?' + params.toString() : '');
  }
  </script>

  <!-- Warranty Check Script -->
  <script>
  $(document).ready(function() {
      $('#checkAllWarrantiesBtn').on('click', function() {
          var $btn = $(this);
          var originalHtml = $btn.html();

          // Confirm with user
          if (!confirm('This will check the Dell warranty API for all PCs without warranty information.\n\nContinue?')) {
              return;
          }

          // Disable button and show loading
          $btn.prop('disabled', true);
          $btn.html('<i class="zmdi zmdi-refresh zmdi-hc-spin"></i> Checking...');

          // Call warranty check endpoint
          $.ajax({
              url: './check_all_warranties.asp',
              type: 'GET',
              dataType: 'json',
              timeout: 300000, // 5 minute timeout
              success: function(response) {
                  if (response.success) {
                      var message = 'Warranty Check Complete!\n\n' +
                            'Total Devices: ' + response.total + '\n' +
                            'Successfully Updated: ' + response.updated + '\n' +
                            'Errors: ' + response.errors;

                      if (response.errorDetails && response.errorDetails.length > 0) {
                          message += '\n\nError Details:\n';
                          for (var i = 0; i < response.errorDetails.length; i++) {
                              var err = response.errorDetails[i];
                              message += '- ' + err.pc + ' (' + err.serial + '): ' + err.reason + '\n';
                          }
                      }

                      message += '\n\nThe page will now reload to show updated information.';
                      alert(message);
                      location.reload();
                  } else {
                      alert('Error: ' + (response.message || 'Unknown error occurred'));
                      $btn.prop('disabled', false);
                      $btn.html(originalHtml);
                  }
              },
              error: function(xhr, status, error) {
                  alert('Error checking warranties:\n' + error + '\n\nPlease try again or contact support.');
                  $btn.prop('disabled', false);
                  $btn.html(originalHtml);
              }
          });
      });
  });
  </script>

</body>
</html>
