<%
'=============================================================================
' FILE: displaysubnet.asp
' PURPOSE: Display detailed subnet information with edit capability
' SECURITY: Parameterized queries, HTML encoding, input validation
' UPDATED: 2025-12-29 - Migrated to match displaypc.asp style
'=============================================================================
%><!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"-->
</head>

<%
	theme = Request.Cookies("theme")
	IF theme = "" THEN
		theme = "bg-theme1"
	END IF

	'=============================================================================
	' SMART REDIRECT: Check if search param is a printer or PC IP address
	'=============================================================================
	Dim search
	search = Trim(Request.QueryString("search") & "")

	IF search <> "" THEN
		' Check if this IP belongs to a printer
		Dim rsPrinterCheck, strPrinterSQL
		strPrinterSQL = "SELECT printerid FROM printers WHERE ipaddress = ?"
		Set rsPrinterCheck = ExecuteParameterizedQuery(objConn, strPrinterSQL, Array(search))
		IF NOT rsPrinterCheck.EOF THEN
			Dim printerRedirectId
			printerRedirectId = rsPrinterCheck("printerid")
			rsPrinterCheck.Close
			Set rsPrinterCheck = Nothing
			objConn.Close
			Response.Redirect("./displayprinter.asp?printerid=" & printerRedirectId)
			Response.End
		END IF
		rsPrinterCheck.Close
		Set rsPrinterCheck = Nothing

		' Check if this IP belongs to a PC (Phase 2: uses communications table)
		Dim rsPCCheck, strPCSQL
		strPCSQL = "SELECT m.machineid FROM machines m " & _
				"INNER JOIN communications c ON m.machineid = c.machineid " & _
				"WHERE c.address = ? AND m.pctypeid IS NOT NULL AND c.isactive = 1"
		Set rsPCCheck = ExecuteParameterizedQuery(objConn, strPCSQL, Array(search))
		IF NOT rsPCCheck.EOF THEN
			Dim pcRedirectId
			pcRedirectId = rsPCCheck("machineid")
			rsPCCheck.Close
			Set rsPCCheck = Nothing
			objConn.Close
			Response.Redirect("./displaypc.asp?machineid=" & pcRedirectId)
			Response.End
		END IF
		rsPCCheck.Close
		Set rsPCCheck = Nothing
	END IF

	'=============================================================================
	' SECURITY: Validate subnet ID input
	'=============================================================================
	Dim subnetid
	subnetid = GetSafeInteger("QS", "subnetid", 0, 1, 999999)

	IF subnetid = 0 THEN
		objConn.Close
		Response.Redirect("displaysubnets.asp")
		Response.End
	END IF

	'=============================================================================
	' SECURITY: Use parameterized query to prevent SQL injection
	'=============================================================================
	Dim strSQL, rs
	strSQL = "SELECT subnets.*, subnettypes.subnettype, " & _
			"INET_NTOA(subnets.ipstart) AS subnetstart, " & _
			"INET_NTOA(subnets.ipend) AS subnetend " & _
			"FROM subnets " & _
			"LEFT JOIN subnettypes ON subnets.subnettypeid = subnettypes.subnettypeid " & _
			"WHERE subnets.isactive = 1 AND subnets.subnetid = ?"

	Set rs = ExecuteParameterizedQuery(objConn, strSQL, Array(subnetid))

	' Check if subnet exists
	IF rs.EOF THEN
		objConn.Close
		Response.Redirect("displaysubnets.asp")
		Response.End
	END IF

	' Store values for use in page
	Dim vlanVal, zoneVal, networkVal, networkEndVal, cidrVal, descVal, ipStartInt, ipEndInt
	vlanVal = rs("vlan") & ""
	zoneVal = rs("subnettype") & ""
	networkVal = rs("subnetstart") & ""
	networkEndVal = rs("subnetend") & ""
	cidrVal = rs("cidr") & ""
	descVal = rs("description") & ""
	ipStartInt = rs("ipstart")
	ipEndInt = rs("ipend")

	If vlanVal = "" Then vlanVal = "N/A"
	If zoneVal = "" Then zoneVal = "Unknown"
	If networkVal = "" Then networkVal = "N/A"
	If cidrVal = "" Then cidrVal = ""
	If descVal = "" Then descVal = "No description"

	' Calculate usable IPs
	Dim usableIPs
	If IsNumeric(ipStartInt) And IsNumeric(ipEndInt) Then
		usableIPs = CLng(ipEndInt) - CLng(ipStartInt)
	Else
		usableIPs = 0
	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/network/subnet-banner.png" alt="Subnet" onerror="this.src='./images/machines/default.png'">
            </div>
            <div class="card-body pt-5">
                <img src="./images/network/subnet-icon.png" alt="subnet-icon" class="profile" onerror="this.src='./images/machines/default.png'">
                <h5 class="card-title"><%=Server.HTMLEncode(networkVal)%><%=Server.HTMLEncode(cidrVal)%></h5>
                <p class="card-text">VLAN <%=Server.HTMLEncode(vlanVal)%></p>
                <p class="card-text text-muted"><%=Server.HTMLEncode(zoneVal)%></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">Details</span></a>
                </li>
                <li class="nav-item">
                    <a href="javascript:void();" data-target="#devices" data-toggle="pill" class="nav-link"><i class="zmdi zmdi-devices"></i> <span class="hidden-xs">Devices</span></a>
                </li>
                <li class="nav-item">
                    <a href="javascript:void();" data-target="#edit" data-toggle="pill" class="nav-link"><i class="icon-note"></i> <span class="hidden-xs">Edit</span></a>
                </li>
            </ul>
            <div class="tab-content p-3">
                <div class="tab-pane active" id="profile">
                    <h5 class="mb-3">Subnet Configuration</h5>
                    <div class="row">
                        <div class="col-md-3">
                            <p class="mb-2"><strong>VLAN:</strong></p>
                            <p class="mb-2"><strong>Zone:</strong></p>
                            <p class="mb-2"><strong>Network:</strong></p>
                            <p class="mb-2"><strong>CIDR:</strong></p>
                            <p class="mb-2"><strong>IP Range:</strong></p>
                            <p class="mb-2"><strong>Usable IPs:</strong></p>
                            <p class="mb-2"><strong>Description:</strong></p>
                        </div>
                        <div class="col-md-9">
                            <p class="mb-2"><%=Server.HTMLEncode(vlanVal)%></p>
                            <p class="mb-2"><span class="badge badge-info"><%=Server.HTMLEncode(zoneVal)%></span></p>
                            <p class="mb-2"><%=Server.HTMLEncode(networkVal)%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(cidrVal)%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(networkVal)%> - <%=Server.HTMLEncode(networkEndVal)%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(CStr(usableIPs))%></p>
                            <p class="mb-2"><%=Server.HTMLEncode(descVal)%></p>
                        </div>
                    </div>
                </div>

                <div class="tab-pane" id="devices">
                    <h5 class="mb-3">Devices on this Subnet</h5>
                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>Name</th>
                                    <th>IP Address</th>
                                </tr>
                            </thead>
                            <tbody>
<%
	' Get PCs on this subnet using machines/communications tables
	Dim strSQL2, rs2, deviceCount
	deviceCount = 0

	' Query for PCs (machines with pctypeid IS NOT NULL)
	strSQL2 = "SELECT m.machineid, m.hostname, c.address " & _
			"FROM machines m " & _
			"INNER JOIN communications c ON m.machineid = c.machineid AND c.isprimary = 1 " & _
			"WHERE m.isactive = 1 AND m.pctypeid IS NOT NULL " & _
			"AND INET_ATON(c.address) >= " & CLng(ipStartInt) & " " & _
			"AND INET_ATON(c.address) <= " & CLng(ipEndInt) & " " & _
			"ORDER BY INET_ATON(c.address)"

	Set rs2 = objConn.Execute(strSQL2)

	Do While Not rs2.EOF
		deviceCount = deviceCount + 1
		Dim pcDeviceName, pcDeviceIP, pcDeviceId
		pcDeviceName = rs2("hostname") & ""
		pcDeviceIP = rs2("address") & ""
		pcDeviceId = rs2("machineid")
		If pcDeviceName = "" Then pcDeviceName = "Unknown"
%>
                                <tr>
                                    <td><span class="badge badge-primary">PC</span></td>
                                    <td><a href="displaypc.asp?machineid=<%=pcDeviceId%>"><%=Server.HTMLEncode(pcDeviceName)%></a></td>
                                    <td><%=Server.HTMLEncode(pcDeviceIP)%></td>
                                </tr>
<%
		rs2.MoveNext
	Loop
	rs2.Close
	Set rs2 = Nothing

	' Query for Printers
	Dim strSQL3, rs3
	strSQL3 = "SELECT printerid, printerwindowsname, ipaddress " & _
			"FROM printers " & _
			"WHERE isactive = 1 " & _
			"AND INET_ATON(ipaddress) >= " & CLng(ipStartInt) & " " & _
			"AND INET_ATON(ipaddress) <= " & CLng(ipEndInt) & " " & _
			"ORDER BY INET_ATON(ipaddress)"

	Set rs3 = objConn.Execute(strSQL3)

	Do While Not rs3.EOF
		deviceCount = deviceCount + 1
		Dim prtName, prtIP, prtId
		prtName = rs3("printerwindowsname") & ""
		prtIP = rs3("ipaddress") & ""
		prtId = rs3("printerid")
		If prtName = "" Then prtName = "Unknown Printer"
%>
                                <tr>
                                    <td><span class="badge badge-success">Printer</span></td>
                                    <td><a href="displayprinter.asp?printerid=<%=prtId%>"><%=Server.HTMLEncode(prtName)%></a></td>
                                    <td><%=Server.HTMLEncode(prtIP)%></td>
                                </tr>
<%
		rs3.MoveNext
	Loop
	rs3.Close
	Set rs3 = Nothing

	If deviceCount = 0 Then
%>
                                <tr>
                                    <td colspan="3" class="text-muted text-center">No devices found on this subnet</td>
                                </tr>
<%
	End If
%>
                            </tbody>
                        </table>
                    </div>
                    <p class="text-muted mt-2"><small>Total devices: <%=deviceCount%></small></p>
                </div>

                <div class="tab-pane" id="edit">
                    <form method="post" action="./updatesubnetdirect.asp?subnetid=<%=subnetid%>" id="subnetEditForm">

                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">VLAN #:</label>
                            <div class="col-lg-9">
                                <input type="text" class="form-control" name="vlan" value="<%=Server.HTMLEncode(rs("vlan") & "")%>" maxlength="10">
                            </div>
                        </div>

                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Zone:</label>
                            <div class="col-lg-9">
                                <select name="subnettypeid" class="form-control">
                                    <option value="<%=Server.HTMLEncode(rs("subnettypeid") & "")%>"><%=Server.HTMLEncode(zoneVal)%></option>
<%
	Dim rsTypes, strTypesSQL
	strTypesSQL = "SELECT * FROM subnettypes WHERE isactive = 1 ORDER BY subnettype ASC"
	Set rsTypes = objConn.Execute(strTypesSQL)
	Do While Not rsTypes.EOF
		If CStr(rsTypes("subnettypeid") & "") <> CStr(rs("subnettypeid") & "") Then
			Response.Write("<option value='" & Server.HTMLEncode(rsTypes("subnettypeid") & "") & "'>" & Server.HTMLEncode(rsTypes("subnettype") & "") & "</option>")
		End If
		rsTypes.MoveNext
	Loop
	rsTypes.Close
	Set rsTypes = Nothing
%>
                                </select>
                            </div>
                        </div>

                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Network:</label>
                            <div class="col-lg-9">
                                <input type="text" class="form-control" name="ipstart" value="<%=Server.HTMLEncode(networkVal)%>" placeholder="e.g., 192.168.1.0">
                            </div>
                        </div>

                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">CIDR:</label>
                            <div class="col-lg-9">
                                <select name="cidr" class="form-control">
                                    <option value="<%=Server.HTMLEncode(cidrVal)%>,<%=usableIPs%>"><%=Server.HTMLEncode(cidrVal)%></option>
                                    <option value="/30,3">/30 (4 IPs)</option>
                                    <option value="/29,7">/29 (8 IPs)</option>
                                    <option value="/28,15">/28 (16 IPs)</option>
                                    <option value="/27,31">/27 (32 IPs)</option>
                                    <option value="/26,63">/26 (64 IPs)</option>
                                    <option value="/25,127">/25 (128 IPs)</option>
                                    <option value="/24,253">/24 (256 IPs)</option>
                                    <option value="/23,511">/23 (512 IPs)</option>
                                    <option value="/22,1023">/22 (1024 IPs)</option>
                                    <option value="/21,2047">/21 (2048 IPs)</option>
                                    <option value="/20,4095">/20 (4096 IPs)</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label">Description:</label>
                            <div class="col-lg-9">
                                <input type="text" class="form-control" name="description" value="<%=Server.HTMLEncode(rs("description") & "")%>" maxlength="255">
                            </div>
                        </div>

                        <div class="form-group row">
                            <label class="col-lg-3 col-form-label form-control-label"></label>
                            <div class="col-lg-9">
                                <input type="reset" class="btn btn-secondary" value="Cancel">
                                <input type="submit" class="btn btn-primary" value="Save Changes">
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
      </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>

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

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