<style>
  #categoryForm input{
    padding-left: 10px;
  }
.form-check {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 12px;
  border: 1px solid #e5e7eb; /* light gray */
  border-radius: 8px;
  background-color: #f9fafb;
  transition: all 0.2s ease-in-out;
}

.form-check:hover {
  background-color: #f3f4f6;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.form-check-input {
  width: 18px;
  height: 18px;
  accent-color: #2563eb; /* Tailwind blue-600 */
}

.form-check label {
  font-size: 0.95rem;
  color: #374151;
  font-weight: 500;
  cursor: pointer;
}

  .gallery-img.selected {
      border: 2px solid #0d6efd;
    }

    .bg-success-focus {
        background-color: var(--white-focus) !important;
    }

    .gallerySwiper {
      width: 100%;
      padding: 10px 40px;
    }

    .gallerySwiper .swiper-slide {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .gallerySwiper img {
      width: 250px;
      height: 200px;
      object-fit: contain;
      cursor: pointer;
      border-radius: 8px;
    }

    .gallerySwiperMapIcon {
      width: 100%;
      padding: 10px 40px;
    }

    .gallerySwiperMapIcon .swiper-slide {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .gallerySwiperMapIcon img {
      width: 250px;
      height: 200px;
      object-fit: contain;
      cursor: pointer;
      border-radius: 8px;
    }
</style>

<form id="categoryForm" enctype="multipart/form-data">

  <!-- General Info -->
  <div class="space-y-4">
    <h2 class="text-lg font-semibold text-gray-800">General Info</h2>
    <hr / style="padding-block: 5px; margin-top: 10px;">

    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="">
  <label for="city_id" class="block text-sm font-medium text-gray-700 mb-1">Location</label>
  <select class="form-select" id="city_id" name="city_id">
    <!-- <option value="">Loading cities...</option> -->
  </select>
</div>


      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Category Name</label>
        <input type="text" name="cat_name" required class="w-full border-gray-300  border-1 rounded-lg   h-12" value="">
      </div>
    </div>
  </div>
  <hr / style="padding-block: 5px; margin-top: 10px;">
  <!-- Base Fare Info -->
  <div class="space-y-4">
    <h2 class="text-lg font-semibold text-gray-800">Base Fare Info</h2>

    <div class="grid grid-cols-1 sm:grid-cols-1 md:grid-cols-2  gap-6">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Minimum Fare (Base Fare)</label>
        <input type="number" name="cat_base_price" required oninput="this.value = this.value.replace(/[^0-9]/g, '')" class="w-full   border-1  border-gray-300 rounded-lg   h-12" value="">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Distance included in Base Fare</label>
        <input type="number" name="cat_base_includes" required oninput="this.value = this.value.replace(/[^0-9]/g, '')" class="w-full  border-1  border-gray-300 rounded-lg   h-12" value="">
      </div>
    </div>
  </div>
  <hr / style="padding-block: 5px; margin-top: 10px;">

  <!-- Driver Section -->
  <div class="space-y-4">
    <h2 class="text-lg font-semibold text-gray-800">Driver Section</h2>

    <div class="grid grid-cols-1 md:grid-cols-3 sm:grid-cols-2 gap-6">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Driver Cancellation Fee Type</label>
        <select name="d_can_fee_type" required class="w-full form-select  border-1  border-gray-300 rounded-lg   h-12">
          <option value="F">Fixed</option>
          <option value="P">Percentage</option>
        </select>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Driver Cancellation Fee</label>
        <input type="number" name="d_can_fee" required oninput="this.value = this.value.replace(/[^0-9]/g, '')" class="w-full  border-1  border-gray-300 rounded-lg   h-12" value="">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Driver Locking Minutes at Arrival</label>
        <input type="number" name="d_can_free_min" required oninput="this.value = this.value.replace(/[^0-9]/g, '')" class="w-full  border-1  border-gray-300 rounded-lg   h-12" value="">
      </div>
    </div>
  </div>
  <hr / style="padding-block: 5px; margin-top: 10px;">

  <!-- Rider Section -->
  <div class="space-y-4">
    <h2 class="text-lg font-semibold text-gray-800">Rider Section</h2>

    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Rider Cancellation Fee Type</label>
        <select name="r_can_fee_type" required class="w-full form-select border-gray-300  border-1  rounded-lg   h-12">
          <option value="F">Fixed</option>
          <option value="P">Percentage</option>
        </select>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Rider Cancellation Fee</label>
        <input type="number" name="r_can_fee" required oninput="this.value = this.value.replace(/[^0-9]/g, '')" class="w-full border-gray-300  border-1  rounded-lg   h-12">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Rider Free Cancellation Minutes</label>
        <input type="number" name="r_can_free_min" required oninput="this.value = this.value.replace(/[^0-9]/g, '')" class="w-full border-gray-300   border-1 rounded-lg   h-12">
      </div>
    </div>
  </div>
  <hr / style="padding-block: 5px; margin-top: 10px;">

  <!-- Minutes Info -->
  <div class="space-y-4">
    <h2 class="text-lg font-semibold text-gray-800">Minutes Info</h2>

    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Fare Per (KM)</label>
        <input type="number" name="cat_fare_per_km" oninput="this.value = this.value.replace(/[^0-9]/g, '')" required class="w-full  border-1  border-gray-300 rounded-lg   h-12">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Fare Per Min</label>
        <input type="number" name="cat_fare_per_min" oninput="this.value = this.value.replace(/[^0-9]/g, '')" required class="w-full   border-1 border-gray-300 rounded-lg   h-12">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Free Waiting Minutes</label>
        <input type="number" name="wait_free_min" oninput="this.value = this.value.replace(/[^0-9]/g, '')" required class="w-full  border-1  border-gray-300 rounded-lg   h-12">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Waiting Fee per Minute</label>
        <input type="number" name="wait_per_min" oninput="this.value = this.value.replace(/[^0-9]/g, '')" required class="w-full   border-1 border-gray-300 rounded-lg   h-12">
      </div>
    </div>
  </div>
  <hr / style="padding-block: 5px; margin-top: 10px;">

  <!-- Basic Info -->
  <div class="space-y-4">
    <h2 class="text-lg font-semibold text-gray-800 mt-2">Basic Info</h2>

    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Max Passenger Capacity</label>
        <input type="number" name="cat_max_size" oninput="this.value = this.value.replace(/[^0-9]/g, '')" required class="w-full  border-1  border-gray-300 rounded-lg   h-12">
      </div>
        <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Change Destination Fee</label>
        <input type="number" name="chng_dest_fee" oninput="this.value = this.value.replace(/[^0-9]/g, '')" required class="w-full  border-1  border-gray-300 rounded-lg   h-12">
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Driver Search Radius (KM)</label>
        <input type="number" name="cat_radius" oninput="this.value = this.value.replace(/[^0-9]/g, '')" required class="w-full  border-1  border-gray-300 rounded-lg   h-12">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Sort Order</label>
        <input type="number" name="sort_order" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 3); if (parseInt(this.value) > 100) this.value = '100';" max="100" maxlength="2" required class="w-full  border-1  border-gray-300 rounded-lg   h-12">
      </div>
    </div>
  </div>
  <hr / style="padding-block: 5px; margin-top: 10px;">

  <!-- Map Icon Upload -->
  <div class="space-y-4">
    <h2 class="text-lg font-semibold text-gray-800 mt-2">Map & Icons</h2>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Icon (100x100)</label>
          <div style="display: flex;gap: 10px;">
            <input type="file" id="catIcon" name="cat_icon" accept=".png" class="w-full border-gray-300 rounded-lg  border-1    h-12" style="padding: 8px;">
            <span style="width: 10%;text-align: center;justify-content: center;display: flex;align-items: center;">
              <a href="javascript:void(0)" data-tooltip="Custom Category Icon" id="openGallery" class="bg-success-focus text-success-main"><i class="fas fa-images" style="font-size: 30px;"></i> </a>
            </span>
          </div>
          <img id="catIconPreview" src="#" class="mt-2 h-20 hidden">
          <span style="color: #d9534f; font-size: 0.9rem;">
            Only <strong>.png</strong> files are allowed
          </span>

        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Map Icon (50x109)</label>

          <div style="display: flex;gap: 10px;">
            <input type="file" id="catMapIcon" name="cat_map_icon" accept=".png" class="w-full border-1    border-gray-300 rounded-lg   h-12" style="padding: 8px;">
            <span style="width: 10%;text-align: center;justify-content: center;display: flex;align-items: center;">
              <a href="javascript:void(0)" data-tooltip="Custom Category Map Icon" id="openGalleryMapIcon" class="bg-success-focus text-success-main"><i class="fas fa-images" style="font-size: 30px;"></i> </a>
            </span>
          </div>
          <img id="catMapIconPreview" src="#" class="mt-2 h-20 hidden">
          <span style="color: #d9534f; font-size: 0.9rem;">
            Only <strong>.png</strong> files are allowed
          </span>

        </div>

      </div>
    </div>
    <hr / style="padding-block: 5px; margin-top: 10px;">


    <!-- gallery Modal Section -->
    <div class="modal fade" id="galleryModal">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h2 class="text-lg font-semibold text-gray-800">Select Icon</h2>
            <!-- <button class="btn-close" data-bs-dismiss="modal"></button> -->
            <span class="btn-close" data-bs-dismiss="modal"></span>
          </div>

          <div class="modal-body">
            <!-- <div class="row" id="galleryImages"></div> -->
            <div class="row" style="margin-left: 15px;margin-right: 15px;">
              <div class="swiper gallerySwiper">
                <div class="swiper-wrapper" id="galleryImages"></div>

                <!-- Controls -->
                <div class="swiper-button-next"></div>
                <div class="swiper-button-prev"></div>
                <div class="swiper-pagination"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="modal fade" id="galleryModalMapIcon">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h2 class="text-lg font-semibold text-gray-800">Select Map Icon</h2>
            <!-- <button class="btn-close" data-bs-dismiss="modal"></button> -->
            <span class="btn-close" data-bs-dismiss="modal"></span>
          </div>

          <div class="modal-body">
            <!-- <div class="row" id="galleryImagesMapIcon"></div> -->
            <div class="row" style="margin-left: 15px;margin-right: 15px;">
              <div class="swiper gallerySwiperMapIcon">
                <div class="swiper-wrapper" id="galleryImagesMapIcon"></div>

                <!-- Controls -->
                <div class="swiper-button-next"></div>
                <div class="swiper-button-prev"></div>
                <div class="swiper-pagination"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- Status -->

<!-- Status -->
<!-- Status Section -->
<div class="space-y-2 mt-6">
  <h2 class="text-lg font-semibold text-gray-800">Status Options</h2>

<div class="row g-3">
  <!-- Status -->
  <div class="col-12 col-sm-6 col-md-4 col-lg-2">
    <div class="form-check p-3 border rounded text-center">
      <input type="checkbox" id="status" name="cat_status" value="1" class="form-check-input">
      <label for="status" class="form-check-label ms-2">Status</label>
    </div>
  </div>

  <!-- Is Delivery -->
  <div class="col-12 col-sm-6 col-md-4 col-lg-2">
    <div class="form-check p-3 border rounded text-center">
      <input type="checkbox" id="is_delivery" name="is_delivery" value="1" class="form-check-input">
      <label for="is_delivery" class="form-check-label ms-2">Is Courier</label>
    </div>
  </div>

  <!-- Is Daily (Hidden but checked to preserve category display) -->
  <div class="col-12 col-sm-6 col-md-4 col-lg-2" style="display: none;">
    <div class="form-check p-3 border rounded text-center">
      <input type="checkbox" id="is_daily" name="is_daily" value="1" class="form-check-input" checked>
      <label for="is_daily" class="form-check-label ms-2">Is Daily</label>
    </div>
  </div>

  <!-- Is Outstation -->
  <div class="col-12 col-sm-6 col-md-4 col-lg-2">
    <div class="form-check p-3 border rounded text-center">
      <input type="checkbox" id="is_outstation" name="is_outstation" value="1" class="form-check-input">
      <label for="is_outstation" class="form-check-label ms-2">Is Outstation</label>
    </div>
  </div>

  <!-- Is Rental -->
  <div class="col-12 col-sm-6 col-md-4 col-lg-2">
    <div class="form-check p-3 border rounded text-center">
      <input type="checkbox" id="is_rental" name="is_rental" value="1" class="form-check-input">
      <label for="is_rental" class="form-check-label ms-2">Is Rental</label>
    </div>
  </div>
</div>

<script>
  document.querySelectorAll('.form-check').forEach(box => {
    const checkbox = box.querySelector('input[type="checkbox"]');
    const label = box.querySelector('label');

    // initial state
    box.classList.toggle('active', checkbox.checked);

    box.addEventListener('click', (e) => {
      // If click is directly on the checkbox -> let browser do it, then update class
      if (e.target === checkbox) {
        // checkbox.checked already updated by the browser
        box.classList.toggle('active', checkbox.checked);
        return;
      }

      // If click is on the label (or inside the label) -> let browser toggle the checkbox,
      // then update the class to reflect the new checked state.
      if (label && (e.target === label || label.contains(e.target))) {
        // use setTimeout 0 to run after browser toggles the checkbox
        setTimeout(() => {
          box.classList.toggle('active', checkbox.checked);
        }, 0);
        return;
      }

      // Clicked elsewhere inside the .form-check: toggle checkbox programmatically
      checkbox.checked = !checkbox.checked;
      box.classList.toggle('active', checkbox.checked);
    });

    // Keep state synced if checkbox is changed by other scripts
    checkbox.addEventListener('change', () => {
      box.classList.toggle('active', checkbox.checked);
    });
  });
</script>


 </div>

 
  <div id="checkboxError" style="color: red; font-size: 14px; margin-top: 8px;"></div>

    <!-- Submit -->
    <div class="" style="display: flex; justify-content: end; align-items: center; margin-top: 25px;">
      <button type="submit" class="px-3 bg-blue-600 hover:bg-blue-700 text-white py-4 rounded-lg font-semibold">Add Category</button>
    </div>
</form>


<script>
    function validateCheckboxes() {
    const isDaily = document.getElementById("is_daily").checked;
    const isOutstation = document.getElementById("is_outstation").checked;
    const isRental = document.getElementById("is_rental").checked;
    const errorDiv = document.getElementById("checkboxError");

    if (!isDaily && !isOutstation && !isRental) {
      errorDiv.textContent = "Please select at least one option: Is Daily, Is Outstation, or Is Rental.";
      return false; // Prevent form submission
    }

    // // Clear any previous error
    errorDiv.textContent = "";
    return true; // Allow form submission
  }
  // Define form configuration
  const formConfig = {
    formId: "categoryForm",
    fields: [{
        name: "city_id",
        type: "select",
        required: true,
        messages: {
          required: "Location is required"
        }
      },
      {
        name: "cat_name",
        type: "text",
        required: true,
        messages: {
          required: "Category name is required"
        }
      },
      {
        name: "cat_base_price",
        type: "text",
        required: true,
        messages: {
          invalid: "Base fare must be a valid number",
          required: "Base fare is required"
        }
      },
      {
        name: "cat_base_includes",
        type: "text",
        required: true,
        messages: {
          required: "Distance included in base fare is required",
        }
      },
      {
        name: "d_can_fee_type",
        type: "select",
        required: true,
        messages: {
          required: "Please select fee type"
        }
      },
      {
        name: "d_can_fee",
        type: "text",
        required: true,
        messages: {
          required: "Driver cancellation fee is required",
        }
      },
      {
        name: "d_can_free_min",
        type: "text",
        required: true,
        messages: {
          required: "Driver locking minutes at arrival is required"
        }
      },
      {
        name: "r_can_fee_type",
        type: "select",
        required: true,
        messages: {
          required: "Please select rider cancellation fee type"
        }
      },
      {
        name: "r_can_fee",
        type: "text",
        required: true,
        messages: {
          required: "Rider cancellation fee is required"
        }
      },
      {
        name: "r_can_free_min",
        type: "text",
        required: true,
        messages: {
          required: "Rider free cancellation minutes is required"
        }
      },
      {
        name: "cat_fare_per_km",
        type: "text",
        required: true,
        messages: {
          required: "Fare per KM is required",
        }
      },
      {
        name: "cat_fare_per_min",
        type: "text",
        required: true,
        messages: {
          required: "Fare per minute is required"
        }
      },
      {
        name: "wait_free_min",
        type: "text",
        required: true,
        messages: {
          required: "Free waiting minutes is required"
        }
      },
      {
        name: "wait_per_min",
        type: "text",
        required: true,
        messages: {
          required: "Waiting fee per minute is required"
        }
      },
      {
        name: "cat_max_size",
        type: "text",
        required: true,
        messages: {
          required: "Please select maximum passenger capacity"
        }
      }, {
        name: "chng_dest_fee",
        type: "text",
        required: true,
        messages: {
          required: "Change destination fee is required"
        }
      }, {
        name: "cat_radius",
        type: "text",
        required: true,
        messages: {
          required: "Driver search radius is required"
        }
      }, {
        name: "sort_order",
        type: "text",
        required: true,
        messages: {
          required: "Sort order is required"
        }
      }, {
        name: "cat_icon",
        type: "upload",
        required: true,
        messages: {
          required: "Please upload category icon"
        }
      },
      {
        name: "cat_map_icon",
        type: "upload",
        required: true,
        messages: {
          required: "Please upload category map icon"
        }
      },
      {
        name: "cat_status",
        type: "select",
        required: true,
        messages: {
          required: "Please select category status"
        }
      }
    ]
  };
</script>

<script src="/js/validator/validation.js"></script>

<script>
  document.getElementById('catIcon').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
      if (!allowedTypes.includes(file.type)) {
        Swal.fire('Invalid File', 'Please upload JPEG, JPG, PNG or GIF only.', 'error');
        e.target.value = '';
        return;
      }
      document.getElementById('catIconPreview').src = URL.createObjectURL(file);
    }
  });

  document.getElementById('catMapIcon').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
      if (!allowedTypes.includes(file.type)) {
        Swal.fire('Invalid File', 'Please upload JPEG, JPG, PNG or GIF only.', 'error');
        e.target.value = '';
        return;
      }
      document.getElementById('catMapIconPreview').src = URL.createObjectURL(file);
    }
  });

  document.getElementById('categoryForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const form = e.target;
    if (!form.checkValidity()) {
      Swal.fire('Error', 'Please fill all required fields.', 'error');
      return;
    }

    // Here you can send form data using Fetch/AJAX

    // Swal.fire('Success', 'Category updated successfully!', 'success');
  });
</script>



<script>
  function previewImage(inputId, previewId) {
    const input = document.getElementById(inputId);
    const preview = document.getElementById(previewId);

    input.addEventListener('change', function(e) {
      const file = e.target.files[0];
      if (file) {
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
        if (!allowedTypes.includes(file.type)) {
          Swal.fire('Invalid File', 'Please upload JPEG, JPG, PNG, or GIF only.', 'error');
          e.target.value = '';
          preview.src = '#';
          preview.classList.add('hidden');
          return;
        }
        preview.src = URL.createObjectURL(file);
        preview.classList.remove('hidden');
      }
    });
  }

  previewImage('catIcon', 'catIconPreview');
  previewImage('catMapIcon', 'catMapIconPreview');
</script>

<script>
  const formValidator = setupFormValidation(
    formConfig.formId,
    formConfig.fields
  );



  document.getElementById('categoryForm').addEventListener('submit', async function(e) {
    e.preventDefault(); // Stop default form submit
    if (!formValidator.validateForm()) return;

        if (!validateCheckboxes()) return;

    const form = e.target;
    const formData = new FormData(form); // Collect all form fields including files
            document.getElementById("loaderOverlay").style.display = "flex"; // Show loader

    try {
      const response = await fetch('/admin/addCategory', { // <-- Change URL to your actual API endpoint
        method: 'POST',
        body: formData
      });

      const result = await response.json();
            document.getElementById("loaderOverlay").style.display = "none"; // Show loader

      if (response.ok) {
Swal.fire('Success', result.message || 'Category added successfully!', 'success')
  .then(() => {
    // Redirect after user closes the alert
    window.location.href = '/admin/category-manager'; // Replace with your target URL
  });
        form.reset();
        document.getElementById('catIconPreview').classList.add('hidden');
        document.getElementById('catMapIconPreview').classList.add('hidden');
      } else {
        Swal.fire('Error', result.message || 'Something went wrong.', 'error');
      }
    } catch (error) {
      console.error('Error:', error);
                  document.getElementById("loaderOverlay").style.display = "none"; // Show loader

      Swal.fire('Error', 'Failed to send request.', 'error');
    }
  });
</script>


<script>
  document.addEventListener('DOMContentLoaded', function() {
    function setupValidation(feeTypeSelectName, feeInputName, feeInputValue, errorMessage) {
      const feeTypeSelect = document.querySelector(`select[name="${feeTypeSelectName}"]`);
      const feeInput = document.querySelector(`input[name="${feeInputName}"]`);

      // Validate input value based on fee type
      function validateInputValue() {
        const value = parseFloat(feeInput.value);

        // If 'Percentage' is selected
        if (feeTypeSelect.value === 'P') {
          if (value < 0 || value > 100) {
            Swal.fire({
              icon: 'error',
              title: 'Invalid Value',
              text: errorMessage,
            });
            feeInput.focus();
          }
        } else {
          // No validation needed for fixed fee type
        }
      }

      // Listen to events on the input and dropdown
      feeTypeSelect.addEventListener('change', validateInputValue);
      feeInput.addEventListener('input', validateInputValue);
    }

    // Apply validation for both driver and rider cancellation fee fields
    setupValidation('d_can_fee_type', 'd_can_fee', 'd_can_fee', 'Driver cancellation fee percentage must be between 0 and 100');
    setupValidation('r_can_fee_type', 'r_can_fee', 'r_can_fee', 'Rider cancellation fee percentage must be between 0 and 100');
  });
</script>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    const city_id = "<%= city_id %>"; // city assigned to the current record

    fetch('/admin/getcities')
      .then(res => res.json())
      .then(cities => {
        initDropdowns(cities, city_id);
      });

    function initDropdowns(cities, selectedId = null) {
      const cityDropdown = document.getElementById('city_id');
      cityDropdown.innerHTML = '<option value="">Select City</option>';

      // Populate dropdown
      cities.data.forEach(city => {
        const option = document.createElement('option');
        option.value = city.city_id;
        option.textContent = city.city_name;

        // Preselect if matches the current city_id
        if (String(city.city_id) === String(selectedId)) {
          option.selected = true;
        }

        cityDropdown.appendChild(option);
      });

      // ✅ If only one city, auto-select and disable
if (cities.data.length === 1) {
  const singleCity = cities.data[0];
  cityDropdown.value = singleCity.city_id;

  // 🔥 Do NOT disable — instead lock it visually
  cityDropdown.setAttribute("readonly", true);
  cityDropdown.style.pointerEvents = "none";
  cityDropdown.style.opacity = "0.7";
  cityDropdown.style.background = "#f3f4f6";
} else {
  cityDropdown.removeAttribute("readonly");
  cityDropdown.style.pointerEvents = "auto";
  cityDropdown.style.opacity = "1";
}

    }
  });
</script>

<script>
let gallerySwiper;

document.getElementById("openGallery").addEventListener("click", () => {
  fetch("/admin/custom-cat-gallery-icons")
    .then(res => res.json())
    .then(res => {
      if (!res.status) return;

      let html = "";

      res.images.forEach(img => {
        html += `
          <div class="swiper-slide">
            <img src="${img.url}"
                 class="img-thumbnail no-popup gallery-img"
                 data-img="${img.url}">
          </div>
        `;
      });

      document.getElementById("galleryImages").innerHTML = html;

      const modalEl = document.getElementById("galleryModal");
      const modal = new bootstrap.Modal(modalEl);
      modal.show();

      modalEl.addEventListener('shown.bs.modal', function () {
        if (gallerySwiper) {
          gallerySwiper.update();
        } else {
          gallerySwiper = new Swiper('.gallerySwiper', {
            slidesPerView: 4,
            spaceBetween: 15,
            navigation: {
              nextEl: '.swiper-button-next',
              prevEl: '.swiper-button-prev'
            },
            pagination: {
              el: '.swiper-pagination',
              clickable: true
            },
            breakpoints: {
              0: { slidesPerView: 2 },
              576: { slidesPerView: 3 },
              992: { slidesPerView: 5 }
            }
          });
        }
      }, { once: true });
    });
});
</script>

<script>
document.getElementById("galleryImages").addEventListener("click", async function (e) {
  if (!e.target.classList.contains("gallery-img")) return;

  const imgUrl = e.target.dataset.img;
  //console.log("Selected:", imgUrl);

  try {
    // 1️⃣ Fetch image
    const response = await fetch(imgUrl);
    const blob = await response.blob();

    // 2️⃣ Convert blob to File
    const fileName = imgUrl.split("/").pop();
    const file = new File([blob], fileName, { type: blob.type });

    // 3️⃣ Inject file into input[type=file]
    const dataTransfer = new DataTransfer();
    dataTransfer.items.add(file);
    document.getElementById("catIcon").files = dataTransfer.files;

    // 4️⃣ Show preview
    const preview = document.getElementById("catIconPreview");
    preview.src = URL.createObjectURL(file);
    preview.style.display = "block";

    // 5️⃣ Close modal
    bootstrap.Modal.getInstance(
      document.getElementById("galleryModal")
    ).hide();

  } catch (err) {
    //console.error("Image fetch failed", err);
  }
});

//--------------------

// document.getElementById("openGalleryMapIcon").addEventListener("click", () => {
//   fetch("/admin/custom-cat-gallery-map-icons")
//     .then(res => res.json())
//     .then(res => {
//       if (!res.status) return;

//       let html = "";
//       res.images.forEach(img => {
//         html += `
//           <div class="col-md-3 mb-3" style="width:135px;height:135px;">
//             <img src="${img.url}"
//                  class="img-fluid img-thumbnail no-popup cat-map-icon"
//                  data-img="${img.url}"
//                  style="cursor:pointer">
//           </div>
//         `;
//       });

//       document.getElementById("galleryImagesMapIcon").innerHTML = html;
//       new bootstrap.Modal(document.getElementById("galleryModalMapIcon")).show();
//     });
// });

let gallerySwiperMapIcon;

document.getElementById("openGalleryMapIcon").addEventListener("click", () => {
  fetch("/admin/custom-cat-gallery-map-icons")
    .then(res => res.json())
    .then(res => {
      if (!res.status) return;

      let html = "";

      res.images.forEach(img => {
        html += `
          <div class="swiper-slide">
            <img src="${img.url}"
                 class="img-thumbnail no-popup cat-map-icon"
                 data-img="${img.url}">
          </div>
        `;
      });

      document.getElementById("galleryImagesMapIcon").innerHTML = html;

      const modalEl = document.getElementById("galleryModalMapIcon");
      const modal = new bootstrap.Modal(modalEl);
      modal.show();

      modalEl.addEventListener('shown.bs.modal', function () {
        if (gallerySwiperMapIcon) {
          gallerySwiperMapIcon.update();
        } else {
          gallerySwiperMapIcon = new Swiper('.gallerySwiperMapIcon', {
            slidesPerView: 4,
            spaceBetween: 15,
            navigation: {
              nextEl: '.swiper-button-next',
              prevEl: '.swiper-button-prev'
            },
            pagination: {
              el: '.swiper-pagination',
              clickable: true
            },
            breakpoints: {
              0: { slidesPerView: 2 },
              576: { slidesPerView: 3 },
              992: { slidesPerView: 5 }
            }
          });
        }
      }, { once: true });
    });
});

document.getElementById("galleryImagesMapIcon").addEventListener("click", async function (e) {
  if (!e.target.classList.contains("cat-map-icon")) return;

  const imgUrl = e.target.dataset.img;
  //console.log("Selected:", imgUrl);

  try {
    // 1️⃣ Fetch image
    const response = await fetch(imgUrl);
    const blob = await response.blob();

    // 2️⃣ Convert blob to File
    const fileName = imgUrl.split("/").pop();
    const file = new File([blob], fileName, { type: blob.type });

    // 3️⃣ Inject file into input[type=file]
    const dataTransfer = new DataTransfer();
    dataTransfer.items.add(file);
    document.getElementById("catMapIcon").files = dataTransfer.files;

    // 4️⃣ Show preview
    const preview = document.getElementById("catMapIconPreview");
    preview.src = URL.createObjectURL(file);
    preview.style.display = "block";

    // 5️⃣ Close modal
    bootstrap.Modal.getInstance(
      document.getElementById("galleryModalMapIcon")
    ).hide();

  } catch (err) {
    //console.error("Image fetch failed", err);
  }
});

</script>

<!-- <script src="/js/demo-protection.js"></script> -->
