{{>header}}
<style>
  .is-invalid {
    border: 2px solid red;
  }

  .error-highlight {
    color: #bf2121;
    font-weight: bold;
    margin-top: 8px;
  }
</style>
<title>Vendor</title>
<section class="content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-12">
        <div class="card card-primary card-outline mt-3">
          <div class="card-header" style="background-color: white; color:#4B0F77;">
            <h4> <b>Add Community</b></h4>
          </div>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <div class="card">
          <div class="card-body">
            <div class="alert-success">{{success}}</div>
            <div class="alert-danger">{{error}}</div>
            <div id="privacy-policy-three" class="privacy-policy">
              <form method="post" action="/admin/v1/addvendor" id="addVendorForm" enctype="multipart/form-data">
                <div class="row">
                  <div class="col-md-4">
                    <div class="form-group">
                      <label class="col-form-label">Community Name <span class="text-danger">*</span></label>
                      <input type="text" class="form-control" id="name1" name="storeName" minlength="3" maxlength="50"
                        placeholder="Store Name" required pattern="^[A-Za-z ]{3,50}$"
                        title="Name must be 3–50 letters long, only alphabets and spaces (no numbers or special characters), and cannot start or end with a space."
                        oninput="this.value = this.value.replace(/^\s+/, '')">
                      {{!-- <small id="nameError" class="text-danger" style="display: none;">
                        Name should start with a letter and only contain letters/spaces (3–30 characters).
                      </small> --}}
                    </div>
                    <p id="nameP" style="color: red !important;"></p>
                  </div>
                  <div class="col-md-4">
                    <div class="form-group">
                      <label class="col-form-label">Vendor Name <span class="text-danger">*</span></label>
                      <input type="text" class="form-control" id="name" name="vendorName" minlength="3" maxlength="50"
                        placeholder="Vendor Name" required pattern="^[A-Za-z ]{3,50}$"
                        title="Name must be 3–50 letters long, only alphabets and spaces (no numbers or special characters), and cannot start or end with a space."
                        oninput="this.value = this.value.replace(/^\s+/, '')">
                    </div>
                    <p id="nameP" style="color: red !important;"></p>
                  </div>
                  <div class="col-md-4">
                    <div class="form-group">
                      <label for="update-email" class="col-form-label">Email<span class="text-danger">*</span></label>
                      <input type="text" class="form-control" name="email" id="update-email" placeholder="Email"
                        required maxlength="50" oninput="validateEmail(this)"
                        onblur="this.value = this.value.trim();" />
                      <small id="update-emailError" style="color: red; display: none;">
                        Please enter a valid email address (e.g., example@domain.com).
                      </small>
                    </div>
                  </div>

                </div>
                <div class="row">
                  <div class="col-md-4">
                    <div class="form-group">
                      <label class="col-form-label">Mobile Number <span class="text-danger">*</span></label>
                      <input type="text" class="form-control" id="mobile" name="phone" placeholder="Enter mobile number"
                        required pattern="^[6-9]\d{9}$"
                        title="Phone number must be exactly 10 digits and start with 6, 7, 8, or 9." maxlength="10"
                        minlength="10" oninput="this.value = this.value.replace(/[^0-9]/g, '')">
                      {{!-- <p id="error-message" class="text-danger d-none">Invalid Mobile Number</p>
                      <span id="phone-error2" class="text-danger d-none">Phone number required.</span> --}}
                    </div>

                  </div>
                  <div class="col-md-4">
                    <div class="form-group">
                      <label for="tax" class="col-form-label">Password <span class="text-danger">*</span></label>
                      <div class="input-group">
                        <input type="password" class="form-control" name="password" id="password"
                          placeholder="Enter password" required
                          pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#.])[A-Za-z\d@$!%*?&#.]{8,}$"
                          title="Password must be at least 8 characters, include uppercase, lowercase, number, and special character.">
                        <button type="button" class="btn btn-outline-secondary" style="background-color: aliceblue;"
                          onclick="togglePasswordVisibility('password', this)">
                          <i class="fas fa-eye"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="form-group">
                      <label for="" class="col-form-label">Confirm Password <span class="text-danger">*</span></label>
                      <div class="input-group">
                        <input type="password" class="form-control" name="confirmPassword"
                          placeholder="Confirm Password here" required id="confirmPassword">
                        <button type="button" class="btn btn-outline-secondary" style="background-color: white;"
                          onclick="togglePasswordVisibility('confirmPassword', this)">
                          <i class="fas fa-eye"></i>
                        </button>
                      </div>
                      <span id="passwordError" style="color: red; display: none;">Passwords don't match!</span>
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-4">
                    <div class="form-group">
                      <label class="col-form-label">Profile Picture <span class="text-danger">*</span></label>
                      <input type="file" class="form-control" accept="image/*" id="picture" name="picture" required>
                    </div>
                  </div>
                  <div class="col-md-4">
                    {{!-- <div class="form-group">
                      <label class="col-form-label">Select City <span class="text-danger">*</span></label>
                      <select name="cityId" class="selectpicker form-control" data-live-search="true" required>
                        <option value="" disabled selected hidden> Select City</option>
                        <!-- Important for placeholder -->
                        {{#each allCities}}
                        <option value="{{this._id}}">{{this.cityName}}</option>
                        {{/each}}
                      </select>
                    </div> --}}
                    <div id="address-field">
                  <label for="storeAddress" class="col-form-label">Store Address</label>
                  <input type="text" class="form-control" name="storeAddress" id="storeAddress" minlength="3"
                    maxlength="500" placeholder="Enter Store Address">
                  <div id="addressError" class="error-highlight mt-1" style="display: none;">
                    Please enter an address when a category is selected.
                  </div><br>
                  </div>
                  </div>
                  {{!-- <div class="col-md-4">
                    <div class="form-group">
                      <label class="col-form-label">Store Type<span class="text-danger">*</span></label>
                      <select name="categories" class="selectpicker form-control" data-live-search="true" required>
                        <option value="" disabled selected hidden> Select Store Type</option>
                        <!-- Important for placeholder -->
                        <option value="grocery">Grocery</option>
                        <option value="ecommerce">Ecommerce</option>
                        <option value="food">Food</option>
                      </select>
                    </div>
                    <div id="categoryError" class="error-highlight" style="display: none;">
                      Please select at least one category.
                    </div>
                  </div> --}}
                </div>
                <div class="row">
                  {{!-- <div class="col-md-4">
                    <div class="form-group">
                      <label class="col-form-label">Store Open Time:<span class="text-danger">*</span></label><br>
                      <input
                        type="time"
                        id="event-time1"
                        name="storeOpenTime"
                        style="border: 1px solid #ccc; border-radius: 6px; padding: 6px 10px; width: 50%; font-size: 18px;"
                        required>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="form-group">
                      <label class="col-form-label">Store Close Time:<span class="text-danger">*</span></label><br>
                      <input type="time" id="event-time" name="storeCloseTime"
                        style="border: 1px solid #ccc; border-radius: 6px; padding: 6px 10px; width: 50%; font-size: 18px;"
                        required>
                    </div>
                  </div> --}}
                  <div class="col-md-4">
                    
                </div>
            </div>
           

            <div class="row">
              <!-- Address Input -->
              <div class="col-md-6">
                

                  <!-- Latitude & Longitude fields -->
                  {{!-- <div class="mt-2">
                    <label for="latitude" class="form-label">Latitude</label>
                    <input type="text" class="form-control" name="latitude" id="latitude" readonly>

                    <label for="longitude" class="form-label mt-2">Longitude</label>
                    <input type="text" class="form-control" name="longitude" id="longitude" readonly>
                  </div>
                </div>
              </div>

              <!-- Map -->
              <div class="col-md-6">
                <label class="form-label">Select Location</label>
                <div id="map" style="height: 300px; width: 100%; border:1px solid #ccc; border-radius:10px;"></div>
              </div>
            </div><br> --}}

            <div class="form-group d-flex justify-content-center">
              <button class="btn btn-lg btn-primary" id="addButton" style="color: black;" type="submit">Submit</button>
            </div>

            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
  </div>
</section>
{{>footer}}
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />

<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>

{{!-- <script>
  let map, marker;

  // Initialize map
  document.addEventListener("DOMContentLoaded", () => {
    // Default center (India)
    const defaultLocation = [20.5937, 78.9629];

    map = L.map('map').setView(defaultLocation, 5);

    // Add OpenStreetMap tiles
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    // Click event
    map.on("click", function (e) {
      const lat = e.latlng.lat.toFixed(6);
      const lng = e.latlng.lng.toFixed(6);

      // Place or move marker
      if (marker) {
        marker.setLatLng(e.latlng);
      } else {
        marker = L.marker(e.latlng).addTo(map);
      }

      // Fill lat/lng fields
      document.getElementById("latitude").value = lat;
      document.getElementById("longitude").value = lng;
    });
  });
</script> --}}
<script>
  const pictureInput = document.getElementById('picture');

  //image validation
  function fileValidation(element) {
    element.addEventListener("change", function () {
      const file = this.files[0];
      if (file) {
        const validTypes = ["image/jpeg", "image/png", "image/webp", "image/jpg"];

        if (!validTypes.includes(file.type)) {
          alert("Only image format is acceptable.");
          this.value = ""; // Clear the file input
        } else {
          console.log("Valid image selected:", file.name);
        }
      }
    });
  }

  fileValidation(pictureInput)
</script>

<script>
  function toggleAddressField() {
    const checkboxes = document.querySelectorAll('select[name="categories"]');
    const addressField = document.getElementById('address-field');
    const anyChecked = Array.from(checkboxes).some(cb => cb.value);

    addressField.style.display = anyChecked ? 'block' : 'none';
    if (!anyChecked) {
      document.getElementById('storeAddress').value = '';
    }
  }

  function validateCategoriesAndAddresses() {
    const checkboxes = document.querySelectorAll('select[name="categories"]');
    const anyChecked = Array.from(checkboxes).some(cb => cb.value);

    const categoryError = document.getElementById('categoryError');
    const addressError = document.getElementById('addressError');
    const addressValue = document.getElementById('storeAddress').value.trim();

    // Category validation
    categoryError.style.display = anyChecked ? 'none' : 'block';

    // Address validation
    if (anyChecked && !addressValue) {
      addressError.style.display = 'block';
      return false;
    } else {
      addressError.style.display = 'none';
    }

    return anyChecked && addressValue.length > 0;
  }

  // Hook into form submit
  document.getElementById('addVendorForm').addEventListener('submit', function (e) {
    if (!validateCategoriesAndAddresses()) {
      e.preventDefault();
    }
  });

  // Checkbox & input events
  document.querySelector('select[name="categories"]').addEventListener('change', (e) => {
    toggleAddressField();
    validateCategoriesAndAddresses();
  });


  document.getElementById('storeAddress').addEventListener('input', validateCategoriesAndAddresses);
</script>
{{!-- image validation --}}
<script>
  // validation to check for image format
  function fileValidation(element) {
    element.addEventListener("change", function () {
      const file = this.files[0];
      if (file) {
        const validTypes = ["image/jpeg", "image/png", "image/webp", "image/jpg"];

        if (!validTypes.includes(file.type)) {
          alert("Only image format is acceptable.");
          this.value = ""; // Clear the file input
        }
      }
    });
  }
  const imageInputs = document.querySelectorAll('.imageInput')
  imageInputs.forEach(input => {
    fileValidation(input)
  })
</script>

{{!-- Name Validation --}}

<script>
  document.getElementById('name').addEventListener('input', function () {
    const nameInput = this;
    const errorMsg = document.getElementById('nameError');
    const namePattern = /^[a-zA-Z\s]{3,30}$/;

    if (!namePattern.test(nameInput.value)) {
      errorMsg.style.display = 'block';
      nameInput.classList.add('is-invalid');
    } else {
      errorMsg.style.display = 'none';
      nameInput.classList.remove('is-invalid');
    }
  });
</script>

{{!-- Email Validation --}}

<script>
  function validateEmail(input) {
    input.value = input.value.toLowerCase();
    /*
            const allowedDomains = [
                '.com', '.net', '.org', '.edu', '.gov', '.mil', '.int', '.co', '.io',
                '.us', '.uk', '.ca', '.in', '.au', '.de', '.jp', '.cn', '.ru', '.br',
                '.tech', '.biz', '.info', '.xyz', '.online', '.store', '.ai', '.app', '.dev',
                '.health', '.law', '.news', '.music', '.bank', '.design', '.photography',
                '.media', '.finance', '.marketing', '.consulting', '.solutions', '.digital',
                '.agency', '.ventures', '.guru', '.expert', '.club'
            ];
    */
    const email = input.value.trim();
    const errorElement = input.parentElement.querySelector("small");


    const emailRegex = /^[a-zA-Z0-9](?!.*[._%+-]{2})[a-zA-Z0-9._%+-]*[a-zA-Z0-9]@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/;
    const isFormatValid = emailRegex.test(email);

    // Extract domain extension
    const domain = email.substring(email.lastIndexOf('.')).toLowerCase();
    //const isDomainValid = allowedDomains.includes(domain);

    if (!isFormatValid) {
      errorElement.style.display = 'block';
      isValidEmail = false;
    } else {
      errorElement.style.display = 'none';
      isValidEmail = true;
    }

    checkFormValidity();
  }

</script>

{{!-- PassWord Validation --}}
<script>
  $(document).ready(function () {
    // When the modal is hidden, clear the form fields
    $('#addModal').on('hidden.bs.modal', function () {
      // Reset the form data
      $('#addAdmin')[0].reset();
      $('#nameError').hide();
      $('#emailError').hide();
      $('#error-message').hide();
    });
  });

  let isValidEmail = false;
  let isPasswordMatched = false;

  function checkFormValidity() {
    const addButton = document.getElementById("addButton");
    if (isValidEmail && isPasswordMatched) {
      addButton.disabled = false;
    } else {
      addButton.disabled = true;
    }
  }


  document.getElementById("password").addEventListener("input", function () {
    //checkFormValidity();
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirmPassword');
    const passwordError = document.getElementById('passwordError');

    function validatePasswords() {
      const password = passwordInput.value;
      const confirmPassword = confirmPasswordInput.value;

      if (password !== confirmPassword || password === "" || confirmPassword === "") {
        passwordError.style.display = "block";
        isPasswordMatched = false;
      } else {
        passwordError.style.display = "none";
        isPasswordMatched = true;
      }

      checkFormValidity();
    }

    passwordInput.addEventListener('input', validatePasswords);
    confirmPasswordInput.addEventListener('input', validatePasswords);

    // Prevent form submission if password doesn't match
    document.querySelector('form').addEventListener('submit', function (event) {
      if (!isPasswordMatched) {
        event.preventDefault();
      }
    });
  });
</script>
{{!-- toggle password --}}
<script>
  function togglePasswordVisibility(inputId, toggleButton) {
    const input = document.getElementById(inputId);
    const icon = toggleButton.querySelector("i");

    if (input.type === "password") {
      input.type = "text";
      icon.classList.remove("fa-eye");
      icon.classList.add("fa-eye-slash");
    } else {
      input.type = "password";
      icon.classList.remove("fa-eye-slash");
      icon.classList.add("fa-eye");
    }
  }
</script>

<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"
  integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"
  integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script>
{{!-- switch --}}
<script>
  $(document).ready(function () {
    $("input[data-bootstrap-switch]").each(function () {
      $(this).bootstrapSwitch('state', $(this).prop('checked'));
    });
    $('.status').bootstrapSwitch('state');
  });
</script>
</body>

</html>