<!DOCTYPE html>
<html lang="en">
<head>
  <!--#include file="./includes/header.asp"-->
  <!--#include file="./includes/sql.asp"-->
  <style>
    .employee-search-container {
      position: relative;
    }
    .employee-dropdown {
      position: absolute;
      top: 100%;
      left: 0;
      right: 0;
      background: #fff;
      border: 1px solid #ced4da;
      border-top: none;
      border-radius: 0 0 .25rem .25rem;
      max-height: 300px;
      overflow-y: auto;
      z-index: 1000;
      box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .employee-option {
      display: flex;
      align-items: center;
      padding: 10px 12px;
      cursor: pointer;
      border-bottom: 1px solid #eee;
    }
    .employee-option:hover {
      background-color: #f8f9fa;
    }
    .employee-option:last-child {
      border-bottom: none;
    }
    .employee-option img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      object-fit: cover;
      margin-right: 12px;
      border: 2px solid #007bff;
    }
    .employee-option .ge-logo {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      margin-right: 12px;
      background: #007bff;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .employee-option .ge-logo img {
      width: 24px;
      height: 24px;
      border: none;
      border-radius: 0;
    }
    .employee-option-info {
      flex: 1;
    }
    .employee-option-name {
      font-weight: 600;
      color: #333;
    }
    .employee-option-sso {
      font-size: 12px;
      color: #666;
    }
    .employee-option-custom {
      color: #28a745;
      font-style: italic;
    }
    .selected-employees {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
    .selected-employee {
      display: flex;
      align-items: center;
      background: #ffffff;
      border: 1px solid #dee2e6;
      border-radius: 20px;
      padding: 5px 10px 5px 5px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    /* Dark theme support */
    .bg-theme4 .selected-employee,
    .bg-theme5 .selected-employee,
    .bg-theme6 .selected-employee,
    .bg-dark .selected-employee {
      background: #2d3748;
      border-color: #4a5568;
    }
    .selected-employee img {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      object-fit: cover;
      margin-right: 8px;
    }
    .selected-employee .ge-logo-small {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      margin-right: 8px;
      background: #007bff;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .selected-employee .ge-logo-small img {
      width: 18px;
      height: 18px;
    }
    .selected-employee-name {
      font-size: 14px;
      margin-right: 8px;
      color: #333;
    }
    /* Dark theme text */
    .bg-theme4 .selected-employee-name,
    .bg-theme5 .selected-employee-name,
    .bg-theme6 .selected-employee-name,
    .bg-dark .selected-employee-name {
      color: #e2e8f0;
    }
    .selected-employee-remove {
      cursor: pointer;
      color: #dc3545;
      font-weight: bold;
      font-size: 16px;
    }
    .selected-employee-remove:hover {
      color: #a71d2a;
    }
  </style>
</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="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-plus-circle"></i> Add Notification
                </h5>
                <a href="./displaynotifications.asp" class="btn btn-sm btn-secondary">
                  <i class="zmdi zmdi-arrow-left"></i> Back to Notifications
                </a>
              </div>

              <form method="post" action="./savenotificationdirect.asp">
                <div class="form-group">
                  <label for="notification">Message <span class="text-danger">*</span></label>
                  <textarea class="form-control" id="notification" name="notification" rows="3"
                         required maxlength="500" placeholder="Enter notification message"></textarea>
                  <small class="form-text text-muted">This message will appear on the dashboard</small>
                </div>

                <div class="form-group">
                  <label for="notificationtypeid">Type <span class="text-danger">*</span></label>
                  <select class="form-control" id="notificationtypeid" name="notificationtypeid" required>
<%
                    Dim rsTypes
                    Set rsTypes = objConn.Execute("SELECT notificationtypeid, typename, typedescription FROM notificationtypes WHERE isactive = 1 ORDER BY notificationtypeid")
                    While Not rsTypes.EOF
                      Dim isDefaultType
                      isDefaultType = ""
                      If rsTypes("typename") = "TBD" Then
                        isDefaultType = " selected"
                      End If
%>
                    <option value="<%=rsTypes("notificationtypeid")%>"<%=isDefaultType%>><%=rsTypes("typename")%><%If Not IsNull(rsTypes("typedescription")) Then%> - <%=rsTypes("typedescription")%><%End If%></option>
<%
                      rsTypes.MoveNext
                    Wend
                    rsTypes.Close
                    Set rsTypes = Nothing
%>
                  </select>
                  <small class="form-text text-muted">Classification type for this notification</small>
                </div>

                <div class="form-group">
                  <label for="businessunitid">Business Unit <span class="text-muted">(Optional - blank applies to all)</span></label>
                  <select class="form-control" id="businessunitid" name="businessunitid">
                    <option value="">-- All Business Units --</option>
<%
                    Dim rsBusinessUnits
                    Set rsBusinessUnits = objConn.Execute("SELECT businessunitid, businessunit FROM businessunits WHERE isactive = 1 ORDER BY businessunit")
                    While Not rsBusinessUnits.EOF
%>
                    <option value="<%=rsBusinessUnits("businessunitid")%>"><%=rsBusinessUnits("businessunit")%></option>
<%
                      rsBusinessUnits.MoveNext
                    Wend
                    rsBusinessUnits.Close
                    Set rsBusinessUnits = Nothing
%>
                  </select>
                  <small class="form-text text-muted">Select a specific business unit or leave blank to apply to all</small>
                </div>

                <div class="form-group">
                  <label for="appid">Related Application <span class="text-muted">(Optional)</span></label>
                  <select class="form-control" id="appid" name="appid">
                    <option value="">-- No Application --</option>
<%
                    Dim rsApps
                    Set rsApps = objConn.Execute("SELECT appid, appname FROM applications WHERE isactive = 1 ORDER BY appname")
                    While Not rsApps.EOF
%>
                    <option value="<%=rsApps("appid")%>"><%=Server.HTMLEncode(rsApps("appname") & "")%></option>
<%
                      rsApps.MoveNext
                    Wend
                    rsApps.Close
                    Set rsApps = Nothing
%>
                  </select>
                  <small class="form-text text-muted">Link this notification to a specific application (e.g., for software updates)</small>
                </div>

                <div class="form-group" id="ticketnumberGroup">
                  <label for="ticketnumber">Ticket Number</label>
                  <input type="text" class="form-control" id="ticketnumber" name="ticketnumber"
                         maxlength="50" placeholder="GEINC123456 or GECHG123456">
                  <small class="form-text text-muted">Optional ServiceNow ticket number</small>
                </div>

                <div class="form-group" id="employeessoGroup" style="display:none;">
                  <label for="employeeSearch">Employee(s) <span class="text-danger">*</span></label>
                  <div class="employee-search-container">
                    <input type="text" class="form-control" id="employeeSearch"
                           placeholder="Search by name or type a custom name..."
                           autocomplete="off">
                    <div id="employeeDropdown" class="employee-dropdown" style="display:none;"></div>
                  </div>
                  <small class="form-text text-muted">Search for employees or type a name for non-system users. Press Enter to add custom names.</small>

                  <div id="selectedEmployees" class="selected-employees mt-2"></div>

                  <!-- Hidden field for form submission (stores SSO or NAME:customname) -->
                  <input type="hidden" id="employeesso" name="employeesso" value="">
                </div>

                <div class="form-row" id="timeFieldsRow">
                  <div class="form-group col-md-6">
                    <label for="starttime">Start Time <span class="text-danger">*</span></label>
                    <div class="input-group">
                      <input type="datetime-local" class="form-control" id="starttime" name="starttime" required>
                      <div class="input-group-append">
                        <button type="button" class="btn btn-outline-primary" onclick="setNow('starttime')" title="Set to current date/time">
                          <i class="zmdi zmdi-time"></i> Now
                        </button>
                      </div>
                    </div>
                    <small class="form-text text-muted">When notification becomes visible</small>
                  </div>

                  <div class="form-group col-md-6">
                    <label for="endtime">End Time <span class="text-muted">(Optional - indefinite if blank)</span></label>
                    <div class="input-group">
                      <input type="datetime-local" class="form-control" id="endtime" name="endtime">
                      <div class="input-group-append">
                        <button type="button" class="btn btn-outline-primary" onclick="setNow('endtime')" title="Set to current date/time">
                          <i class="zmdi zmdi-time"></i> Now
                        </button>
                        <button type="button" class="btn btn-outline-secondary" onclick="clearEndtime()" title="Clear to make indefinite">
                          <i class="zmdi zmdi-close"></i>
                        </button>
                      </div>
                    </div>
                    <small class="form-text text-muted">Leave blank for indefinite (will display until you set an end date)</small>
                  </div>
                </div>

                <div class="form-group">
                  <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="isactive" name="isactive" value="1" checked>
                    <label class="custom-control-label" for="isactive">Active</label>
                  </div>
                  <small class="form-text text-muted">Uncheck to save as draft without displaying</small>
                </div>

                <div class="form-group">
                  <div class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" id="isshopfloor" name="isshopfloor" value="1">
                    <label class="custom-control-label" for="isshopfloor">Show on Shopfloor Dashboard</label>
                  </div>
                  <small class="form-text text-muted">Check this to display on the shopfloor TV dashboard (72-hour window)</small>
                </div>

                <hr>

                <div class="form-group text-right">
                  <button type="submit" class="btn btn-primary btn-lg">
                    <i class="zmdi zmdi-check"></i> Add Notification
                  </button>
                  <a href="./displaynotifications.asp" class="btn btn-secondary btn-lg">
                    <i class="zmdi zmdi-close"></i> Cancel
                  </a>
                </div>
              </form>

            </div>
          </div>
        </div>
      </div>
      <!-- End Row -->

    </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>
    // Format: YYYY-MM-DDTHH:MM
    function formatDateTime(date) {
      var year = date.getFullYear();
      var month = ('0' + (date.getMonth() + 1)).slice(-2);
      var day = ('0' + date.getDate()).slice(-2);
      var hours = ('0' + date.getHours()).slice(-2);
      var minutes = ('0' + date.getMinutes()).slice(-2);
      return year + '-' + month + '-' + day + 'T' + hours + ':' + minutes;
    }

    // Set field to current date/time
    function setNow(fieldId) {
      var now = new Date();
      document.getElementById(fieldId).value = formatDateTime(now);
    }

    // Clear end time to make notification indefinite
    function clearEndtime() {
      document.getElementById('endtime').value = '';
    }

    // Set default start time to now
    // Leave end time blank for indefinite
    document.addEventListener('DOMContentLoaded', function() {
      var now = new Date();
      var startInput = document.getElementById('starttime');

      startInput.value = formatDateTime(now);
      // Leave endInput blank by default for indefinite notifications

      // Handle notification type change
      var typeSelect = document.getElementById('notificationtypeid');
      typeSelect.addEventListener('change', handleTypeChange);
      handleTypeChange(); // Initial check
    });

    // Recognition type ID (from database)
    var RECOGNITION_TYPE_ID = '5';

    function handleTypeChange() {
      var typeSelect = document.getElementById('notificationtypeid');
      var selectedText = typeSelect.options[typeSelect.selectedIndex].text;
      var isRecognition = selectedText.toLowerCase().indexOf('recognition') !== -1;

      // Show/hide SSO field
      document.getElementById('employeessoGroup').style.display = isRecognition ? 'block' : 'none';
      document.getElementById('employeesso').required = isRecognition;

      // Show/hide time fields and ticket number for Recognition
      document.getElementById('timeFieldsRow').style.display = isRecognition ? 'none' : 'flex';
      document.getElementById('ticketnumberGroup').style.display = isRecognition ? 'none' : 'block';

      // For Recognition, remove required from starttime
      document.getElementById('starttime').required = !isRecognition;

      // Auto-check shopfloor dashboard for Recognition
      if (isRecognition) {
        document.getElementById('isshopfloor').checked = true;
      }
    }

    // Employee autocomplete functionality
    var searchTimeout = null;
    var selectedEmployees = []; // Array of {sso, name, picture, isCustom}
    var EMPLOYEE_PHOTO_BASE = 'https://tsgwp00525.rd.ds.ge.com/EmployeeDBAPP/images/';
    var GE_LOGO_URL = './shopfloor-dashboard/ge-aerospace-logo.svg';

    document.addEventListener('DOMContentLoaded', function() {
      var searchInput = document.getElementById('employeeSearch');
      var dropdown = document.getElementById('employeeDropdown');

      // Search on input
      searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        var query = this.value.trim();

        if (query.length < 2) {
          dropdown.style.display = 'none';
          return;
        }

        searchTimeout = setTimeout(function() {
          searchEmployees(query);
        }, 300);
      });

      // Handle Enter key for custom names
      searchInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          var customName = this.value.trim();
          if (customName.length > 0) {
            addEmployee(null, customName, null, true);
            this.value = '';
            dropdown.style.display = 'none';
          }
        }
      });

      // Close dropdown when clicking outside
      document.addEventListener('click', function(e) {
        if (!e.target.closest('.employee-search-container')) {
          dropdown.style.display = 'none';
        }
      });
    });

    function searchEmployees(query) {
      var dropdown = document.getElementById('employeeDropdown');

      fetch('./apiemployeesearch.asp?q=' + encodeURIComponent(query) + '&limit=8')
        .then(function(response) { return response.json(); })
        .then(function(data) {
          if (data.success && data.results) {
            renderDropdown(data.results, query);
          } else {
            renderDropdown([], query);
          }
        })
        .catch(function(err) {
          renderDropdown([], query);
        });
    }

    function renderDropdown(results, query) {
      var dropdown = document.getElementById('employeeDropdown');
      var html = '';

      // Show matching employees
      results.forEach(function(emp) {
        // Check if already selected
        var isSelected = selectedEmployees.some(function(s) { return s.sso === emp.sso; });
        if (isSelected) return;

        var photoHtml;
        if (emp.picture) {
          photoHtml = '<img src="' + EMPLOYEE_PHOTO_BASE + emp.picture + '" onerror="this.parentNode.innerHTML=\'<div class=ge-logo><img src=' + GE_LOGO_URL + '></div>\'">';
        } else {
          photoHtml = '<div class="ge-logo"><img src="' + GE_LOGO_URL + '"></div>';
        }

        html += '<div class="employee-option" onclick="selectEmployee(\'' + emp.sso + '\', \'' + escapeHtml(emp.fullName) + '\', \'' + (emp.picture || '') + '\')">';
        html += photoHtml;
        html += '<div class="employee-option-info">';
        html += '<div class="employee-option-name">' + escapeHtml(emp.fullName) + (emp.team ? ' - ' + escapeHtml(emp.team) : '') + '</div>';
        html += '<div class="employee-option-sso">SSO: ' + emp.sso + '</div>';
        html += '</div></div>';
      });

      // Always show option to add as custom name
      if (query.length > 0) {
        html += '<div class="employee-option" onclick="addCustomEmployee(\'' + escapeHtml(query) + '\')">';
        html += '<div class="ge-logo"><img src="' + GE_LOGO_URL + '"></div>';
        html += '<div class="employee-option-info">';
        html += '<div class="employee-option-name employee-option-custom">Add "' + escapeHtml(query) + '" (not in system)</div>';
        html += '</div></div>';
      }

      dropdown.innerHTML = html;
      dropdown.style.display = html ? 'block' : 'none';
    }

    function selectEmployee(sso, name, picture) {
      addEmployee(sso, name, picture, false);
      document.getElementById('employeeSearch').value = '';
      document.getElementById('employeeDropdown').style.display = 'none';
    }

    function addCustomEmployee(name) {
      addEmployee(null, name, null, true);
      document.getElementById('employeeSearch').value = '';
      document.getElementById('employeeDropdown').style.display = 'none';
    }

    function addEmployee(sso, name, picture, isCustom) {
      // Check for duplicates
      var isDuplicate = selectedEmployees.some(function(s) {
        if (sso && s.sso === sso) return true;
        if (isCustom && s.isCustom && s.name === name) return true;
        return false;
      });
      if (isDuplicate) return;

      selectedEmployees.push({ sso: sso, name: name, picture: picture, isCustom: isCustom });
      updateSelectedDisplay();
      updateHiddenFields();
    }

    function removeEmployee(index) {
      selectedEmployees.splice(index, 1);
      updateSelectedDisplay();
      updateHiddenFields();
    }

    function updateSelectedDisplay() {
      var container = document.getElementById('selectedEmployees');
      var html = '';

      selectedEmployees.forEach(function(emp, index) {
        var photoHtml;
        if (emp.picture) {
          photoHtml = '<img src="' + EMPLOYEE_PHOTO_BASE + emp.picture + '" onerror="this.parentNode.innerHTML=\'<div class=ge-logo-small><img src=' + GE_LOGO_URL + '></div>\'">';
        } else {
          photoHtml = '<div class="ge-logo-small"><img src="' + GE_LOGO_URL + '"></div>';
        }

        html += '<div class="selected-employee">';
        html += photoHtml;
        html += '<span class="selected-employee-name">' + escapeHtml(emp.name);
        if (emp.isCustom) html += ' <small>(custom)</small>';
        html += '</span>';
        html += '<span class="selected-employee-remove" onclick="removeEmployee(' + index + ')">x</span>';
        html += '</div>';
      });

      container.innerHTML = html;
    }

    function updateHiddenFields() {
      var values = [];

      selectedEmployees.forEach(function(emp) {
        if (emp.sso) {
          // System employee - use SSO
          values.push(emp.sso);
        } else if (emp.isCustom) {
          // Custom name - use NAME: prefix
          values.push('NAME:' + emp.name);
        }
      });

      document.getElementById('employeesso').value = values.join(',');
    }

    function escapeHtml(text) {
      var div = document.createElement('div');
      div.textContent = text;
      return div.innerHTML;
    }
  </script>

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