   <%- header %>
   <!-- pre-rendered navbar inserted -->
   <main class="dashboard-main">
     <%- navbar %>
     <!-- pre-rendered navbar inserted -->


     <style>
       .select2-container {
         min-width: 100px !important;
         width: auto !important;
       }

       .select2-selection {
         height: 100% !important;
         padding: 6px 8px !important;
       }

       .select2-selection__rendered {
         line-height: 36px !important;
         padding-left: 6px !important;
       }

       #phone {
         width: 70% !important;
         border-bottom-right-radius: 8px;
         border-top-right-radius: 8px;
       }

       @media (max-width: 576px) {
         #countryCode {
           min-width: 90px !important;
         }
       }

       .select2-selection__rendered {
         padding: 0px !important;
       }
     </style>



     <div class="container flex-1 pt-20 w-full my-4">

       <%- include('../../partials/utils/title.ejs', {title: "Add Driver"}) %>

       <% 
    const breadcrumbs = [
      { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
       { label: " Add Driver" }
    ];
  %>

       <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>

       <div class="  mt-4">
         <div class=" bg-white shadow-md rounded-lg" style="padding: 15px;">

           <form id="createDriverForm" enctype="multipart/form-data">
             <div class="row">
               <!-- Left Column -->
               <div class="col-md-6">
                 <h4 class="text-lg font-semibold">General Info</h4>
                 <hr / style="margin-top: 10px;">

                 <div class="mb-2">
                   <label for="city_id" class="form-label">Location</label>
                   <select class="form-select" id="city_id" name="city_id">
                     <option value="">Loading cities...</option>
                   </select>
                 </div>


                 <div class="mb-4">
                   <label class="form-label">Phone</label>
                   <div class="input-group">
                     <div class="input-group-prepend">
                       <select id="countryCode" class="form-select" name="countryCode" style="width: 100%;">
                         <option disabled selected value="">Choose Country</option>
                       </select>
                     </div>
                     <input type="tel" id="phone" name="phone" class="form-control" oninput="this.value = this.value.replace(/[^0-9]/g, '')" />
                   </div>
                 </div>


                 <div class="mb-4">
                   <label class="form-label">First Name</label>
                   <input type="text" id="firstName" name="d_fname" class="form-control" oninput="this.value = this.value.replace(/^\s+/, '')">
                 </div>

                 <div class="mb-4">
                   <label class="form-label">Last Name</label>
                   <input type="text" id="lastName" name="d_lname" class="form-control" oninput="this.value = this.value.replace(/^\s+/, '')">
                 </div>
                 <div class="mb-3">
                <label for="d_gender" class="form-label">Gender</label>
                <select class="form-select" id="d_gender" name="d_gender">
                  <option value="" selected disabled>Please select gender</option>
                  <option value="Male">Male</option>
                  <option value="Female">Female</option>
                 </select>
              </div>
                 <div class="mb-4">
                   <label class="form-label">Email</label>
                   <input type="email" id="email" name="email" class="form-control">
                 </div>
                 <div>
                   <div class="mb-4" style="display: none;">
                     <label for="text_password" class="form-label">Password</label>
                     <input type="text" class="form-control" id="text_password" name="text_password">
                   </div>
                 </div>
                 <div class="mb-4">
                   <label class="form-label">Profile Picture</label>
                   <input type="file" id="profilePic" name="profilePic" class="form-control" accept="image/*">
                   <img id="profilePreview" class="image-preview" style="display:none;">
                   <small id="profilePicError" class="text-danger"></small>

                 </div>
                 <div class="form-check" style="margin-top: 30px; display: flex; justify-content: start; align-items: center; gap: 10px;">
                   <input type="checkbox" id="d_is_verified" name="d_is_verified" class="form-check-input" />
                   <label for="d_is_verified" class="form-check-label">Approved</label>
                 </div>
               </div>

               <!-- Right Column -->
               <div class="col-md-6">
                 <h4 class="text-lg font-semibold">Vehicle Information</h4>
                 <hr / style="margin-top: 10px;">

                 <div class="mb-4">
                   <label class="form-label">Category</label>
                   <select id="category" class="form-select" name="category">
                     <option disabled selected value="">Select category</option>
                   </select>
                 </div>

                 <div class="mb-4">
                   <label class="form-label">Vehicle Model</label>
                   <input type="text" id="carModel" name="model" class="form-control">
                 </div>

                 <div class="mb-4">
                   <label class="form-label">Vehicle Brand</label>
                   <input type="text" id="vehicleBrand" class="form-control" name="brand">
                 </div>

                 <div class="mb-4">
                   <label class="form-label">Year of Manufacture</label>
                   <input type="text" id="year" class="form-control" name="yom">
                 </div>

                 <div class="mb-4">
                   <label class="form-label">Registration Number</label>
                   <input type="text" id="registration" class="form-control" name="reg">
                 </div>

                 <div class="mb-4">
                   <label class="form-label">Vehicle Front Image</label>
                   <input type="file" id="vehicleFront" class="form-control" accept=".jpg" name="vfi">
                   <img id="vehicleFrontPreview" class="image-preview" style="display:none;">
                   <small id="vehicleFrontError" class="text-danger"></small>
                 </div>

                 <div class="mb-4">
                   <label class="form-label">Vehicle Back Image</label>
                   <input type="file" id="vehicleBack" class="form-control" accept=".jpg" name="vbi">
                   <img id="vehicleBackPreview" class="image-preview" style="display:none;">
                   <small id="vehicleBackError" class="text-danger"></small>
                 </div>





               </div>
               <div style="display: flex; justify-content: end;">
                 <button id="registerBtn" class="btn btn-primary mt-2" style="width: 150px; padding: 10px;">Add Driver</button>
               </div>
             </div>
           </form>
         </div>
       </div>

     </div>
     </div>
     <!-- Black Transparent Loader Overlay -->
     <div id="loaderOverlay" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
       <div class="animate-spin rounded-full h-12 w-12 border-t-4 border-blue-500 border-solid"></div>
     </div>

     <script>
       // Define form configuration
       const formConfig = {
         formId: "createDriverForm",
         fields: [{
             name: "d_fname",
             type: "text",
             required: true,
             messages: {
               required: "First name is required"
             }
           },
           {
             name: "d_lname",
             type: "text",
             required: true,
             messages: {
               required: "Last name is required"
             }
           },
           {
             name: "email",
             type: "email",
             required: true,
             messages: {
               invalid: "Please enter a valid email address"
             }
           },

           {
             name: "countryCode",
             type: "select",
             required: true,
             messages: {
               required: "Please select country code"
             }
           },
           {
             name: "phone",
             type: "phone",
             required: true,
             messages: {
               required: "Phone number is required",
               invalid: "Phone number must be 6-15 digits"
             }
           },
           {
             name: "status",
             type: "select",
             required: true,
             messages: {
               required: "Please select status"
             }
           },
           {
             name: "profilePic",
             type: "upload",
             required: true,
             messages: {
               required: "Profile image is required"
             }
           },
           {
             name: "vfi",
             type: "upload",
             required: true,
             messages: {
               required: "Vehicle front image is required"
             }
           },
           {
             name: "vbi",
             type: "upload",
             required: true,
             messages: {
               required: "Vehicle Back image is required"
             }
           },
           {
             name: "model",
             type: "text",
             required: true,
             messages: {
               required: "Vehicle Model is required"
             }
           },
           {
             name: "brand",
             type: "text",
             required: true,
             messages: {
               required: "Vehicle Brand is required"
             }
           },
           {
             name: "yom",
             type: "text",
             required: true,
             messages: {
               required: "Year is required"
             }
           },
           {
             name: "reg",
             type: "text",
             required: true,
             messages: {
               required: "Registration number is required"
             }
           },
           {
             name: "category",
             type: "select",
             required: true,
             messages: {
               required: "Please select category"
             }
           },
              {
             name: "d_gender",
             type: "select",
             required: true,
             messages: {
               required: "Please select gender"
             }
           },
         ]
       };
     </script>

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

     <script>
       let API_BASE_URL = "<%= API_BASE_URL %>";
       const userCompanyId = <%= user.user_id %>;
       const userGroupId = <%= user.group_id %>;
       
       validateImage("vehicleFront", "vehicleFrontPreview", "vehicleFrontError");
       validateImage("vehicleBack", "vehicleBackPreview", "vehicleBackError");
       validateImage("profilePic", "profilePreview", "profilePicError");
       document.addEventListener("DOMContentLoaded", function() {
         console.log("Script loaded!");
         let toastCooldown = false;

         function showToast(message, type = "error") {
           if (!toastCooldown) {
             toastCooldown = true;

             Swal.fire({
               toast: true,
               position: 'top-end',
               icon: type === "error" ? "error" : "success",
               title: message,
               showConfirmButton: false,
               timer: 3000,
               timerProgressBar: true,
               didOpen: (toast) => {
                 toast.addEventListener('mouseenter', Swal.stopTimer)
                 toast.addEventListener('mouseleave', Swal.resumeTimer)
               }
             });

             setTimeout(() => (toastCooldown = false), 2000);
           }
         }


         function validateForm() {
           const requiredFields = [{
               id: 'countryCode',
               name: 'Country C ode'
             },
             {
               id: 'phone',
               name: 'Phone Number'
             },
             {
               id: 'firstName',
               name: 'First Name'
             },
             {
               id: 'lastName',
               name: 'Last Name'
             },
             {
               id: 'email',
               name: 'Email'
             },
             {
               id: 'profilePic',
               name: 'Profile Picture'
             },
             {
               id: 'category',
               name: 'Category'
             },
             {
               id: 'carModel',
               name: 'Car Model'
             },
             {
               id: 'vehicleBrand',
               name: 'Vehicle Brand'
             },
             {
               id: 'year',
               name: 'Year of Manufacture'
             },
             {
               id: 'registration',
               name: 'Registration Number'
             },
             {
               id: 'vehicleFront',
               name: 'Vehicle Front Image'
             },
             {
               id: 'vehicleBack',
               name: 'Vehicle Back Image'
             },

           ];

           let isValid = true;

           requiredFields.forEach(field => {
             const element = document.getElementById(field.id);
             if (!element ||
               (element.value === '' && element.type !== 'file') ||
               (element.type === 'file' && !element.files[0])) {
               showToast(`${field.name} is required`);
               isValid = false;
               if (element) element.style.borderColor = 'red';
             } else {
               if (element) element.style.borderColor = '';
             }
           });

           // Validate email format
           const email = document.getElementById('email');
           if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value)) {
             showToast('Please enter a valid email address');
             isValid = false;
             email.style.borderColor = 'red';
           }

           return isValid;
         }

         async function validatePhoneNumber(countryCode, phoneNumber, email = "") {

           if (!/^\d{6,15}$/.test(phoneNumber)) {
             return Swal.fire("Invalid Phone Number", "Phone number must be between 6 to 15 digits.", "error");
           }
           try {
             const formData = new FormData();
             formData.append('c_code', countryCode);
             formData.append('d_phone', phoneNumber);
             if (email) formData.append('d_email', email);

             const response = await fetch(`${API_BASE_URL}driverapi/phdrivervalidate`, {
               method: 'POST',
               body: formData
             });

             const result = await response.json();
             return result;
           } catch (error) {
             console.error('Validation error:', error);
             return {
               status: 'error',
               message: 'Validation failed'
             };
           }
         }

         async function registerDriver(registrationData) {
           try {
             const formData = new FormData();
             for (const key in registrationData) {
               formData.append(key, registrationData[key]);
               document.getElementById("loaderOverlay").classList.remove("hidden");

             }

             const response = await fetch(`${API_BASE_URL}driverapi/registrationv1`, {
               method: 'POST',
               body: formData
             });

             return await response.json();
           } catch (error) {
             document.getElementById("loaderOverlay").classList.add("hidden");

             console.error('Registration error:', error);
             return {
               status: 'error',
               message: 'Registration failed'
             };
           }
         }

         // Helper function to convert file to base64
         function getBase64(file) {
           return new Promise((resolve, reject) => {
             const reader = new FileReader();
             reader.readAsDataURL(file);
             reader.onload = () => {
               // Extract base64 string (remove data:image/...;base64, prefix)
               const base64String = reader.result.split(',')[1];
               resolve({
                 base64: base64String,
                 type: file.type
               });
             };
             reader.onerror = error => reject(error);
           });
         }

         async function updateDriverProfile(updateData) {
           try {
             const formData = new FormData();

             // Append all non-file fields
             for (const key in updateData) {
               if (key !== 'driver_image' && key !== 'car_image' && key !== 'car_image_back') {
                 formData.append(key, updateData[key]);
               }
             }

             // Handle file uploads as base64
             const profilePic = document.getElementById('profilePic');
             const vehicleFront = document.getElementById('vehicleFront');
             const vehicleBack = document.getElementById('vehicleBack');

             if (profilePic.files[0]) {
               const {
                 base64,
                 type
               } = await getBase64(profilePic.files[0]);
               formData.append('driver_image', base64);
               formData.append('image_type', type); // Add image type for profile image
             }
             if (vehicleFront.files[0]) {
               const {
                 base64
               } = await getBase64(vehicleFront.files[0]);
               formData.append('car_image', base64);
             }
             if (vehicleBack.files[0]) {
               const {
                 base64
               } = await getBase64(vehicleBack.files[0]);
               formData.append('car_image_back', base64);
             }


             const response = await fetch(`${API_BASE_URL}driverapi/updatedriverprofile`, {
               method: 'POST',
               body: formData
             });
             document.getElementById("loaderOverlay").classList.add("hidden");


             return await response.json();
           } catch (error) {
             document.getElementById("loaderOverlay").classList.add("hidden");

             console.error('Update error:', error);
             return {
               status: 'error',
               message: 'Update failed'
             };
           }
         }

         const formValidator = setupFormValidation(
           formConfig.formId,
           formConfig.fields
         );
         async function handleRegistrationAndUpdate() {


           if (!formValidator.validateForm()) return;

           // Then validate the phone number
           const validationResult = await validatePhoneNumber(
             document.getElementById('countryCode').value.trim().replace(/\D/g, ''),
             document.getElementById('phone').value,
             document.getElementById('email').value
           );

           if (!validationResult || validationResult.resDecrypt?.message !== null) {
             showToast(validationResult?.resDecrypt?.message || 'Validation failed');
             return;
           }

           // Register the driver
           const registrationData = {
             c_code: document.getElementById('countryCode').value.trim().replace(/\D/g, ''),
             iso_code: $('#countryCode option:selected').data('iso'),
             d_phone: document.getElementById('phone').value,
             d_email: document.getElementById('email').value
           };
           
           // Add company_id for sub-admins
           if (userGroupId !== 1) {
             registrationData.company_id = userCompanyId;
           }

           const registrationResult = await registerDriver(registrationData);

           if (registrationResult.resDecrypt?.code !== 200) {
             showToast(registrationResult.resDecrypt?.message || 'Registration failed');
             return;
           }

           const driverId = registrationResult.resDecrypt.response.driver_id;
           const apiKey = registrationResult.resDecrypt.response.api_key;

           // Update driver profile with additional information
  const updateData = {
  driver_id: driverId,
  d_phone: document.getElementById('phone').value,
  d_fname: document.getElementById('firstName').value,
  d_lname: document.getElementById('lastName').value,
  d_email: document.getElementById('email').value,
  category_id: document.getElementById('category').value,
  car_name: document.getElementById('carModel').value,
  car_model: document.getElementById('vehicleBrand').value,
  car_make: document.getElementById('year').value,
  car_reg_no: document.getElementById('registration').value,
  city_id: document.getElementById('city_id').value,
  c_code: document.getElementById('countryCode').value.trim().replace(/\D/g, ''),
  d_is_verified:document.getElementById('d_is_verified').checked ? 1 : 0,
  d_gender: document.getElementById("d_gender").value,
  api_key: apiKey,
  is_return_details: 1
};

// Add company_id for sub-admins
if (userGroupId !== 1) {
  updateData.company_id = userCompanyId;
}

// 🔥 Check password only once
const newPassword = document.getElementById("text_password").value.trim();

if (newPassword) {
  updateData.d_password = newPassword;
  updateData.is_password_required = 1;
}


           const updateResult = await updateDriverProfile(updateData);

           if (updateResult.status === 'success' || updateResult.resDecrypt?.code === 200) {
             showToast('Driver registered and profile updated successfully!', 'success');
             // Optional: Redirect after successful registration

             updateResult.resDecrypt.response.d_active = 1 ? window.location.href = '/admin/active-drivers' : window.location.href = '/admin/inactive-drivers';; // Ensure driver_id is set for redirection

             // window.location.href = '/admin/drivers';
           } else {
             showToast(updateResult.message || updateResult.resDecrypt?.message || 'Profile update failed');
           }
         }

         // Attach event listener to registration button
         document.getElementById('registerBtn').addEventListener('click', async function(e) {
           e.preventDefault();
           await handleRegistrationAndUpdate();
         });

         // Image preview functions
         function previewImage(input, previewId, imageTypeElementId) {
           if (input.files && input.files[0]) {
             const reader = new FileReader();
             reader.onload = function(e) {
               const preview = document.getElementById(previewId);
               if (preview) {
                 preview.src = e.target.result;
                 preview.style.display = "block";
               }

               // Update image type if element ID is provided
               if (imageTypeElementId) {
                 const imageTypeElement = document.getElementById(imageTypeElementId);
                 if (imageTypeElement) {
                   imageTypeElement.value = input.files[0].type;
                 }
               }
             };
             reader.readAsDataURL(input.files[0]);
           }
         }

         // Add event listeners for image previews
         document.getElementById('profilePic')?.addEventListener('change', function() {
           previewImage(this, 'profilePreview', 'image_type');
         });

         document.getElementById('vehicleFront')?.addEventListener('change', function() {
           previewImage(this, 'vehicleFrontPreview');
         });

         document.getElementById('vehicleBack')?.addEventListener('change', function() {
           previewImage(this, 'vehicleBackPreview');
         });
       });
     </script>


     <script>
       // Update phone input with selected country code
       countryDropdown.addEventListener("change", function() {
         document.getElementById("phone").value = this.value + " ";
       });
     </script>
     <script>
       document.addEventListener("DOMContentLoaded", function() {
         console.log("Script loaded!");

         function previewImage(input, previewId) {
           console.log("File input changed:", input.files); // Debugging step

           if (input.files && input.files[0]) {
             const reader = new FileReader();
             reader.onload = function(e) {
               const preview = document.getElementById(previewId);
               if (preview) {
                 preview.src = e.target.result;
                 preview.style.display = "block"; // Ensure the image is visible
                 console.log("Preview updated for:", previewId); // Debugging step
               } else {
                 console.error("Preview element not found:", previewId);
               }
             };
             reader.readAsDataURL(input.files[0]);
           } else {
             console.error("No file selected.");
           }
         }

         // Attach event listeners to file inputs
         const fileInputs = [{
             id: "profilePic",
             previewId: "profilePreview"
           },
           {
             id: "vehicleFront",
             previewId: "vehicleFrontPreview"
           },
           {
             id: "vehicleBack",
             previewId: "vehicleBackPreview"
           }
         ];

         fileInputs.forEach(({
           id,
           previewId
         }) => {
           const inputElement = document.getElementById(id);
           if (inputElement) {
             inputElement.addEventListener("change", function() {
               previewImage(this, previewId);
             });
           } else {
             console.error("Input element not found:", id);
           }
         });
       });
     </script>
     <script>
       document.addEventListener("DOMContentLoaded", function() {
         console.log("Script loaded!");

         // Ensure categories is properly rendered as a JSON array in JavaScript
         const categories = <%- JSON.stringify(categories) %>;

         console.log("Categories Data:", categories);

         // Populate category dropdown dynamically
         const categoryDropdown = document.getElementById("category");

         if (categoryDropdown && Array.isArray(categories)) {
           categories.forEach(cat => {
             const option = document.createElement("option");
             option.value = cat.category_id;
             option.textContent = cat.cat_name;
             categoryDropdown.appendChild(option);
           });
           console.log("Category dropdown populated.");
         } else {
           console.error("Category dropdown not found or categories is not an array.");
         }
       });
     </script>



     <script>
       $(document).ready(function() {
         function getFlagEmoji(code) {
           return code.toUpperCase().replace(/./g, char =>
             String.fromCodePoint(127397 + char.charCodeAt())
           );
         }

fetch("/countryCode.json")
  .then(res => res.json())
  .then(data => {
    window.countryCodes = data; // Store globally
    const $select = $('#countryCode');
    if (!$select.length) {
      console.error("Dropdown element #countryCode not found.");
      return;
    }

    data.forEach(country => {
      const isSelected = country.id === '<%= country_code %>';
      const option = new Option(
        `${getFlagEmoji(country.code)} +${country.id} (${country.name})`,
        `+${country.id}`,
        isSelected,
        isSelected
      );
      option.dataset.iso = country.code;
      $select.append(option);
    });

    $select.select2({
      placeholder: "Country Code",
      width: 'resolve',
      templateSelection: function (data) {
        return data.id || '';
      }
    });
    
    // Set country code from server
    $select.val('+<%= country_code %>').trigger('change');
  })
  .catch(err => {
    console.error("Failed to load country codes:", err);
  });

       });
     </script>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    fetch('/admin/getcities')
      .then(res => res.json())
      .then(cities => {
        window.citiesData = cities.data; // Store for country code lookup
        initDropdowns(cities);
        
        // Set up city change handler AFTER citiesData is loaded
        $('#city_id').on('change', function() {
          const selectedCityId = $(this).val();
          
          console.log('City changed, ID:', selectedCityId);
          console.log('citiesData available:', !!window.citiesData);
          console.log('countryCodes available:', !!window.countryCodes);
          
          if (selectedCityId && window.citiesData && window.countryCodes) {
            const selectedCity = window.citiesData.find(c => c.city_id == selectedCityId);
            
            console.log('Selected city data:', selectedCity);
            
            if (selectedCity && selectedCity.country_code) {
              console.log('Looking for phone code:', selectedCity.country_code);
              
              const matchingCountry = window.countryCodes.find(c => c.id == selectedCity.country_code);
              
              console.log('Matching country found:', matchingCountry);
              
              if (matchingCountry) {
                const $countrySelect = $('#countryCode');
                const newValue = `+${matchingCountry.id}`;
                $countrySelect.val(newValue).trigger('change');
                console.log(`Auto-selected country code: ${newValue} for phone code ${selectedCity.country_code}`);
              } else {
                console.error('No matching country found for phone code:', selectedCity.country_code);
              }
            }
          }
        });
        
        // Trigger country code selection after city dropdown is ready
        setTimeout(() => {
          const $citySelect = $('#city_id');
          if ($citySelect.val()) {
            const selectedCityId = $citySelect.val();
            
            console.log('Initial load - City ID:', selectedCityId);
            console.log('citiesData:', window.citiesData);
            console.log('countryCodes:', window.countryCodes);
            
            const selectedCity = window.citiesData.find(c => c.city_id == selectedCityId);
            
            console.log('Found city:', selectedCity);
            
            if (selectedCity && selectedCity.country_code && window.countryCodes) {
              console.log('City country_code:', selectedCity.country_code);
              
              // country_code in DB is actually the phone code (61), not ISO code (AU)
              // Match by id field in countryCode.json
              const matchingCountry = window.countryCodes.find(c => c.id == selectedCity.country_code);
              
              console.log('Matching country:', matchingCountry);
              
              if (matchingCountry) {
                const $countrySelect = $('#countryCode');
                const newValue = `+${matchingCountry.id}`;
                $countrySelect.val(newValue).trigger('change');
                console.log(`Initial country code set to: ${newValue} for phone code ${selectedCity.country_code}`);
              } else {
                console.error('No matching country found for phone code:', selectedCity.country_code);
              }
            }
          }
        }, 600);
      });

    function initDropdowns(cities, selectedId = null) {
      const cityDropdown = document.getElementById('city_id');
      const userGroupId = <%= user.group_id %>;
      const userCityId = <%= user.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;
        cityDropdown.appendChild(option);
      });

      // For Corporate (group_id=6) or Company Manager (group_id=5), lock to their city
      if (userGroupId === 5 || userGroupId === 6) {
        cityDropdown.value = userCityId;
        cityDropdown.setAttribute("readonly", true);
        cityDropdown.style.pointerEvents = "none";
        cityDropdown.style.opacity = "0.7";
        cityDropdown.style.background = "#f3f4f6";
      }
      // If only one city, auto-select and disable
      else 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>



     <%- footer %>
