{{>header}}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@17.0.13/build/css/intlTelInput.min.css">
<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@17.0.13/build/js/intlTelInput.min.js"></script>

<style>
  #phone {
    padding-left: 50px;
    width: 470px;
  }

  .no-spinner::-webkit-inner-spin-button,
  .no-spinner::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }

  .no-spinner {
    -moz-appearance: textfield;
  }
</style>

<title>Communities</title>
<div class="row p-2" style="margin: 0px !important;">
  <div class="col-md-12">
    <div class="card mt-2">
      {{!-- {{!-- <div class="alert-success">{{success}}</div>
      <div class="alert-danger">{{error}}</div> --}}
      <div class="card-header" style="background-color:white; color:#4B0F77;">
        <h4><b>Communities</b></h4>
      </div>
      <div class="card-body p-2">
        <div id="example1_wrapper">
          <div class="row">
            <div class="col-sm-12">
              <div class="col-sm-12">
                            <ol class="float-sm-right">
                                <a href="/admin/v1/renderaddvendor"
                                    style="background-color: black; color:white; border:none; border-radius:5px; width: 180px; height: 40px; display: flex; align-items: center; justify-content: center; text-decoration: none;">
                                    <i class="fa-solid fa-plus"></i> Add Community
                                </a>
                            </ol>
                        </div>
            </div>
            <div class="col-sm-12 table-responsive">
              <table id="example5" class="table table-bordered table-striped" aria-describedby="example1_info">
                <thead>
                  <tr>
                    <th>S.No</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Mobile</th>
                    <th>Status</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  {{#each vendors}}
                  <tr>
                    <td>{{inc @index}}</td>
                    <td>{{this.communityName}}</td>
                    <td>{{this.email}}</td>
                    <td>{{this.phone}}</td>
                    <td>{{this.status}}</td>
                    <td>
                      <a href="/admin/v1/singlevendor/{{this._id}}" class="btn btn-md btn-info m-1">
                        <i class="fa-solid fa-eye"></i>
                      </a>
                      {{!-- <a href="javascript:void(0);" data-bs-toggle="modal" data-bs-target="#updateModal"
                        class="btn btn-md btn-warning m-1" data-id="{{this._id}}" data-name="{{this.name}}"
                        data-email="{{this.email}}" data-phone="{{this.phone}}" data-status="{{this.status}}">
                        <i class="fa-solid fa-edit"></i>
                      </a> --}}
                      {{!-- <a href="javascript:void(0);" data-bs-toggle="modal" data-id="{{this._id}}"
                        data-bs-target="#deleteModal" class="btn btn-md btn-danger m-1">
                        <i class="fa-solid fa-trash"></i>
                      </a> --}}
                    </td>
                  </tr>
                  {{/each}}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      
      <!-- Modal Header -->
      <div class="modal-header">
        <h5 class="modal-title fw-bold fs-2 text-dark" id="addModalLabel" style="font-size: 1.25rem; font-weight: 500;"><b>Add Vendor</b></h5>
      </div>

      <!-- Modal Form -->
      <form id="addAdmin" action="/admin/v1/addvendor" method="POST" enctype="multipart/form-data" onsubmit="changeButtonState()">
        <div class="modal-body">

          <!-- Store Name -->
          <div class="mb-3">
            <label for="name" class="form-label fw-semibold fs-5" style="font-size: 1.25rem; font-weight: 500; color: #0e0b0b"><b>Shop Name</b></label>
            <input type="text" class="form-control form-control-lg" id="name" name="name" placeholder="Enter shop name"
              required maxlength="30" minlength="3" pattern="^[a-zA-Z\s]+$">
            <small id="nameError" class="form-text text-danger d-none">
              Name should only contain letters and spaces (3–30 characters).
            </small>
          </div>

          <!-- Store Type -->
          <div class="mb-4">
            <label class="form-label fw-semibold fs-4"  style="font-size: 1.25rem; font-weight: 500; color: #0e0b0b"><b>Store Type</b></label>

            <div class="form-check form-check-lg">
              <input class="form-check-input" type="checkbox" name="categories" value="Grocery" id="categoryGrocery" style="transform: scale(1.4); margin-right: 10px;">
              <label class="form-check-label fs-5 fw-medium text-dark" for="categoryGrocery"  style="font-size: 1.25rem; font-weight: 500; color: #161414;">Grocery</label>
            </div>

            <div class="form-check form-check-lg">
              <input class="form-check-input" type="checkbox" name="categories" value="E-commerce" id="categoryEcom" style="transform: scale(1.4); margin-right: 10px;">
              <label class="form-check-label fs-5 fw-medium text-dark" for="categoryEcom"  style="font-size: 1.25rem; font-weight: 500; color: #222;">E-commerce</label>
            </div>

            <div class="form-check form-check-lg">
              <input class="form-check-input" type="checkbox" name="categories" value="Food" id="categoryFood" style="transform: scale(1.4); margin-right: 10px;">
              <label class="form-check-label fs-5 fw-medium text-dark" for="categoryFood"  style="font-size: 1.25rem; font-weight: 500; color: #222;">Food</label>
            </div>
          </div>


          <!-- Address -->
          <div class="mb-3">
            <label for="address" class="form-label fw-semibold fs-5" style="font-size: 1.25rem; font-weight: 500; color: #0e0b0b"><b>Address</b></label>
            <textarea name="address" class="form-control" id="address" rows="2"
              placeholder="Enter address" minlength="5" maxlength="100" required></textarea>
            <p id="addressP" class="text-danger"></p>
          </div>

          <!-- Profile Picture -->
          <div class="mb-3">
            <label for="picture" class="form-label fw-semibold fs-5" style="font-size: 1.25rem; font-weight: 500; color: #0e0b0b"><b>Profile Picture</b></label>
            <input type="file" class="form-control" accept="image/*" id="picture" name="picture" required>
          </div>

          <!-- Email -->
          <div class="mb-3">
            <label for="email" class="form-label fw-semibold fs-5" style="font-size: 1.25rem; font-weight: 500; color: #0e0b0b"><b>Email Address</b></label>
            <input type="email" class="form-control form-control-lg" name="email" id="email"
              placeholder="Enter email" required maxlength="50" oninput="validateEmail(this)">
            <small id="emailError" class="form-text text-danger d-none">Please enter a valid email address.</small>
          </div>

          <!-- Mobile Number -->
          <div class="mb-3">
            <label for="mobile" class="form-label fw-semibold fs-5" style="font-size: 1.25rem; font-weight: 500; color: #0e0b0b"><b>Mobile Number</b></label>
            <input type="number" class="form-control form-control-lg no-spinner" id="mobile"
              name="phone" placeholder="Enter mobile number" required>
            <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>

          <!-- Password -->
          <div class="mb-3">
            <label for="password" class="form-label fw-semibold fs-5" style="font-size: 1.25rem; font-weight: 500; color: #0e0b0b"><b>Password</b></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)(?=.*[@$!%*?&#])[\w@$!%*?&#]{8,14}$"
                title="Password must be 8–14 characters with at least one uppercase letter, one lowercase letter, one number, and one special character.">
              <button type="button" class="btn btn-outline-secondary"
                onclick="togglePasswordVisibility('password', this)">
                <i class="fas fa-eye"></i>
              </button>
            </div>
          </div>

          <!-- Confirm Password -->
          <div class="mb-3">
            <label for="confirmPassword" class="form-label fw-semibold fs-5" style="font-size: 1.25rem; font-weight: 500; color: #0e0b0b"><b>Confirm Password</b></label>
            <div class="input-group">
              <input type="password" class="form-control" name="confirmPassword" id="confirmPassword"
                placeholder="Confirm password" required>
              <button type="button" class="btn btn-outline-secondary"
                onclick="togglePasswordVisibility('confirmPassword', this)">
                <i class="fas fa-eye"></i>
              </button>
            </div>
            <span id="passwordError" class="text-danger d-none">Passwords don't match!</span>
          </div>

        </div>

        <!-- Modal Footer -->
        <div class="modal-footer">
          <button type="submit" class="btn btn-success" id="addButton">Add Vendor</button>
        </div>

      </form>
    </div>
  </div>
</div>


<script>
  document.getElementById("email").addEventListener("input", function() {
    this.value = this.value.toLowerCase();
});
</script>

<script>

  function changeButtonState() {
    var submitButton = document.getElementById('addButton');
    submitButton.textContent = 'Adding...';
    submitButton.disabled = true;
  }
</script>

<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 isValidMobile = false;
    let isPasswordMatched = false;

     function checkFormValidity() {
    const addButton = document.getElementById("addButton");
    if (isValidEmail && isValidMobile && isPasswordMatched) {
      addButton.disabled = false;
    } else {
      addButton.disabled = true;
    }
  }

    function validateEmail(input) {

    input.value = input.value.toLowerCase();


    const emailRegex = /^[a-zA-Z0-9]+[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]+\.(com|in|org|jnu|ac)$/i;
    const errorElement = document.getElementById('emailError');


    if (!emailRegex.test(input.value)) {
      errorElement.style.display = 'block';
      isValidEmail = false;
    } else {
      errorElement.style.display = 'none';
      isValidEmail = true;
    }
    checkFormValidity();
  }

  function isValidMobileNumber(mobile) {
    const mobileRegex = /^[6-9]\d{9}$/; // Starts with 6-9, followed by 9 digits
    return mobileRegex.test(mobile);
  }

  document.getElementById("mobile").addEventListener("input", function () {
    const mobile = this.value.trim();
    const errorMsg = document.getElementById("error-message");

    if (isValidMobileNumber(mobile)) {
      errorMsg.style.display = "none"; // Hide error if valid
      isValidMobile = true;
    } else {
      errorMsg.style.display = "block"; // Show error if invalid
      errorMsg.textContent = "Enter a valid 10-digit mobile number.";
      isValidMobile = false;
    }
    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>


<!-- Update Modal -->
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h3 style="color: black; font-weight: bold;">Update Admin</h3>
      </div>
      <form id="updateForm" action="/admin/update-admin/{{this._id}}" method="post" enctype="multipart/form-data">
        <div class="modal-body">
          <label for="update-name">Name</label>
          <input type="text" class="form-control" name="name" id="update-name" placeholder="Name" required
            maxlength="30" minlength="3" pattern="^[a-zA-Z\s]{3,30}$" />
          <small id="nameError" class="text-danger" style="display: none;">
            Name should only contain letters and spaces (3-30 characters).
          </small>
        </div>
        <div class="modal-body">
          <label for="update-email">Email</label>
          <input type="text" class="form-control" name="email" id="update-email" placeholder="Email" required
            maxlength="50" oninput="validateUpdateEmail(this)" />
          <small id="update-emailError" style="color: red; display: none;">
            Please enter a valid email address (e.g., example@domain.com).
          </small>
        </div>
        <div class="modal-body">
          <label for="phone">Mobile</label>
          <input type="number" id="update-phone" class="form-control no-spinner" name="phone"
            placeholder="Mobile Number" value="{{User.phone}}" required>
            <p id="update-error-message" style="color: red; display: none;">Invalid Mobile Number</p>
          <span id="phone-error2" class="text-danger" style="display: none;">Phone number required.</span>
        </div>
        <div class="modal-body">
          <label for="status" class="col-sm-3 col-form-label text-end">Status</label>
          <select name="status" id="status" class="form-control statuss">
            <option value="Active">Active</option>
            <option value="Inactive">Inactive</option>
          </select>
        </div>
        <div class="modal-footer">
          <button type="submit" id="updateButton" class="btn btn-success">Update</button>
        </div>
      </form>
    </div>
  </div>
</div>
<script>
    $(document).ready(function () {
        // When the modal is hidden, clear the form fields
        $('#updateModal').on('hidden.bs.modal', function () {
            // Reset the form data
            $('#updateForm')[0].reset();
            $('#update-emailError').hide();
            $('#update-error-message').hide();
            document.getElementById('updateButton').disabled=false;
        });
    });
</script>
<script>
  document.getElementById("update-email").addEventListener("input", function() {
    this.value = this.value.toLowerCase();
});
</script>

<script>
  document.getElementById("update-name").addEventListener("input", function () {
    const nameInput = this.value;
    const regex = /^[a-zA-Z\s]*$/;
    const errorMessage = document.getElementById("nameError");
    if (!regex.test(nameInput)) {
      this.value = nameInput.replace(/[^a-zA-Z\s]/g, "");
      errorMessage.style.display = "block";
    } else {
      errorMessage.style.display = "none";
    }
  });
   document.getElementById("updateModal").addEventListener("submit", function () {
      let nameField = document.getElementById("update-name");
      nameField.value = nameField.value.trim(); // Trim spaces before storing
    });

  document.getElementById("name").addEventListener("input", function () {
    const nameInput = this.value;
    const regex = /^[a-zA-Z\s]*$/;
    const errorMessage = document.getElementById("nameError");
    if (!regex.test(nameInput)) {
      this.value = nameInput.replace(/[^a-zA-Z\s]/g, "");
      errorMessage.style.display = "block";
    } else {
      errorMessage.style.display = "none";
    }
  });
   document.getElementById("addModal").addEventListener("submit", function () {
      let nameField = document.getElementById("name");
      nameField.value = nameField.value.trim(); // Trim spaces before storing
    });
</script>




<!-- Delete Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 style="color: black; font-weight: 480;">Are you sure you want to delete this?</h4>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
        <a href="/admin/deletevendor/{{this._id}}" type="button" class="btn btn-danger">Yes</a>
      </div>
    </div>
  </div>
</div>

</body>

<script>
  const nameInput = document.getElementById('name');
  const errorMessage = document.getElementById('nameError');

  nameInput.addEventListener('input', function () {
    const namePattern = /^[a-zA-Z\s]{3,30}$/;
    if (!namePattern.test(nameInput.value)) {
      errorMessage.style.display = 'block'; // Show the error message
    } else {
      errorMessage.style.display = 'none'; // Hide the error message
    }
  });

  document.getElementById("addModal").addEventListener("submit", function () {
      let nameField = document.getElementById("name");
      nameField.value = nameField.value.trim(); // Trim spaces before storing
    });
</script>

<script>
  const form = document.getElementById('updateForm')
  //const initialFormData = new FormData(form);
  let isValidUpdateEmail;
  let isValidUpdateMobile;
  function validateUpdateEmail(input) {
    const emailPattern =/^[a-zA-Z0-9]+[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]+\.(com|in|org|jnu|ac)$/i;
    const emailError = document.getElementById("update-emailError");

    if (!emailPattern.test(input.value)) {
      emailError.style.display = "block"; // Show error message
      emailError.textContent = "Please enter a valid email.";
      isValidUpdateEmail = false;
     //document.getElementById("updateButton").disabled = true;
      //input.setCustomValidity("Invalid email");
    } else {
      emailError.style.display = "none"; // Hide error message
      isValidUpdateEmail = true;
      //document.getElementById("updateButton").disabled = false;
      //input.setCustomValidity("");
    }
  }
   document.getElementById("update-phone").addEventListener("input", function () {
    const mobile = this.value.trim();
    const errorMsg = document.getElementById("update-error-message");

    if (isValidMobileNumber(mobile)) {
      errorMsg.style.display = "none"; // Hide error if valid
      isValidUpdateMobile = true;
      //document.getElementById("updateButton").disabled = false;
    } else {
      errorMsg.style.display = "block"; // Show error if invalid
      errorMsg.textContent = "Enter a valid 10-digit mobile number.";
      isValidUpdateMobile = false;
      //document.getElementById("updateButton").disabled = true;
    }
  });

  form.addEventListener("input", () => {
    if(/^[a-zA-Z0-9]+[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]+\.(com|in|org|jnu|ac)$/i.test(form.elements.email.value) && isValidMobileNumber(form.elements.phone.value)){
        isValidUpdateEmail = true;
        isValidUpdateMobile = true;
    }
    /*const currentFormData = new FormData(form);
    for (let [key, value] of currentFormData.entries()) {
        if (value !== initialFormData.get(key)) {
            isChanged = true;
            //document.getElementById('updateButton').disabled = false;
            break;
        }
    }*/
    if(isValidUpdateEmail && isValidUpdateMobile){
        document.getElementById('updateButton').disabled = false;
    }
    else{
        document.getElementById('updateButton').disabled = true;
    };
  })
</script>

<script>

  var phoneInput = document.querySelector("#phone");
  var iti = window.intlTelInput(phoneInput, {
    initialCountry: "auto",
    separateDialCode: true,
    preferredCountries: ['us', 'gb', 'ca'],
  });

  phoneInput.addEventListener("countrychange", function () {
    var selectedCountry = iti.getSelectedCountryData();
    var combinedDetails = {
      dialCode: selectedCountry.dialCode,
      countryCode: selectedCountry.iso2,
      countryName: selectedCountry.name,
    };

    console.log(combinedDetails);
  });



  input.addEventListener("input", function (e) {
    this.value = this.value.replace(/[^0-9]/g, '');
    if (this.value.length > 10) {
      this.value = this.value.slice(0, 10);
    }
  });
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">

<script>
  function togglePasswordVisibility(fieldId, button) {
    const field = document.getElementById(fieldId);
    const icon = button.querySelector('i');

    if (field.type === 'password') {
      field.type = 'text';
      icon.classList.remove('fa-eye');
      icon.classList.add('fa-eye-slash');
    } else {
      field.type = 'password';
      icon.classList.remove('fa-eye-slash');
      icon.classList.add('fa-eye');
    }
  }
</script>

<script>
  // Validate Name
  function validateName(input) {
    const namePattern = /^[a-zA-Z\s]{3,30}$/;
    const nameError = document.getElementById("nameError");
    if (!namePattern.test(input.value)) {
      nameError.style.display = "block"; // Show error message
      input.style.borderColor = "red"; // Highlight input border
      input.setCustomValidity("Invalid name");
    } else {
      nameError.style.display = "none"; // Hide error message
      input.style.borderColor = ""; // Reset input border
      input.setCustomValidity("");
    }
  }

  // Validate Email
  function validateEmail(input) {
    const emailPattern = /^[a-zA-Z0-9]+[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]+\.(com|in|org|jnu|ac)$/i;
    const emailError = document.getElementById("emailError");
    if (!emailPattern.test(input.value)) {
      emailError.style.display = "block"; // Show error message
      input.style.borderColor = "red"; // Highlight input border
      input.setCustomValidity("Invalid email");
    } else {
      emailError.style.display = "none"; // Hide error message
      input.style.borderColor = ""; // Reset input border
      input.setCustomValidity("");
    }
  }


  // Validate Form Before Submitting
  function validateUpdateForm() {
    const nameInput = document.getElementById("update-name");
    const emailInput = document.getElementById("update-email");

    validateUpdateName(nameInput);
    validateUpdateEmail(emailInput);

    if (
      nameInput.checkValidity() &&
      emailInput.checkValidity() &&
    ) {
      return true; // Allow form submission
    }

    return false; // Prevent form submission
  }
</script>

<script>
  $(document).ready(function () {
    if (!$.fn.DataTable.isDataTable('#example2')) {
      $('#example2').addClass('table table-bordered table-striped').DataTable({
        "paging": true,
        "dom": 'Bfrtip',
        "buttons": [
          'copy', 'csv', 'excel', 'print', 'colvis'
        ]
      });
    }
  });
</script>

<script>
  $(document).ready(function () {
    // Initialize DataTable
    if (!$.fn.DataTable.isDataTable('#example2')) {
      $('#example2').addClass('table table-bordered table-striped').DataTable({
        "paging": true,
      });
    }

    // Update modal functionality
    $('#updateModal').on('show.bs.modal', function (event) {
      var button = $(event.relatedTarget);
      var modal = $(this);
      var userId = button.data('id');
      var name = button.data('name');
      var email = button.data('email');
      var phone = button.data('phone');
      var status = button.data('status');

      modal.find('form').attr('action', '/admin/update-admin/' + userId);
      modal.find('#update-name').val(name);
      modal.find('#update-email').val(email);
      modal.find('#update-phone').val(phone);
      $(".statuss").val(status);
    });

    // Delete modal functionality
    $('#deleteModal').on('show.bs.modal', function (event) {
      var button = $(event.relatedTarget);
      var userId = button.data('id');
      var modal = $(this);
      modal.find('a.btn-danger').attr('href', '/admin/deletevendor/' + userId);
    });
  });
</script>

{{>footer}}

</html>