<script>
  const IMAGE_FOLDER_PATH = "<%= IMAGE_FOLDER_PATH %>";
  const formJson = <%- JSON.stringify(formJson) %>;

  // Keys from existing uploaded assets that may not be in the city JSON (legacy docs)
  const uploadedAssetTypes = <%- JSON.stringify(
    [...new Set((assets || []).map(a => a.asset_type))].map(key => ({
      key,
      displayName: (assets.find(a => a.asset_type === key)?.title) || key.replace(/_/g, ' ')
    }))
  ) %>;
</script>
<style>
  .input-group {
    transition: all 0.2s ease-in-out;
  }

  .input-group:hover {
    box-shadow: 0 0 6px rgba(0, 0, 0, 0.1);
  }

  .uploadLabel {
    white-space: nowrap;
  }

  button.btn-danger.rounded-circle {
    width: 40px;
    height: 28px;
    font-size: 16px;
    line-height: 16px;
  }

  .closemodel {
    background-color: rgb(110, 2, 2) !important;
  }

  .form-select.border-danger,
  .form-control.border-danger {
    border-color: #dc3545 !important;
  }

  .error-message {
    font-size: 0.75rem;
    margin-top: 2px;
    position: absolute;
  }

  .bt-minus {
    width: 135px;
    height: 28px;
    font-size: 16px;
    line-height: 16px;
    padding-inline: 0px !important;
  }

  /* button.btn-danger.rounded-circle{
  color: rgb(110, 2, 2);
} */
</style>
<div class="w-full bg-white rounded-lg shadow-md p-6" style="padding: 20px !important;">
  <div class="border-b pb-3 mb-6 flex items-center justify-between">
    <h4 class="text-lg font-semibold text-gray-700">
      Driver Assets
    </h4>
  </div>

  <!-- Upload Form Section -->
  <!-- Upload Section -->
  <div class="card shadow-sm border-0 p-4 mb-4 bg-light" style="padding-inline: 20px !important;">
    <h6 class="fw-bold text-secondary mb-3">&nbsp;</h6>

    <!-- Dynamic Input Rows -->
    <div id="inputContainer" class="d-flex flex-column gap-3"></div>

    <!-- Buttons (bottom-right) -->
    <div class="d-flex justify-content-end mt-3 gap-2">
      <button id="uploadBtn" type="button" class="btn btn-success px-4" onclick="validateAndSubmit()">Upload</button>
      <button type="button" class="btn btn-success px-4" onclick="addInput()">Add More</button>
    </div>
  </div>

  <!-- Template for Rows -->
  <template id="inputTemplate">
    <div class="row align-items-end g-3 border rounded bg-white p-3 position-relative input-group">

      <!-- Remove Row -->
      <button type="button" class="btn shadow btn-danger" style="padding-block: 6px !important; padding-inline: 10px !important; width: 40px; position: absolute; top: 15px; right: 15px; z-index: 10;" onclick="removeInputGroup(this)">
        <i class="fas fa-trash"></i>
      </button>

      <!-- Select Doc -->
      <div class="col-12 col-lg-3" style="padding-bottom: 22px;">
        <label class="form-label fw-semibold">Select Doc <span class="text-danger">*</span></label>
        <select class="form-select documentType">
          <option value="">Select Document Type</option>
        </select>
        <small class="text-danger error-message d-none"></small>
      </div>

      <!-- Select Side -->
      <div class="col-12 col-lg-3" style="padding-bottom: 22px;">
        <label class="form-label fw-semibold">Select Side <span class="text-danger">*</span></label>
        <select class="form-select imageSide">
          <option value="">Select Side</option>
        </select>
        <small class="text-danger error-message d-none"></small>
      </div>

      <!-- Expiry Date -->
      <div class="col-12 col-lg-3 expiry-field-container d-none" style="padding-bottom: 22px;">
        <label class="form-label fw-semibold">Expire Date</label>
        <input type="date" class="form-control expirationDate">
        <small class="text-danger error-message d-none"></small>
      </div>

      <!-- Upload Image -->
      <div class="col-12 col-lg-3" style="padding-bottom: 22px;">
        <label class="form-label fw-semibold">Upload Image</label>
        <input type="file" accept="image/*" class="d-none fileUpload">
        <small class="text-danger error-message d-none" style="margin-left: -105px; margin-top: 80px;"></small>

        <button type="button" class="btn btn-primary w-100 uploadLabel">Choose File</button>

        <div class="image-preview-container d-none mt-2">
          <img class="imagePreview img-thumbnail" style="width:70px; height:70px; object-fit:cover; cursor:pointer;" onclick="openImageModal(this.src)">
          <button type="button" style="width: 40px; height: 28px; line-height: 1; padding: 0 !important; position: absolute; top: 80px; right: 15px; z-index: 10;" class="btn btn-sm btn-danger rounded-circle d-flex align-items-center justify-content-center bt-minus" onclick="removeUploadedImg(this)">×</button>
        </div>
      </div>
    </div>
  </template>



  <!-- Uploaded Documents Grid -->
  <div class="uploaded-section">
    <div class="flex items-center border-b pb-3 mb-6" style="padding-top: 20px !important;">
      <h5 class="font-semibold text-gray-700 text-md">Uploaded Documents</h5>
    </div>

<div id="uploadedDocuments" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6">
  <% if (assets && assets.length > 0) { %>
    <% assets.forEach(asset => { %>
      <div 
        class="bg-white border rounded-lg shadow-sm overflow-hidden group relative" 
        style="padding: 20px;" 
        data-asset-id="<%= asset.driver_asset_id %>"
      >
        <!-- Red Cross Delete Icon -->
        <button 
          class="delete-icon absolute top-2 right-2 text-white bg-red-600 hover:bg-red-700 rounded-full w-7 h-7 flex items-center justify-center shadow-md transition" 
          onclick="deleteAsset(this)"
          title="Delete Document"
        >
          &times;
        </button>

        <!-- Image or PDF Icon -->
        <% 
          const imagePath = asset.image.img_path;
          const isPDF = imagePath && imagePath.toLowerCase().endsWith('.pdf');
        %>
        
        <% if (isPDF) { %>
          <!-- PDF Icon -->
          <div class="w-full h-48 flex items-center justify-center bg-gray-100 cursor-pointer hover:bg-gray-200 transition" onclick="window.open('<%= imagePath.startsWith('http') ? imagePath : IMAGE_FOLDER_PATH + imagePath %>', '_blank')">
            <div class="text-center">
              <svg class="w-20 h-20 mx-auto text-red-600" fill="currentColor" viewBox="0 0 20 20">
                <path d="M4 18h12V6h-4V2H4v16zm-2 1V0h12l4 4v16H2v-1z"/>
                <path d="M7 14h6v1H7v-1zm0-2h6v1H7v-1zm0-2h6v1H7v-1z"/>
              </svg>
              <p class="mt-2 text-sm font-semibold text-gray-700">PDF Document</p>
              <p class="text-xs text-gray-500">Click to view</p>
            </div>
          </div>
        <% } else { %>
          <!-- Image -->
          <img 
            src="<%= imagePath.startsWith('http') ? imagePath : IMAGE_FOLDER_PATH + imagePath %>" 
            alt="Document" 
            class="w-full h-48 object-cover cursor-pointer hover:opacity-80 transition" 
            style="object-fit: contain;"
            onerror="this.onerror=null;this.src='/car.jpg';"
            onclick="openImageModal(this.src)"
          >
        <% } %>

        <!-- Info -->
        <div class="p-4">
          <h6 class="font-semibold text-gray-800 text-sm uppercase">
            <%= asset.title || asset.asset_type.replace(/_/g, ' ') %> (<%= asset.is_front ? 'Front' : 'Back' %>)
          </h6>

          <% if (asset.expire_date) { %>
            <p class="text-gray-600 text-sm mt-1">
              <strong>Expire Date:</strong> 
              <%= new Date(asset.expire_date).toLocaleDateString('en-GB') %>
            </p>
          <% } %>
        </div>
      </div>
    <% }) %>
  <% } else { %>
    <p class="text-gray-500 text-sm">No documents uploaded yet.</p>
  <% } %>
</div>

<!-- Optional CSS for consistent style -->
<style>
  .delete-icon {
    font-size: 18px;
    line-height: 1;
    cursor: pointer;
    transition: transform 0.2s ease, background-color 0.2s ease;
    color: rgb(110, 2, 2) !important;
    background-color: white !important;
  }

</style>

  </div>
</div>

<!-- Image Preview Modal -->
<div id="imageModal" class="fixed inset-0 bg-black bg-opacity-75 flex justify-center items-center z-50 hidden" onclick="handleOutsideClick(event)">
  <div class="relative">
    <!-- Close Button -->
    <button type="button" onclick="closeImageModal()" class="absolute closemodel -top-3 -right-3 font-bold rounded-full w-8 h-8 flex items-center justify-center shadow-lg z-50" style="border: 2px solid white;">
      ×
    </button>

    <!-- Image -->
    <img id="modalImage" src="" class="max-h-[90vh] max-w-[90vw] object-cover rounded-lg shadow-2xl border border-gray-300" alt="Preview">
  </div>
</div>


<script>
  let API_BASE_URL = "<%= API_BASE_URL %>";
  // Image Modal Logic
  // Function to open the modal with an image
  function openImageModal(imageUrl) {
    const modal = document.getElementById("imageModal");
    const modalImage = document.getElementById("modalImage");

    modalImage.src = imageUrl;
    modal.classList.remove("hidden");
  }

  // Function to close the modal
  function closeImageModal() {
    const modal = document.getElementById("imageModal");
    modal.classList.add("hidden");
  }

  // Function to close modal when clicking outside the image
  function handleOutsideClick(event) {
    const modalImage = document.getElementById("modalImage");
    if (!modalImage.contains(event.target) && !event.target.classList.contains("closemodel")) {
      closeImageModal();
    }
  }

  // Always start with 1 empty upload input (not prefilled)
  document.addEventListener('DOMContentLoaded', function() {
    const inputContainer = document.getElementById('inputContainer');
    const template = document.getElementById('inputTemplate');
    inputContainer.innerHTML = '';

    if (template) {
      const newGroup = template.content.firstElementChild.cloneNode(true);
      inputContainer.appendChild(newGroup);
      const docTypeSelect = newGroup.querySelector('.documentType');
      if (typeof populateDocumentTypeDropdown === 'function') {
        populateDocumentTypeDropdown(docTypeSelect);
      }
    }
  });
</script>


<script src="/js/validator/validation.js"></script>
<script>
  let removedAssetIds = [];
  let originalAssets = [];

  // Document configuration based on formJson
  const documentConfig = {};

  // Initialize document configuration (city JSON only)
  function initializeDocumentConfig() {
    formJson.forEach(doc => {
      const docType = doc.inputs.find(input => input.key !== 'expire_date')?.key;
      if (docType) {
        documentConfig[docType] = {
          hasExpiry: doc.inputs.some(input => input.key === 'expire_date'),
          hasFront: doc.inputs.some(input => input.type === 'ImageView' && input.is_front === "1"),
          hasBack: doc.inputs.some(input => input.type === 'ImageView' && input.is_front === "0")
        };
      }
    });
    console.log('Document configuration:', documentConfig);
  }

  // Extract document types from formJson (city JSON only)
  function getDocumentTypes() {
    const docTypes = [];
    const seenKeys = new Set();

    formJson.forEach(doc => {
      const imageInput = doc.inputs.find(input => input.type === 'ImageView');
      if (imageInput && imageInput.key && !seenKeys.has(imageInput.key)) {
        seenKeys.add(imageInput.key);
        docTypes.push({
          key: imageInput.key,
          displayName: doc.header?.value || imageInput.key
        });
      }
    });

    console.log('Extracted document types:', docTypes);
    return docTypes;
  }

  // Handle document type change - update image side options and expiry field
  function handleDocumentTypeChange(selectElement) {
    const container = selectElement.closest('.input-group');
    if (!container) return;

    const imageSideSelect = container.querySelector('.imageSide');
    const expiryContainer = container.querySelector('.expiry-field-container');
    const expiryInput = container.querySelector('.expirationDate');
    const expiryLabel = expiryContainer?.querySelector('label');

    const selectedDocType = selectElement.value;
    const config = documentConfig[selectedDocType];

    if (config && expiryContainer && expiryInput && expiryLabel) {
      // ✅ Update image side options dynamically
      updateImageSideOptions(imageSideSelect, config);

      // ✅ Update expiry field (use Bootstrap d-none, not hidden)
      if (config.hasExpiry) {
        expiryContainer.classList.remove('d-none');
        expiryContainer.classList.remove('hidden'); // ensure both removed
        expiryInput.required = true;
        expiryLabel.innerHTML = 'Expiration Date <span class="text-danger">*</span>';
      } else {
        expiryContainer.classList.add('d-none');
        expiryInput.required = false;
        expiryInput.value = ''; // clear old date
        expiryLabel.innerHTML = 'Expiration Date';
      }
    }
  }

  // Update image side options based on document configuration
  function updateImageSideOptions(selectElement, config) {
    if (!selectElement) return;

    const currentValue = selectElement.value;

    let options = '<option value="">Select Image Side</option>';

    if (config.hasFront) {
      options += '<option value="1">Front Image</option>';
    }

    if (config.hasBack) {
      options += '<option value="0">Back Image</option>';
    }

    selectElement.innerHTML = options;

    // Try to preserve the current value if it's still valid
    if (currentValue && selectElement.querySelector(`option[value="${currentValue}"]`)) {
      selectElement.value = currentValue;
    } else {
      selectElement.value = "";
    }
  }

  // Initialize existing asset with proper configuration
  function initializeExistingAsset(group, asset) {
    const docTypeSelect = group.querySelector('.documentType');
    const imageSideSelect = group.querySelector('.imageSide');
    const expiryContainer = group.querySelector('.expiry-field-container');
    const expiryInput = group.querySelector('.expirationDate');
    const expiryLabel = expiryContainer?.querySelector('label');

    const assetType = asset.asset_type || '';
    const imageSideValue = asset.is_front ? '1' : '0';
    const config = documentConfig[assetType];

    if (docTypeSelect) docTypeSelect.value = assetType;

    // Set image side options based on document configuration
    if (imageSideSelect && config) {
      let options = '<option value="">Select Image Side</option>';

      if (config.hasFront) {
        options += '<option value="1">Front Image</option>';
      }

      if (config.hasBack) {
        options += '<option value="0">Back Image</option>';
      }

      imageSideSelect.innerHTML = options;

      // Set the image side value after populating options
      if (imageSideValue && imageSideSelect.querySelector(`option[value="${imageSideValue}"]`)) {
        imageSideSelect.value = imageSideValue;
      }
    }

    // Set expiry field
    if (expiryInput && asset.expire_date) {
      expiryInput.value = asset.expire_date.split('T')[0];
    }

    // Update expiry field visibility
    if (expiryContainer && expiryInput && expiryLabel && config) {
      if (config.hasExpiry) {
        expiryContainer.classList.remove('hidden');
        expiryInput.required = true;
        expiryLabel.innerHTML = 'Expiration Date <span class="text-red-500">*</span>';
      } else {
        expiryContainer.classList.add('hidden');
        expiryInput.required = false;
        expiryLabel.innerHTML = 'Expiration Date';
      }
    }
  }

  // Populate document type dropdown options (display name cleaned)
  function populateDocumentTypeDropdown(selectElement) {
    if (!selectElement) return;

    const docTypes = getDocumentTypes();
    const defaultOption = '<option value="">Select Document Type</option>';

    let options = defaultOption;
    docTypes.forEach(docType => {
      // Use the displayName from the header value
      options += `<option value="${docType.key}">${docType.displayName}</option>`;
    });

    selectElement.innerHTML = options;
  }


  function showError(element, message) {
    if (!element) return;

    const container = element.closest('.flex.flex-col') || element.parentElement;
    if (!container) return;

    const errorElement = container.querySelector('.error-message');
    if (errorElement) {
      errorElement.textContent = message;
      errorElement.classList.remove('hidden');
      element.classList.add('border-red-500');
    }
  }

  function hideError(element) {
    if (!element) return;

    const container = element.closest('.flex.flex-col') || element.parentElement;
    if (!container) return;

    const errorElement = container.querySelector('.error-message');
    if (errorElement) {
      errorElement.classList.add('hidden');
      element.classList.remove('border-red-500');
    }
  }


  function previewImage(event, input) {
    const file = input.files[0];
    const container = input.closest('.input-group');
    if (!container) return;

    const previewWrapper = container.querySelector('.image-preview-container');
    const previewImg = container.querySelector('.imagePreview');
    const uploadBtn = container.querySelector('.uploadLabel');

    if (file) {
      // Create temporary image URL
      const imageUrl = URL.createObjectURL(file);
      previewImg.src = imageUrl;

      // ✅ Show preview thumbnail
      previewWrapper.classList.remove('d-none');
      previewWrapper.classList.remove('hidden'); // in case older logic used hidden
      uploadBtn.style.display = "none";

      // ✅ Update label with selected file name
      const fileName = file.name;
      uploadBtn.textContent = `Selected: ${fileName}`;

      // ✅ Clear validation error if any
      hideError(input);
    }
  }


  async function deleteAssetFromServer(assetId) {
    const driverId = new URL(window.location.href).pathname.split('/').pop();
     const apiKey = "<%= api_key %>";

    try {
      $("#loader").show();

      const response = await fetch('/admin/upload-driver-docs', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          driver_id: driverId,
          removed_asset_ids: [assetId],
          api_key: apiKey
        })
      });

      $("#loader").hide();

      if (!response.ok) {
        throw new Error('Failed to delete asset from server');
      }

      return true;
    } catch (error) {
      $("#loader").hide();
      console.error('Error deleting asset:', error);
      return false;
    }
  }

  function removeUploadedImg(button) {
    Swal.fire({
      icon: 'warning',
      title: 'Are you sure?',
      text: 'Do you want to remove this image?',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, remove it!'
    }).then((result) => {
      if (result.isConfirmed) {
        const container = button.closest('.input-group');
        if (!container) return;

        const assetId = container.getAttribute('data-asset-id');

        // Only track for removal if it's an existing asset
        if (assetId) {
          removedAssetIds.push(assetId);
        }

        const fileInput = container.querySelector('.fileUpload');
        const previewImg = container.querySelector('.imagePreview');
        const previewWrapper = container.querySelector('.image-preview-container');
        const uploadBtn = container.querySelector('.uploadLabel');

        if (fileInput) fileInput.value = "";
        if (previewImg) previewImg.src = "";
        if (previewWrapper) {
          previewWrapper.classList.add('hidden');
          previewWrapper.classList.add('d-none');
        }
        if (uploadBtn) {
          uploadBtn.style.display = "block";
          uploadBtn.textContent = "Choose File";
        }
      }
    });
  }

  async function deleteAsset(button) {
    const container = button.closest('.bg-white.border.rounded-lg.shadow-sm');
    if (!container) return;

    const assetId = container.getAttribute('data-asset-id');
    if (!assetId) {
      console.warn("No asset ID found for deletion.");
      return;
    }

    Swal.fire({
      icon: 'warning',
      title: 'Are you sure?',
      text: 'Do you want to delete this document? This action cannot be undone.',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, delete it!'
    }).then(async (result) => {
      if (result.isConfirmed) {
        const success = await deleteAssetFromServer(assetId);

        if (success) {
          container.remove();
          Swal.fire({
            icon: 'success',
            title: 'Deleted!',
            text: 'The document has been removed.',
            timer: 1500,
            showConfirmButton: false
          });
        } else {
          Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Failed to delete the document. Please try again.'
          });
        }
      }
    });
  }


  function addInput() {
    const template = document.getElementById('inputTemplate');
    const container = document.getElementById('inputContainer');
    if (!template || !container) return;

    const newGroup = template.content.firstElementChild.cloneNode(true);

    const fileInput = newGroup.querySelector('.fileUpload');
    const uploadBtn = newGroup.querySelector('.uploadLabel');
    const docTypeSelect = newGroup.querySelector('.documentType');
    const imageSideSelect = newGroup.querySelector('.imageSide');
    const expiryContainer = newGroup.querySelector('.expiry-field-container');

    // Hide expiry by default
    expiryContainer?.classList.add('d-none');
    populateDocumentTypeDropdown(docTypeSelect);

    // Handle doc type change
    docTypeSelect.addEventListener('change', function() {
      handleDocumentTypeChange(this);
    });

    // Trigger file input
    uploadBtn.addEventListener('click', function() {
      fileInput.click();
    });

    // Preview image
    fileInput.addEventListener('change', function(e) {
      previewImage(e, fileInput);
    });

    imageSideSelect.innerHTML = '<option value="">Select Side</option>';

    // ✅ Hide remove button for the first field only
    const removeBtn = newGroup.querySelector('button.btn-danger');
    if (container.children.length === 0) {
      // This is the first field
      removeBtn.style.display = 'none';
    } else {
      removeBtn.style.display = 'block';
    }

    container.appendChild(newGroup);
  }




  // ✅ Updated validation to optionally skip showing errors
  function validateInputGroup(group, showErrors = true) {
    if (!group) return false;
    let isValid = true;

    const docType = group.querySelector('.documentType');
    const imageSide = group.querySelector('.imageSide');
    const expirationDate = group.querySelector('.expirationDate');
    const fileInput = group.querySelector('.fileUpload');
    const expiryContainer = group.querySelector('.expiry-field-container');
    const previewWrapper = group.querySelector('.image-preview-container');

    // If this group doesn't have upload fields, skip
    if (!docType || !imageSide || !fileInput) return true;

    function setError(el, msg) {
      const err = el?.closest('.col-12, .col-lg-3')?.querySelector('.error-message');
      if (showErrors && err) {
        err.textContent = msg;
        err.classList.remove('d-none');
        el.classList.add('border-danger');
      }
    }

    function clearError(el) {
      const err = el?.closest('.col-12, .col-lg-3')?.querySelector('.error-message');
      if (err) {
        err.textContent = '';
        err.classList.add('d-none');
        el.classList.remove('border-danger');
      }
    }

    // Document Type
    if (!docType.value.trim()) {
      setError(docType, 'Document type is required');
      isValid = false;
    } else clearError(docType);

    // Image Side
    if (!imageSide.value.trim()) {
      setError(imageSide, 'Image side is required');
      isValid = false;
    } else clearError(imageSide);

    // Expiry (only if visible)
    const expiryVisible =
      expiryContainer &&
      !expiryContainer.classList.contains('d-none') &&
      !expiryContainer.classList.contains('hidden');

    if (expiryVisible && !expirationDate?.value.trim()) {
      setError(expirationDate, 'Expiration date is required');
      isValid = false;
    } else clearError(expirationDate);

    // Image check
    const hasFile = fileInput?.files?.length > 0;
    const hasPreview = previewWrapper && !previewWrapper.classList.contains('d-none');

    if (!hasFile && !hasPreview) {
      setError(fileInput, 'Image is required');
      isValid = false;
    } else clearError(fileInput);

    return isValid;
  }

  // Remove a field row
  function removeInputGroup(button) {
    const group = button.closest('.input-group');
    if (group) group.remove();
  }


  // 🗑️ Remove input row
  function removeInputGroup(button) {
    const container = button.closest('.input-group');
    if (container) container.remove();
  }

  function getImageType(file) {
    const type = file.type.split('/').pop();
    return type === 'jpeg' ? 'jpg' : type;
  }

  function fileToBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result.split(',')[1]);
      reader.onerror = error => reject(error);
    });
  }

  function validateAndSubmit() {
    const allValid = validateAllInputs();
    if (!allValid) {
      // Errors are already shown inline
      return;
    }

    submitData();
  }

  function validateAllInputs() {
    const inputGroups = document.querySelectorAll('#inputContainer .input-group');
    if (inputGroups.length === 0) {
      Swal.fire({
        icon: 'warning',
        title: 'No Documents Added',
        text: 'Please add at least one document before uploading.'
      });
      return false;
    }

    let allValid = true;
    inputGroups.forEach(group => {
      const valid = validateInputGroup(group, true);
      if (!valid) allValid = false;
    });
    return allValid;
  }


  async function imageUrlToBase64(url) {
    try {
      const response = await fetch(url);
      const blob = await response.blob();
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => {
          // Remove the data:image/...;base64, prefix
          const base64 = reader.result.split(',')[1];
          resolve(base64);
        };
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      });
    } catch (error) {
      console.error('Error converting image URL to base64:', error);
      throw error;
    }
  }

  // Get image type from URL or file
  function getImageTypeFromSource(file, imageUrl) {
    if (file) {
      const type = file.type.split('/').pop();
      return type === 'jpeg' ? 'jpg' : type;
    } else if (imageUrl) {
      // Extract extension from URL
      const url = new URL(imageUrl);
      const pathname = url.pathname;
      const extension = pathname.split('.').pop().toLowerCase();
      return extension === 'jpeg' ? 'jpg' : extension;
    }
    return '';
  }

  async function submitData() {
    const driverId = new URL(window.location.href).pathname.split('/').pop();
    if (!driverId) {
      Swal.fire({
        icon: 'warning',
        title: 'Driver not selected',
        text: 'Please select a driver before uploading.'
      });
      return;
    }

    $("#loader").show();

    const inputGroups = document.querySelectorAll('.input-group');
    const apiKey = "<%= api_key %> ";
    let hasChanges = false;

    // First check if we have any changes at all
    const currentState = Array.from(inputGroups).map(group => {
      const assetId = group.getAttribute('data-asset-id') || '';
      const docType = group.querySelector('.documentType')?.value;
      const imageSide = group.querySelector('.imageSide')?.value;
      const expirationDate = group.querySelector('.expirationDate')?.value || '';
      const fileInput = group.querySelector('.fileUpload');
      const previewImg = group.querySelector('.imagePreview');
      const expiryContainer = group.querySelector('.expiry-field-container');

      const hasNewFile = fileInput?.files?.length > 0;
      const hasPreviewImage = previewImg?.src && previewImg.src !== '';
      const isExternalUrl = previewImg?.src && (previewImg.src.startsWith('http') || previewImg.src.startsWith(IMAGE_FOLDER_PATH));
      const isExpiryVisible = expiryContainer && !expiryContainer.classList.contains('hidden');

      return {
        assetId,
        docType,
        imageSide,
        expirationDate: isExpiryVisible ? expirationDate : '', // Only include if visible
        hasNewFile,
        hasPreviewImage,
        isExternalUrl,
        imageUrl: previewImg?.src,
        groupElement: group,
        isExpiryVisible
      };
    });

    // Check for removed assets
    if (removedAssetIds.length > 0) {
      hasChanges = true;
      console.log('Changes detected: removed assets', removedAssetIds);
    }

    // Check for modified or new assets
    if (!hasChanges) {
      for (const currentGroup of currentState) {
        if (!currentGroup.assetId) {
          // New asset added
          hasChanges = true;
          console.log('Changes detected: new asset added');
          break;
        }

        const originalAsset = originalAssets.find(a => a.driver_asset_id === currentGroup.assetId);
        if (!originalAsset) {
          hasChanges = true;
          console.log('Changes detected: asset not found in originals', currentGroup.assetId);
          break;
        }

        // Use direct key comparison from JSON
        const originalDocType = originalAsset.asset_type || '';
        const originalImageSide = originalAsset.is_front ? '1' : '0';
        const originalExpireDate = originalAsset.expire_date ? originalAsset.expire_date.split('T')[0] : '';

        // Check if any field was modified
        const isDocTypeChanged = originalDocType !== currentGroup.docType;
        const isImageSideChanged = originalImageSide !== currentGroup.imageSide;
        const isExpireDateChanged = originalExpireDate !== currentGroup.expirationDate;
        const hasImageChanges = currentGroup.hasNewFile || (currentGroup.hasPreviewImage && currentGroup.isExternalUrl);

        if (isDocTypeChanged || isImageSideChanged || isExpireDateChanged || hasImageChanges) {
          hasChanges = true;
          console.log('Changes detected for asset:', currentGroup.assetId, {
            isDocTypeChanged,
            isImageSideChanged,
            isExpireDateChanged,
            hasImageChanges
          });
          break;
        }
      }
    }

    if (!hasChanges) {
      $("#loader").hide();
      Swal.fire({
        icon: 'info',
        title: 'No changes detected',
        text: 'No modifications were made to the documents.'
      });
      return;
    }

    console.log('Proceeding with changes...');

    // Process each asset individually
    for (const currentGroup of currentState) {
      const group = currentGroup.groupElement;
      const docTypeEl = group.querySelector('.documentType');
      const imageSideEl = group.querySelector('.imageSide');
      const fileInput = group.querySelector('.fileUpload');
      const expirationDate = currentGroup.expirationDate; // Use the processed expiration date
      const assetId = group.getAttribute('data-asset-id') || '';
      const previewImg = group.querySelector('.imagePreview');
      const expiryContainer = group.querySelector('.expiry-field-container');
      const isExpiryVisible = expiryContainer && !expiryContainer.classList.contains('hidden');

      if (!docTypeEl || !imageSideEl || !fileInput) continue;

      const assetType = docTypeEl.value;
      const isFront = imageSideEl.value;
      const hasNewFile = fileInput.files.length > 0;
      const hasPreviewImage = previewImg.src && previewImg.src !== '';
      const isExternalUrl = previewImg.src && (previewImg.src.startsWith('http') || previewImg.src.startsWith(IMAGE_FOLDER_PATH));

      // For existing assets, check if we need to process this group
      if (assetId) {
        const originalAsset = originalAssets.find(a => a.driver_asset_id === assetId);
        if (originalAsset) {

          console.log('Checking existing asset for changes:', originalAsset);
          const originalDocType = originalAsset.asset_type || '';
          const originalImageSide = originalAsset.is_front ? '1' : '0';
          const originalExpireDate = originalAsset.expire_date ? originalAsset.expire_date.split('T')[0] : '';

          const isDocTypeChanged = originalDocType !== assetType;
          const isImageSideChanged = originalImageSide !== isFront;
          const isExpireDateChanged = originalExpireDate !== expirationDate;
          const hasImageChanges = hasNewFile || (hasPreviewImage && isExternalUrl);

          // Skip if no changes at all
          if (!isDocTypeChanged && !isImageSideChanged && !isExpireDateChanged && !hasImageChanges) {
            console.log('Skipping unchanged asset:', assetId);
            continue;
          }

          console.log('Processing changed asset:', assetId, {
            isDocTypeChanged,
            isImageSideChanged,
            isExpireDateChanged,
            hasImageChanges
          });
        }
      }

      // Skip if no file and no preview image for new assets
      if (!assetId && !hasNewFile && !hasPreviewImage) {
        console.log('Skipping new asset with no image');
        continue;
      }

      try {
        let base64Image = '';
        let imageType = '';

        if (hasNewFile) {
          // Handle file upload
          const file = fileInput.files[0];
          imageType = getImageTypeFromSource(file, null);
          base64Image = await fileToBase64(file);
          console.log('Processing new file for:', assetType);
        } else if (hasPreviewImage && isExternalUrl) {
          // Handle URL-based images
          console.log('Converting URL to base64 for:', assetType, 'URL:', previewImg.src);
          base64Image = await imageUrlToBase64(previewImg.src);
          imageType = getImageTypeFromSource(null, previewImg.src);
          console.log('URL image processed, type:', imageType);
        } else if (hasPreviewImage) {
          // Handle other preview images (blob URLs, etc.)
          console.log('Has preview image but not external URL:', previewImg.src);
        }

        // For existing assets with only data changes (no image changes), we still need to submit
        // but without image data if the image hasn't changed
        const needsImageData = hasNewFile || (hasPreviewImage && isExternalUrl);

        if (needsImageData && !imageType) {
          Swal.fire({
            icon: 'warning',
            title: 'Missing Image Type',
            text: 'Could not determine image type. Please check the image source.',
          });
          $("#loader").hide();
          return;
        }

        if (needsImageData && !base64Image) {
          Swal.fire({
            icon: 'warning',
            title: 'Missing Image Data',
            text: 'Could not process the image. Please try again.',
          });
          $("#loader").hide();
          return;
        }

        const payload = {
          driver_id: driverId,
          asset_type: assetType,
          is_front: isFront,
          api_key: apiKey,
          image_type: imageType
        };

        // Only include expiry date if the field is visible
        if (isExpiryVisible && expirationDate) {
          payload.expire_date = expirationDate;
        }

        // Include image data only if we have it
        if (base64Image) {
          payload.driver_image = base64Image;
        }

        if (assetId) {
          payload.driver_asset_id = assetId;
        }

        console.log('Submitting payload for:', assetType, {
          hasImage: !!base64Image,
          hasExpiry: isExpiryVisible,
          assetId: assetId || 'new'
        });

        const response = await fetch(`${API_BASE_URL}driverassetapi/adddriverasset`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(payload)
        });

        const responseText = await response.json();

        if (responseText.resDecrypt.code !== 200) {
          throw new Error('Upload failed: ' + (responseText.resDecrypt.message || 'Unknown error'));
        }

        console.log('Successfully submitted:', assetType);

      } catch (err) {
        $("#loader").hide();
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: `Failed to upload ${assetType}: ${err.message}`
        });
        return;
      }
    }

    $("#loader").hide();

    // Notify driver about asset update
    try {
      await fetch(`${API_BASE_URL}push/sendNotification`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          driver_id: driverId,
          message: 'Your documents have been updated by the admin. Please review your profile.',
        }),
      });
    } catch (notifErr) {
      console.error('Asset notification error:', notifErr);
    }

    Swal.fire({
      icon: 'success',
      title: 'Success',
      text: 'Documents updated successfully!'
    }).then(() => {
      window.location.reload();
    });
  }

  // Initialize the page with existing assets
  document.addEventListener('DOMContentLoaded', function() {
    initializeDocumentConfig();

    const inputContainer = document.getElementById('inputContainer');
    const template = document.getElementById('inputTemplate');
    inputContainer.innerHTML = '';

    if (template) {
      const newGroup = template.content.firstElementChild.cloneNode(true);
      inputContainer.appendChild(newGroup);

      const docTypeSelect = newGroup.querySelector('.documentType');
      const fileInput = newGroup.querySelector('.fileUpload');
      const uploadBtn = newGroup.querySelector('.uploadLabel');
      const imageSideSelect = newGroup.querySelector('.imageSide');

      populateDocumentTypeDropdown(docTypeSelect);

      docTypeSelect.addEventListener('change', function() {
        handleDocumentTypeChange(this);
      });

      uploadBtn.addEventListener('click', function() {
        fileInput.click();
      });

      fileInput.addEventListener('change', function(e) {
        previewImage(e, fileInput);
      });

      imageSideSelect.innerHTML = '<option value="">Select Side</option>';

      // ✅ Hide remove button for the first input only
      const removeBtn = newGroup.querySelector('button.btn-danger');
      if (removeBtn) removeBtn.style.display = 'none';
    }
  });

  // Show loader on any AJAX request start
  $(document).ready(function() {
    $(document).ajaxStart(function() {
      $("#loader").show();
    });

    $(document).ajaxStop(function() {
      $("#loader").hide();
    });
  });
</script>
<script>
  // ✅ Attach live validation to every field dynamically
  function attachValidationEvents(group) {
    const inputs = [
      group.querySelector('.documentType'),
      group.querySelector('.imageSide'),
      group.querySelector('.expirationDate'),
      group.querySelector('.fileUpload')
    ];

    inputs.forEach(input => {
      if (!input) return;
      input.addEventListener('change', () => {
        validateInputGroup(group, true); // revalidate on change
      });
    });
  }

  // Attach to new and existing rows
  document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('#inputContainer .input-group').forEach(attachValidationEvents);
  });


  // ✅ Dynamically enable/disable Upload button
  function checkAllGroupsValid() {
    const uploadBtn = document.getElementById('uploadBtn');
    if (!uploadBtn) return;

    const groups = document.querySelectorAll('.input-group');
    let allValid = true;
    groups.forEach(group => {
      if (!validateInputGroup(group, false)) allValid = false;
    });

    uploadBtn.disabled = !allValid;
  }



  // ✅ Attach validation when new input group is added
  const originalAddInput = addInput;
  addInput = function() {
    originalAddInput();
    const groups = document.querySelectorAll('.input-group');
    attachValidationEvents(groups[groups.length - 1]);
  };

  // ✅ Also attach validation to the first input on page load
  document.addEventListener('DOMContentLoaded', () => {
    const firstGroup = document.querySelector('.input-group');
    if (firstGroup) attachValidationEvents(firstGroup);
  });
</script>