<!DOCTYPE html>
<html lang="en">
<head>
  <!--#include file="./includes/header.asp"-->
  <!--#include file="./includes/sql.asp"-->
  <!--#include file="./includes/db_helpers.asp"-->
</head>

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

	Dim machineid, isScanned
	machineid = Request.QueryString("pcid") ' Parameter named pcid for backwards compatibility
	If machineid = "" Then machineid = Request.QueryString("machineid")
	isScanned = Request.QueryString("scanned")

	' Validate machineid
	If Not IsNumeric(machineid) Or CLng(machineid) < 1 Then
		Response.Write("Invalid device ID")
		Response.End
	End If

	' Get PC data using parameterized query - PHASE 2: Use machines table
	Dim strSQL, rs
	strSQL = "SELECT machines.*, machinestatus.machinestatus, pctype.typename " & _
			 "FROM machines " & _
			 "LEFT JOIN machinestatus ON machines.machinestatusid = machinestatus.machinestatusid " & _
			 "LEFT JOIN pctype ON machines.pctypeid = pctype.pctypeid " & _
			 "WHERE machines.machineid = ? AND machines.pctypeid IS NOT NULL"

	Set rs = ExecuteParameterizedQuery(objconn, strSQL, Array(CLng(machineid)))

	If rs.EOF Then
		Response.Write("Device not found")
		Response.End
	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="container-fluid">
      <div class="row mt-3">
        <div class="col-lg-8 offset-lg-2">
          <div class="card">
            <div class="card-body">
              <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
                <h5 class="card-title" style="margin:0;">
                  <i class="zmdi zmdi-edit"></i> Edit Device - <span style="font-family:monospace;"><%=Server.HTMLEncode(rs("serialnumber"))%></span>
                </h5>
                <a href="./adddevice.asp" class="btn btn-sm btn-secondary">
                  <i class="zmdi zmdi-arrow-left"></i> Back to Scan
                </a>
              </div>

<%
Dim errorType, errorMsg
errorType = Request.QueryString("error")
errorMsg = Request.QueryString("msg")

If isScanned = "1" Then
%>
              <div class="alert alert-warning">
                <i class="zmdi zmdi-alert-triangle"></i> <strong>Device already exists!</strong> Update the details below.
              </div>
<%
ElseIf errorType = "required" Then
%>
              <div class="alert alert-danger">
                <i class="zmdi zmdi-close-circle"></i> <strong>Error!</strong> Status is required.
              </div>
<%
ElseIf errorType = "db" Then
%>
              <div class="alert alert-danger">
                <i class="zmdi zmdi-close-circle"></i> <strong>Database Error:</strong> <%=Server.HTMLEncode(errorMsg)%>
              </div>
<%
End If
%>

              <form method="post" action="./updatedevice_direct.asp" id="editForm">
                <input type="hidden" name="pcid" value="<%=machineid%>">

                <div class="form-group">
                  <label for="serialnumber">Serial Number</label>
                  <input type="text" class="form-control readonly-serial" id="serialnumber" name="serialnumber"
                         value="<%=Server.HTMLEncode(rs("serialnumber"))%>" readonly>
                </div>

                <div class="form-group">
                  <label for="machinestatusid">Status <span class="text-danger">*</span></label>
                  <select class="form-control" id="machinestatusid" name="machinestatusid" required>
<%
	Dim rsStatus, sqlStatus
	sqlStatus = "SELECT machinestatusid, machinestatus FROM machinestatus ORDER BY machinestatusid"
	Set rsStatus = objconn.Execute(sqlStatus)

	While Not rsStatus.EOF
		Dim selectedStatus
		selectedStatus = ""
		If Not IsNull(rs("machinestatusid")) And rsStatus("machinestatusid") = rs("machinestatusid") Then
			selectedStatus = " selected"
		End If
		Response.Write("<option value='" & rsStatus("machinestatusid") & "'" & selectedStatus & ">" & rsStatus("machinestatus") & "</option>")
		rsStatus.MoveNext
	Wend
	rsStatus.Close
%>
                  </select>
                </div>

                <div class="form-group">
                  <label for="pctypeid">Type</label>
                  <select class="form-control" id="pctypeid" name="pctypeid">
                    <option value="">-- Not Set --</option>
<%
	Dim rsType, sqlType
	sqlType = "SELECT pctypeid, typename FROM pctype WHERE isactive = 1 ORDER BY displayorder"
	Set rsType = objconn.Execute(sqlType)

	While Not rsType.EOF
		Dim selectedType
		selectedType = ""
		If Not IsNull(rs("pctypeid")) And rsType("pctypeid") = rs("pctypeid") Then
			selectedType = " selected"
		End If
		Response.Write("<option value='" & rsType("pctypeid") & "'" & selectedType & ">" & rsType("typename") & "</option>")
		rsType.MoveNext
	Wend
	rsType.Close
%>
                  </select>
                </div>

                <div class="form-group">
                  <label for="hostname">Hostname</label>
                  <input type="text" class="form-control" id="hostname" name="hostname"
                         value="<%If Not IsNull(rs("hostname")) Then Response.Write(Server.HTMLEncode(rs("hostname")))%>"
                         placeholder="e.g., DESKTOP-ABC123">
                </div>

                <div class="form-group">
                  <label for="modelnumberid">Model</label>
                  <div class="input-group">
                    <select class="form-control" id="modelnumberid" name="modelnumberid">
                      <option value="">-- Not Set --</option>
                      <option value="new">+ Add New Model</option>
<%
	Dim rsModel, sqlModel
	sqlModel = "SELECT models.modelnumberid, models.modelnumber, vendors.vendor " & _
			   "FROM models " & _
			   "INNER JOIN vendors ON models.vendorid = vendors.vendorid " & _
			   "WHERE vendors.ispc = 1 " & _
			   "ORDER BY vendors.vendor, models.modelnumber"
	Set rsModel = objconn.Execute(sqlModel)

	While Not rsModel.EOF
		Dim selectedModel
		selectedModel = ""
		If Not IsNull(rs("modelnumberid")) And rsModel("modelnumberid") = rs("modelnumberid") Then
			selectedModel = " selected"
		End If
		Response.Write("<option value='" & rsModel("modelnumberid") & "'" & selectedModel & ">" & rsModel("vendor") & " - " & rsModel("modelnumber") & "</option>")
		rsModel.MoveNext
	Wend
	rsModel.Close
%>
                    </select>
                    <div class="input-group-append">
                      <button type="button" class="btn btn-info" id="addModelBtn">
                        <i class="zmdi zmdi-plus"></i> New
                      </button>
                    </div>
                  </div>
                </div>

                <!-- New Model Fields (hidden by default) -->
                <div id="newModelSection" style="display:none; margin-left:20px; padding:15px; border-left:3px solid #007bff; background-color:rgba(0,123,255,0.05); margin-bottom:20px;">
                  <h6 style="color:#007bff; margin-bottom:15px;"><i class="zmdi zmdi-plus-circle"></i> New Model Details</h6>

                  <div class="form-group">
                    <label for="newmodelnumber">Model Number</label>
                    <input type="text" class="form-control" id="newmodelnumber" name="newmodelnumber" placeholder="e.g., OptiPlex 7090">
                  </div>

                  <div class="form-group">
                    <label for="newvendorid">Vendor</label>
                    <div class="input-group">
                      <select class="form-control" id="newvendorid" name="newvendorid">
                        <option value="">-- Select --</option>
                        <option value="new">+ Add New Vendor</option>
<%
	Dim rsVendor, sqlVendor
	sqlVendor = "SELECT vendorid, vendor FROM vendors WHERE ispc = 1 ORDER BY vendor"
	Set rsVendor = objconn.Execute(sqlVendor)

	While Not rsVendor.EOF
		Response.Write("<option value='" & rsVendor("vendorid") & "'>" & rsVendor("vendor") & "</option>")
		rsVendor.MoveNext
	Wend
	rsVendor.Close
%>
                      </select>
                      <div class="input-group-append">
                        <button type="button" class="btn btn-info" id="addVendorBtn">
                          <i class="zmdi zmdi-plus"></i> New
                        </button>
                      </div>
                    </div>
                  </div>

                  <!-- New Vendor Fields (nested, hidden by default) -->
                  <div id="newVendorSection" style="display:none; margin-left:20px; padding:15px; border-left:3px solid #28a745; background-color:rgba(40,167,69,0.05); margin-bottom:15px;">
                    <h6 style="color:#28a745; margin-bottom:15px;"><i class="zmdi zmdi-plus-circle"></i> New Vendor</h6>
                    <div class="form-group">
                      <label for="newvendorname">Vendor Name</label>
                      <input type="text" class="form-control" id="newvendorname" name="newvendorname" placeholder="e.g., Dell, HP, Lenovo">
                    </div>
                  </div>
                </div>

                <div class="form-group">
                  <label for="machinenumber">Machine Number</label>
                  <input type="text" class="form-control" id="machinenumber" name="machinenumber"
                         value="<%If Not IsNull(rs("machinenumber")) Then Response.Write(Server.HTMLEncode(rs("machinenumber")))%>"
                         placeholder="e.g., 101">
                </div>

                <div class="form-group">
                  <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="isactive" name="isactive" value="1"
                           <%If rs("isactive") = True Or rs("isactive") = 1 Then Response.Write("checked")%>>
                    <label class="custom-control-label" for="isactive">Active</label>
                  </div>
                  <small class="form-text text-muted">Default: Active (checked)</small>
                </div>

                <div class="text-center" style="margin-top:30px;">
                  <button type="submit" class="btn btn-primary btn-lg" id="saveBtn">
                    <i class="zmdi zmdi-check"></i> Save & Return to Scan
                  </button>
                </div>
              </form>

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

<script>
$(document).ready(function() {
    // Auto-focus on status dropdown for quick keyboard selection
    $('#machinestatusid').focus();

    // Model dropdown change handler
    $('#modelnumberid').on('change', function() {
        if ($(this).val() === 'new') {
            $('#newModelSection').slideDown();
        } else {
            $('#newModelSection').slideUp();
            $('#newvendorid').val('');
            $('#newVendorSection').hide();
        }
    });

    // Model "+ New" button
    $('#addModelBtn').on('click', function() {
        $('#modelnumberid').val('new').trigger('change');
    });

    // Vendor dropdown change handler (nested)
    $('#newvendorid').on('change', function() {
        if ($(this).val() === 'new') {
            $('#newVendorSection').slideDown();
        } else {
            $('#newVendorSection').slideUp();
        }
    });

    // Vendor "+ New" button (nested)
    $('#addVendorBtn').on('click', function() {
        $('#newvendorid').val('new').trigger('change');
    });
});
</script>

</body>
</html>
<%
rs.Close
objConn.Close
%>
