   <%- 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: 18px !important;
         padding-left: 6px !important;
       }

       #u_phone {
         width: 70% !important;
       }

       @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">
       <%- include('../../partials/utils/title.ejs', { title: "Edit Company" }) %>

       <% 
      const breadcrumbs = [
        { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
        { label: "Edit Company" }
      ];
    %>
       <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>

       <div class="card">
         <div class="card-header">
           <h6 class="mb-0">Edit Company</h6>
         </div>
         <div class="card-body">
           <form id="subAdminForm" enctype="multipart/form-data">
             <div class="row mb-3">
               <div class="col-md-6">
                 <label>First Name</label>
                 <input type="text" name="u_fname" class="form-control" value="<%- subAdmin.u_fname %>" />
               </div>
               <div class="col-md-6">
                 <label>Last Name</label>
                 <input type="text" name="u_lname" class="form-control" value="<%- subAdmin.u_lname %>" />
               </div>
             </div>

             <div class="row mb-3">
               <div class="col-md-6">
                 <label>Email</label>
                 <input type="email" name="u_email" class="form-control" value="<%- subAdmin.u_email %>" />
               </div>
               <div class="col-md-6">
                 <label>Phone</label>
                 <div class="input-group">
                   <select name="countryCode" id="countryCode" class="form-select" style="max-width: 130px;"></select>
                   <input type="text" name="u_phone" id="u_phone" class="form-control" value="<%- subAdmin.u_phone %>" />
                 </div>
               </div>
             </div>

             <div class="row mb-3">
               <div class="col-md-6">
                 <label>Password <small class="text-muted">(Leave blank to keep current password)</small></label>
                 <input type="password" name="password" class="form-control" placeholder="Enter new password to update" />
               </div>
               <div class="col-md-6">
                 <label>Commission (%)</label>
                 <input type="number" name="city_comm" class="form-control" step="0.01" min="0" max="100" value="<%- subAdmin.city_comm || '' %>" placeholder="Enter commission percentage" />
               </div>
               <div class="col-md-6" style="display: none;">
                 <label>Role</label>
                 <select name="group_id" class="form-control">
                   <% roles.forEach(role => { %>
                   <option value="<%= role.id %>" <%= subAdmin.group_id === role.id ? "selected" : "" %>><%= role.name %></option>
                   <% }) %>
                 </select>
               </div>
             </div>

             <div class="row mb-3">
               <div class="col-md-6">
                 <label>Street</label>
                 <input type="text" name="street" class="form-control" value="<%- subAdmin.u_street || '' %>" placeholder="Enter street address" />
               </div>
               <div class="col-md-6">
                 <label>Address</label>
                 <input type="text" name="address" class="form-control" value="<%- subAdmin.u_address || '' %>" placeholder="Enter address" />
               </div>
             </div>

             <div class="row mb-3">
               <div class="col-md-6">
                 <label>State</label>
                 <input type="text" name="state" class="form-control" value="<%- subAdmin.u_state || '' %>" placeholder="Enter state" />
               </div>
               <div class="col-md-6">
                 <label>Pin Code</label>
                 <input type="text" name="pin_code" class="form-control" value="<%- subAdmin.u_zip || '' %>" placeholder="Enter pin code" />
               </div>
             </div>

             <div class="row mb-3">
               <div class="col-md-6">
                 <label for="city_id" class="form-label">City</label>
                 <select name="city_id" class="form-control form-select" id="city_id">
                   <option value="">Loading cities...</option>
                 </select>
               </div>
               <div class="col-md-6">
                 <label>Status</label>
                 <select name="status" class="form-control">
                   <option value="1" <%= subAdmin.active == "1" ? "selected" : "" %>>Active</option>
                   <option value="0" <%= subAdmin.active == "0" ? "selected" : "" %>>Inactive</option>
                 </select>
               </div>
             </div>

             <div class="row mb-3">
               <div class="col-md-6">
                 <label for="profilePic" class="form-label">Profile Picture</label>
                 <input type="file" class="form-control" id="profilePic" name="profilePic" accept=".jpg, .jpeg, .png">
                 <small class="text-muted">Allowed: JPG, JPEG, PNG (Max 2MB). Leave empty to keep current picture.</small>
                 <% if (subAdmin.image_id) { %>
                   <img src="/img/category/images/<%= subAdmin.image_name || '' %>" class="img-thumbnail mt-2" width="100" alt="Current Profile" id="profilePreview">
                 <% } else { %>
                   <img src="" class="img-thumbnail mt-2" width="100" style="display: none;" alt="Profile Preview" id="profilePreview">
                 <% } %>
                 <small id="profilePicError" class="text-danger mt-1"></small>
               </div>
             </div>

             <div class="text-end">
               <button type="submit" class="btn btn-success">Update Company</button>
             </div>
           </form>
         </div>
       </div>
     </div>
   </main>
   <script>
     // Define form configuration
     const formConfig = {
       formId: "subAdminForm",
       fields: [{
           name: "u_fname",
           type: "text",
           required: true,
           messages: {
             required: "First name is required"
           }
         },
         {
           name: "u_lname",
           type: "text",
           required: true,
           messages: {
             required: "Last name is required"
           }
         },
         {
           name: "u_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: "u_phone",
           type: "phone",
           required: true,
           messages: {
             required: "Phone number is required",
             invalid: "Phone number must be 6-15 digits"
           }
         },
         {
           name: "password",
           type: "text",
           required: false,
           messages: {
             required: "Password is required"
           }
         },
         {
           name: "city_id",
           type: "select",
           required: true,
           messages: {
             required: "Please select city"
           }
         },
         {
           name: "city_comm",
           type: "number",
           required: true,
           messages: {
             required: "Commission is required",
             invalid: "Commission must be between 0 and 100"
           }
         },
       ]
     };
   </script>

   <script src="/js/validator/validation.js"></script>
   <script>
     const form = document.getElementById("subAdminForm");
     const formValidator = setupFormValidation(
       formConfig.formId,
       formConfig.fields
     );

     // Profile picture validation
     const profilePicInput = document.getElementById('profilePic');
     if (profilePicInput) {
       const profilePicError = document.getElementById('profilePicError');
       const preview = document.getElementById('profilePreview');

       profilePicInput.addEventListener('change', function() {
         const file = this.files[0];
         profilePicError.textContent = '';

         if (file) {
           const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];
           if (!validTypes.includes(file.type)) {
             profilePicError.textContent = 'Only JPG, JPEG, PNG images are allowed';
             this.value = '';
             if (!preview.src || preview.src.includes('blob:')) {
               preview.style.display = 'none';
             }
           } else if (file.size > 2 * 1024 * 1024) { // 2MB
             profilePicError.textContent = 'Image size must be less than 2MB';
             this.value = '';
             if (!preview.src || preview.src.includes('blob:')) {
               preview.style.display = 'none';
             }
           } else {
             // Show preview
             const reader = new FileReader();
             reader.onload = function(e) {
               preview.src = e.target.result;
               preview.style.display = 'block';
             };
             reader.readAsDataURL(file);
           }
         }
       });
     }

     form.addEventListener("submit", async (e) => {
       e.preventDefault();
       // Validate form
       if (!formValidator.validateForm()) {
         console.log('Form validation failed');
         return;
       }
       
       const formData = new FormData(form);

       try {
         const res = await fetch("/admin/update-sub-admin/<%= subAdmin.user_id %>", {
           method: "POST",
           body: formData, // Send FormData directly for file upload
         });

         const result = await res.json();

         if (result.success) {
           Swal.fire({
             icon: "success",
             title: "Company updated successfully!",
             toast: true,
             position: "top-end",
             showConfirmButton: false,
             timer: 3000,
           });
         } else {
           throw new Error(result.message || "Something went wrong");
         }
       } catch (err) {
         Swal.fire({
           icon: "error",
           title: "Error",
           text: err.message || "Failed to update company.",
         });
       }
     });
   </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 => {
           const $select = $('#countryCode');
           if (!$select.length) {
             console.error("Dropdown element #countryCode not found.");
             return;
           }

           data.forEach(country => {
             const option = new Option(
               `${getFlagEmoji(country.code)} +${country.id} (${country.name})`,
               `+${country.id}`,
               false,
               `+${country.id}` === "<%- subAdmin.c_code %>" // preselect match
             );
             $select.append(option);
           });

           $select.select2({
             dropdownParent: $('#countryCode').parent(),
             width: '130px',
             minimumResultsForSearch: Infinity,
             templateSelection: function(data) {
               return data.id || '';
             }
           });

           $select.val("<%- subAdmin.c_code %>").trigger('change');
         })
         .catch(err => {
           console.error("Failed to load country codes:", err);
         });
     });
   </script>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const savedCityId = "<%= subAdmin.city_id %>"; // user's assigned city

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

      function initDropdowns(cities, selectedId) {
        const cityDropdown = document.getElementById('city_id');
        const userGroupId = <%= subAdmin.group_id %>;
        const userCityId = <%= subAdmin.city_id %>;

        cityDropdown.innerHTML = '<option value="">Select City</option>';

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

          // Preselect if matching user's city
          if (String(city.city_id) === String(selectedId)) {
            option.selected = true;
          }

          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 %>