<?php include 'header.php'; ?>

<style>
  .btn-primary-600,
  .btn-primary {
    border-radius: 10px;
    padding: 10px 20px;
    font-size: 16px;
    font-weight: 600;
  }

  .password-wrapper {
    position: relative;
  }

  .password-toggle {
    position: absolute;
    top: 50%;
    right: 14px;
    transform: translateY(-50%);
    cursor: pointer;
    font-size: 18px;
    color: #6c757d;
  }

  .password-toggle:hover {
    color: #4a63ff;
  }

  .role-dropdown {
    display: none;
    /* hidden by default */
    position: absolute;
    /* relative to parent */
    top: 100%;
    /* below input */
    left: 17px;
    width: 95%;
    max-height: 200px;
    /* set max height */
    overflow-y: auto;
    /* scroll if content exceeds max-height */
    background: #fff;
    border: 1px solid #ccc;
    z-index: 1000;
    list-style: none;
    padding: 0;
    margin: 0;
  }

  .role-dropdown li {
    padding: 8px 12px;
    cursor: pointer;
  }

  .role-dropdown li:hover {
    background-color: #f0f0f0;
  }

  .swal-small-title {
    font-size: 42px !important;
  }

  .swal-small-text {
    font-size: 16px !important;
  }

  .swal-small-btn {
    font-size: 14px !important;
    padding: 6px 12px !important;
  }
</style>

<div class="dashboard-main-body">
  <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
    <h6 class="fw-semibold mb-0">Add Alert</h6>
  </div>
  <div class="d-flex flex-wrap align-items-center justify-content-end gap-3 mb-3">
    <a type="button" href="alert.php" class="tooltip-button btn bg-primary-600 text-white border border-primary-600 radius-8 px-12 py-11 d-flex align-items-center" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-html="true" data-bs-custom-class="tooltip-primary" title="Listing">
      <iconify-icon icon="ic:baseline-arrow-back" class="icon text-xl line-height-1"></iconify-icon>
    </a>
  </div>

  <div class="row gy-4">
    <div class="col-md-12">
      <div class="card">
        <div class="card-body">
          <h6 class="mb-4 text-xl">Add Alert</h6> <br />
          <form id="modelform" action="" method="post">
            <div class="row gy-3">

              <!-- Alert Type -->
              <div class="col-sm-6">
                <label class="form-label">Alert Type <span class="text-danger">*</span></label>
                <select name="alert_type" class="form-select" required>
                  <option value="">Select Alert Type</option>
                  <option>Unauthorized Entry</option>
                  <option>Suspicious Activity</option>
                  <option>Fire Alarm</option>
                  <option>Theft</option>
                  <option>Other</option>
                </select>
              </div>

              <!-- Loaction -->
              <div class="col-sm-6">
                <label class="form-label">Location<span class="text-danger">*</span></label>
                <input type="text" name="tower" class="form-control" placeholder="Enter Location" required>
              </div>


              <!-- Incident Date -->
              <div class="col-sm-6">
                <label class="form-label">Incident Date & Time <span class="text-danger">*</span></label>
                <input type="datetime-local" name="incident_time" class="form-control" required>
              </div>

              <!-- Description -->
              <div class="col-sm-12">
                <label class="form-label">Description</label>
                <textarea name="description" class="form-control" rows="4" placeholder="Enter Alert Description"></textarea>
              </div>


            </div>
            <!-- Save Button -->
            <div class="form-group text-end mt-4">
              <button type="submit" class="btn-primary-600">
                <i class="bi bi-floppy"></i>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ============================
     Password Hide/Show Toggle
============================= -->
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const togglePassword = document.getElementById('togglePassword');
    const passwordInput = document.getElementById('password');

    if (togglePassword && passwordInput) {
      togglePassword.addEventListener('click', function() {
        const isPassword = passwordInput.type === 'password';
        passwordInput.type = isPassword ? 'text' : 'password';
        this.classList.toggle('bi-eye');
        this.classList.toggle('bi-eye-slash');
      });
    }
  });
</script>

<!-- ==================================
     Role Dropdown Search & Selection
=================================== -->
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const search = document.getElementById('search');
    const dropdown = document.getElementById('roleDropdown');
    const roleItems = dropdown ? dropdown.querySelectorAll('li') : [];

    function showDropdown() {
      if (dropdown) dropdown.style.display = 'block';
    }

    function hideDropdown() {
      if (dropdown) dropdown.style.display = 'none';
    }

    function showAllItems() {
      roleItems.forEach(item => item.style.display = 'block');
    }

    if (search && dropdown) {
      search.addEventListener('focus', () => {
        showAllItems();
        showDropdown();
      });
      search.addEventListener('click', () => {
        showAllItems();
        showDropdown();
      });
      search.addEventListener('input', function() {
        const value = search.value.toLowerCase().trim();
        let visibleCount = 0;
        roleItems.forEach(item => {
          if (item.textContent.toLowerCase().includes(value)) {
            item.style.display = 'block';
            visibleCount++;
          } else {
            item.style.display = 'none';
          }
        });
        dropdown.style.display = visibleCount ? 'block' : 'none';
      });

      roleItems.forEach(item => {
        item.addEventListener('click', function() {
          search.value = this.textContent;
          search.style.borderColor = '#28a745'; // mark valid
          hideDropdown();
        });
      });

      document.addEventListener('click', function(e) {
        if (!e.target.closest('#search') && !e.target.closest('#roleDropdown')) {
          hideDropdown();
        }
      });
    }
  });
</script>

<!-- ==================================
     Form Validation
=================================== -->
<script>
  document.addEventListener('DOMContentLoaded', function() {
    const search = document.getElementById('search');
    const dropdown = document.getElementById('roleDropdown');
    const roleItems = dropdown ? Array.from(dropdown.querySelectorAll('li')) : [];
    const validRoles = roleItems.map(li => li.textContent.trim()); // allowed roles

    // -------------------------
    // Helpers
    // -------------------------
    function showDropdown() {
      if (dropdown) dropdown.style.display = 'block';
    }

    function hideDropdown() {
      if (dropdown) dropdown.style.display = 'none';
    }

    function showAllItems() {
      roleItems.forEach(item => item.style.display = 'block');
    }

    function showError(input, message) {
      const existing = input.parentNode.querySelector('.error-message');
      if (existing) existing.remove();
      const div = document.createElement('div');
      div.className = 'error-message text-danger mt-1 small';
      div.textContent = message;
      input.parentNode.appendChild(div);
    }

    function clearError(input) {
      const existing = input.parentNode.querySelector('.error-message');
      if (existing) existing.remove();
    }

    function validateName() {
      const nameInput = document.querySelector('[name="name"]');
      if (!nameInput.value.trim()) {
        showError(nameInput, 'Name is required');
        return false;
      }
      return true;
    }

    function validateMobile() {
      const mobileInput = document.querySelector('[name="mobile"]');
      if (!/^\d{10}$/.test(mobileInput.value)) {
        showError(mobileInput, 'Enter valid 10-digit mobile');
        return false;
      }
      return true;
    }

    function validateEmail() {
      const emailInput = document.querySelector('[name="email"]');
      const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!re.test(emailInput.value)) {
        showError(emailInput, 'Enter valid email');
        return false;
      }
      return true;
    }

    function validatePassword() {
      const passwordInput = document.getElementById('password');
      if (!passwordInput.value || passwordInput.value.length < 6) {
        showError(passwordInput, 'Password min 6 characters');
        return false;
      }
      return true;
    }

    function validateRole() {
      const value = search.value.trim();
      if (!validRoles.includes(value)) {
        showError(search, 'Select a valid role');
        return false;
      }
      return true;
    }

    // -------------------------
    // Role Dropdown Behavior
    // -------------------------
    if (search && dropdown) {
      // open dropdown
      search.addEventListener('focus', () => {
        showAllItems();
        showDropdown();
      });
      search.addEventListener('click', () => {
        showAllItems();
        showDropdown();
      });

      // filter as user types
      search.addEventListener('input', function() {
        const value = search.value.toLowerCase().trim();
        let visibleCount = 0;
        roleItems.forEach(item => {
          if (item.textContent.toLowerCase().includes(value)) {
            item.style.display = 'block';
            visibleCount++;
          } else {
            item.style.display = 'none';
          }
        });
        dropdown.style.display = visibleCount ? 'block' : 'none';
        clearError(search);
      });

      // click to select
      roleItems.forEach(item => {
        item.addEventListener('click', function() {
          search.value = this.textContent.trim();
          search.style.borderColor = '#28a745';
          hideDropdown();
          clearError(search);
        });
      });

      // hide dropdown when clicking outside
      document.addEventListener('click', function(e) {
        if (!e.target.closest('#search') && !e.target.closest('#roleDropdown')) {
          hideDropdown();
        }
      });
    }

    // -------------------------
    // Form Submission
    // -------------------------
    const form = document.getElementById('modelform');

    // clear errors on input
    ['[name="name"]', '[name="mobile"]', '[name="email"]', '#password', '#search'].forEach(sel => {
      const el = document.querySelector(sel);
      if (el) el.addEventListener('input', e => clearError(e.target));
    });

    form.addEventListener('submit', function(e) {
      e.preventDefault();

      const isNameValid = validateName();
      const isMobileValid = validateMobile();
      const isEmailValid = validateEmail();
      const isPasswordValid = validatePassword();
      const isRoleValid = validateRole();

      if (isNameValid && isMobileValid && isEmailValid && isPasswordValid && isRoleValid) {
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          html: 'User added successfully',
          width: '450px',
          heightAuto: false,
          customClass: {
            popup: 'my-swal-popup',
            title: 'swal-small-title',
            htmlContainer: 'swal-small-text',
            confirmButton: 'swal-small-btn'
          },
          confirmButtonColor: '#4a63ff',
          timer: 2000,
          timerProgressBar: true
        }).then(() => form.submit());
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Missing Information',
          html: 'Please fill all fields correctly!',
          width: '450px',
          heightAuto: false,
          customClass: {
            popup: 'my-swal-popup',
            title: 'swal-small-title',
            htmlContainer: 'swal-small-text',
            confirmButton: 'swal-small-btn'
          },
          confirmButtonColor: '#dc3545'
        });
      }
    });
  });
</script>

<?php include 'footer.php'; ?>