<form id="categoryForm" class="space-y-8" enctype="multipart/form-data">
<style>.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;
}
</style>
<script src="/js/demo-protection.js"></script>
<% const isLtfrb = typeof user !== 'undefined' && user && (user.group_id === 9 || user.group_id === 3 || user.u_email === 'ltfrb@gmail.com' || user.is_ltfrb); %>

  <% if (!isLtfrb) { %>
  <!-- General Info -->
  <div class="space-y-4">
    <h2 class="text-lg font-semibold text-gray-800">General Info</h2>

    <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="<%= category?.cat_name %>">
      </div>
    </div>
  </div>
  <% } %>

  <!-- Base Fare Info -->
  <div class="space-y-4">
      <hr / style="padding-block: 5px; margin-top: 10px;">

    <h2 class="text-lg font-semibold text-gray-800">Base Fare Info</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">Minimum Fare (Base Fare)</label>
        <input type="text" name="cat_base_price" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="
    this.value = this.value
      .replace(/[^0-9.]/g, '')
      .replace(/(\..*)\./g, '$1')
      .replace(/(\.\d{2}).+/g, '$1');" value="<%= category?.cat_base_price %>">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Distance included in Base Fare</label>
        <input type="text" name="cat_base_includes" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="
    this.value = this.value
      .replace(/[^0-9.]/g, '')
      .replace(/(\..*)\./g, '$1')
      .replace(/(\.\d{2}).+/g, '$1');" value="<%= category?.cat_base_includes %>">
      </div>
    </div>
  </div>

  <% if (!isLtfrb) { %>
  <!-- Driver Section -->
  <div class="space-y-4">
      <hr / style="padding-block: 5px; margin-top: 10px;">

    <h2 class="text-lg font-semibold text-gray-800">Driver Section</h2>

    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 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 border-gray-300 border-1 form-select rounded-lg h-12">
          <option value="F" <%= category?.d_can_fee_type == 'F' ? 'selected' : '' %>>Fixed</option>
          <option value="P" <%= category?.d_can_fee_type == 'P' ? 'selected' : '' %>>Percentage</option>
        </select>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Driver Cancellation Fee</label>
        <input type="text" name="d_can_fee" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="
    this.value = this.value
      .replace(/[^0-9.]/g, '')
      .replace(/(\..*)\./g, '$1')
      .replace(/(\.\d{2}).+/g, '$1');" value="<%= category?.d_can_fee %>">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Driver Locking Minutes at Arrival</label>
        <input type="text" name="d_can_free_min" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="this.value = this.value.replace(/[^0-9]/g, '')" value="<%= category?.d_can_free_min %>">
      </div>
    </div>
  </div>

  <!-- Rider Section -->
  <div class="space-y-4">
      <hr / style="padding-block: 5px; margin-top: 10px;">

    <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-2 lg: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 border-gray-300 border-1 form-select rounded-lg h-12">
          <option value="F" <%= category?.r_can_fee_type == 'F' ? 'selected' : '' %>>Fixed</option>
          <option value="P" <%= category?.r_can_fee_type == 'P' ? 'selected' : '' %>>Percentage</option>
        </select>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Rider Cancellation Fee</label>
        <input type="text" name="r_can_fee" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="
    this.value = this.value
      .replace(/[^0-9.]/g, '')
      .replace(/(\..*)\./g, '$1')
      .replace(/(\.\d{2}).+/g, '$1');" value="<%= category?.r_can_fee %>">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Rider Free Cancellation Minutes</label>
        <input type="text" name="r_can_free_min" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="this.value = this.value.replace(/[^0-9]/g, '')" value="<%= category?.r_can_free_min %>">
      </div>
    </div>
  </div>
  <% } %>

  <!-- Minutes Info -->
  <div class="space-y-4">
      <hr / style="padding-block: 5px; margin-top: 10px;">

    <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="text" name="cat_fare_per_km" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="
    this.value = this.value
      .replace(/[^0-9.]/g, '')
      .replace(/(\..*)\./g, '$1')
      .replace(/(\.\d{2}).+/g, '$1');" value="<%= category?.cat_fare_per_km %>">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Fare Per Min</label>
        <input type="text" name="cat_fare_per_min" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="
    this.value = this.value
      .replace(/[^0-9.]/g, '')
      .replace(/(\..*)\./g, '$1')
      .replace(/(\.\d{2}).+/g, '$1');" value="<%= category?.cat_fare_per_min %>">
      </div>
      <% if (!isLtfrb) { %>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Free Waiting Minutes</label>
        <input type="text" name="wait_free_min" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="this.value = this.value.replace(/[^0-9]/g, '')" value="<%= category?.wait_free_min %>">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Waiting Fee per Minute</label>
        <input type="text" name="wait_per_min" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="
    this.value = this.value
      .replace(/[^0-9.]/g, '')
      .replace(/(\..*)\./g, '$1')
      .replace(/(\.\d{2}).+/g, '$1');" value="<%= category?.wait_per_min %>">
      </div>
      <% } %>
    </div>
  </div>

  <% if (!isLtfrb) { %>
  <!-- Basic Info -->
  <div class="space-y-4">
      <hr / style="padding-block: 5px; margin-top: 10px;">

    <h2 class="text-lg font-semibold text-gray-800">Basic Info</h2>

    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-3 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" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="this.value = this.value.replace(/[^0-9]/g, '')" value="<%= category?.cat_max_size %>">
      </div>
 
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Driver Search Radius (KM)</label>
        <input type="text" name="cat_radius" required class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="
    this.value = this.value
      .replace(/[^0-9.]/g, '')
      .replace(/(\..*)\./g, '$1')
      .replace(/(\.\d{2}).+/g, '$1');" value="<%= category?.cat_radius %>">
      </div>
      <!-- <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Commission (%)</label>
        <input type="text" name="commission" class="w-full border-gray-300 border-1 rounded-lg h-12" oninput="
    this.value = this.value
      .replace(/[^0-9.]/g, '')
      .replace(/(\..*)\./g, '$1')
      .replace(/(\.\d{2}).+/g, '$1');" value="<%= category?.commission || 0 %>" placeholder="0.00">
      </div> -->
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Sort Order</label>

        <input type="number" name="sort_order" required max="99" min="0" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 2)" class="w-full border-gray-300 border-1 rounded-lg h-12" value="<%= category?.sort_order %>">


      </div>
    </div>
  </div>

  <!-- Map Icon Upload -->
  <div class="space-y-4">
      <hr / style="padding-block: 5px; margin-top: 10px;">

    <h2 class="text-lg font-semibold text-gray-800">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>
        <input type="file" id="catIcon" name="cat_icon" accept=".png" class="w-full  border-gray-300 border-1 rounded-lg h-12" style="padding: 8px;">
      <span style="color: #d9534f; font-size: 0.9rem;">
  Only <strong>.png</strong> files are allowed
</span>
  <% if (category?.cat_icon_path) { %>
        <img id="catIconPreview" src="<%= CATEGORY_BASE_URL %><%= category.cat_icon_path %>" class="mt-2 h-20">
        <% } %>
 

      </div>


      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Map Icon (50x109)</label>
        <input type="file" id="catMapIcon" name="cat_map_icon" accept=".png" class="w-full border-gray-300 border-1 rounded-lg h-12" style="padding: 8px;">
      <span style="color: #d9534f; font-size: 0.9rem;">
  Only <strong>.png</strong> files are allowed
</span>

        <% if (category?.cat_map_icon_path) { %>
        <img id="catMapIconPreview" src="<%= CATEGORY_BASE_URL %><%= category.cat_map_icon_path %>" class="mt-2 h-20">
        <% } %>
        
      </div>
    </div>
  </div>

  <!-- Bidding Settings Section -->

 
<!-- Status Section -->
<div class="space-y-2 mt-6">
  <h2 class="text-lg font-semibold text-gray-800" style="padding-bottom: 10px;">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">
      <input type="hidden" name="cat_status" value="0">
      <input 
        type="checkbox"
        id="status"
        name="cat_status"
        value="1"
        <%= category?.cat_status == 1 ? 'checked' : '' %>
        class="form-check-input"
      >
      <label for="status" class="form-check-label">Status</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">
      <input type="hidden" name="is_daily" value="0">
      <input 
        type="checkbox"
        id="is_daily"
        name="is_daily"
        value="1"
        checked
        class="form-check-input"
      >
      <label for="is_daily" class="form-check-label">Is Daily</label>
    </div>
  </div>
  <!-- Is Female -->
<!-- <div class="col-12 col-sm-6 col-md-4 col-lg-2" style="pointer-events: none;">
  <div class="form-check">
    <input type="hidden" name="is_female" value="<%= category?.is_female %>">

    <input 
      type="checkbox"
      id="is_female"
      <%= category?.is_female == 1 ? 'checked' : '' %>
      class="form-check-input"
      style="pointer-events:none; opacity:0.6;"
    >

    <label class="form-check-label">Is Female</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 style="display: flex; justify-content: end; align-items: center; margin-top: 20px;">
    <button type="submit" class=" bg-blue-600 hover:bg-blue-700 text-white py-[10px] rounded-lg font-semibold">Save Category</button>
  </div>

</form>



<script>

    function validateCheckboxes() {
      // return
    // const isDaily = document.getElementById("is_daily").checked;
    // const isOutstation = document.getElementById("is_outstation").checked;
    // const isRental = document.getElementById("is_rental").checked;
    // const is_delivery = document.getElementById("is_delivery").checked;
    // const errorDiv = document.getElementById("checkboxError");

    // console.log("123121")
    // if (!isDaily && !isOutstation && !isRental && !is_delivery) {
    //   errorDiv.textContent = "Please select at least one option: Is Daily, Is Outstation, Is Rental, or Is Courier.";
    //       console.log("23")

    //   return true; // Prevent form submission
    // }

    // // Clear any previous error
    // errorDiv.textContent = "";
    
    // // Validate bidding fields only if bidding is enabled
    // const isBidding = document.getElementById("is_bidding").checked;
    // if (isBidding) {
    //   const maxOfferPerc = parseFloat(document.getElementById("max_offer_perc").value) || 0;
    //   const minOfferPerc = parseFloat(document.getElementById("min_offer_perc").value) || 0;
      
    //   if (maxOfferPerc === 0 || minOfferPerc === 0) {
    //     errorDiv.textContent = "When bidding is enabled, both Max Offer % and Min Offer % must be greater than 0.";
    //     return false;
    //   }
      
    //   if (minOfferPerc > maxOfferPerc) {
    //     errorDiv.textContent = "Min Offer % cannot be greater than Max Offer %.";
    //     return false;
    //   }
    // }
    
    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: "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_status",
        type: "select",
        required: true,
        messages: {
          required: "Please select category status"
        }
      }
    ]
  };
</script>

<script src="/js/validator/validation.js"></script>

<script>
  const category = "<%- JSON.stringify(category || {}) %>"; // Pass server-side data into JS
  const initialData = {};

  // Capture initial values
  document.querySelectorAll('#categoryForm [name]').forEach(field => {
    initialData[field.name] = field.value;
  });
</script>

<script>
  function validateImageSize(input, expectedWidth, expectedHeight, previewId, label, tolerance = 0.15) {
    const file = input.files[0];
    if (!file) return;

    const img = new Image();
    img.onload = function () {
      const actualRatio = img.width / img.height;
      const expectedRatio = expectedWidth / expectedHeight;

      // Allow deviation ±tolerance (5% default)
      const minRatio = expectedRatio * (1 - tolerance);
      const maxRatio = expectedRatio * (1 + tolerance);

      if (actualRatio < minRatio || actualRatio > maxRatio) {
        Swal.fire(
          'Invalid Image Ratio',
          `${label} must follow a ${expectedWidth}x${expectedHeight}px ratio.\n` +
          `Your image size is ${img.width}x${img.height}px.`,
          'error'
        );
        input.value = '';
        if (previewId) document.getElementById(previewId).src = '';
      } else {
        if (previewId) {
          document.getElementById(previewId).src = URL.createObjectURL(file);
        }
      }
    };

    img.src = URL.createObjectURL(file);
  }

  document.getElementById('catIcon')?.addEventListener('change', function () {
    // Accept same ratio as 100x100 (1:1)
    validateImageSize(this, 100, 100, 'catIconPreview', 'Icon');
  });

  document.getElementById('catMapIcon')?.addEventListener('change', function () {
    // Accept same ratio as 50x109 (≈0.4587)
    validateImageSize(this, 50, 109, 'catMapIconPreview', 'Map Icon');
  });
</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;
      }
      const preview = document.getElementById('catIconPreview');
      if (preview) preview.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;
      }
      const preview = document.getElementById('catMapIconPreview');
      if (preview) preview.src = URL.createObjectURL(file);
    }
  });
      const formValidator = setupFormValidation(
    formConfig.formId,
    formConfig.fields
  );

  document.getElementById('categoryForm').addEventListener('submit', async function(e) {
    e.preventDefault();
        if (!validateCheckboxes()) return;

     if (!formValidator.validateForm()) return;

 
    const form = e.target;
    if (!form.checkValidity()) {
      Swal.fire('Error', 'Please fill all required fields.', 'error');
      return;
    }


      $("#loader").show();

    const formData = new FormData(form);
    const categoryId = "<%= category?.category_id %>";

    // Get the file inputs
    const catIconInput = document.getElementById('catIcon');
    const catMapIconInput = document.getElementById('catMapIcon');

    // Append the files if they exist
    // if (catIconInput.files[0]) {
    //     formData.append('cat_icon', catIconInput.files[0]);
    // }
    // if (catMapIconInput.files[0]) {
    //     formData.append('cat_map_icon', catMapIconInput.files[0]);
    // }
// Sanitize binary checkbox fields
const binaryFields = ['cat_status','is_share','is_bidding','is_extras','is_delivery','is_daily', 'is_outstation', 'is_rental'];
binaryFields.forEach(field => {
  const values = formData.getAll(field);
  if (values.length > 1) {
    formData.delete(field);
    formData.append(field, values[values.length - 1]);
  }
});

    try {
      const response = await fetch(`/admin/category/update/${categoryId}`, {
        method: 'POST',
        body: formData // This will include the binary file data
        // Note: Don't set Content-Type header - the browser will set it automatically
      });
      $("#loader").hide();

      const result = await response.json();
      if (result.success) {
        Swal.fire({
          icon: 'success',
          title: 'Saved!',
          text: 'Changes saved successfully.',
          showConfirmButton: false,
          timer: 1500
        }).then(() => {
          // Reload the page to refresh seat count in Share Discount tab
          window.location.reload();
        });
      } else {
        document.getElementById('catIcon').value = '';
        document.getElementById('catMapIcon').value = '';
        Swal.fire('Saved!', 'Changes saved successfully.', 'success').then(() => {
          window.location.reload();
        });
      }
    } catch (error) {
      $("#loader").hide();
      console.error(error);
      Swal.fire('Error', 'Network error occurred.', 'error');
    }
  });


</script>
<script>
  document.addEventListener('DOMContentLoaded', function () {
    const savedCityId = "<%= category.city_id %>"; // assigned city for this category

    fetch('/admin/getcities')
      .then(res => res.json())
      .then(cities => {
        initDropdowns(cities, savedCityId);
      });

    function initDropdowns(cities, selectedId = null) {
      const cityDropdown = document.getElementById('city_id');
      cityDropdown.innerHTML = '<option value="">Select City</option>';

      // Populate dropdown with city options
      cities.data.forEach(city => {
        const option = document.createElement('option');
        option.value = city.city_id;
        option.textContent = city.city_name;

        // Preselect if matches category 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>
  // Toggle Share Discount tab based on is_share checkbox
  document.addEventListener('DOMContentLoaded', function() {
    const isShareCheckbox = document.getElementById('is_share');
    const shareDiscountTabBtn = document.getElementById('share-discount-tab-btn');
    
    function toggleShareDiscountTab() {
      if (isShareCheckbox && shareDiscountTabBtn) {
        if (isShareCheckbox.checked) {
          shareDiscountTabBtn.style.display = 'block';
        } else {
          shareDiscountTabBtn.style.display = 'none';
        }
      }
    }
    
    // Initial check on page load
    toggleShareDiscountTab();
    
    // Listen for changes
    if (isShareCheckbox) {
      isShareCheckbox.addEventListener('change', toggleShareDiscountTab);
    }
  });
</script>
