<div class="flex min-h-screen">
  <!-- Sidebar -->
  <div class="w-64 bg-white p-4">
    <div class="flex items-center justify-between px-6 py-4">
      <span class="text-xl font-semibold">ToyHub</span>
    </div>
    <nav>
      <ul class="space-y-2">
        <li>
          <a href="/admin"
            class="flex items-center p-2 text-gray-700 hover:shadow-xl rounded-lg hover:bg-gray-100 transition-all">Dashboard</a>
        </li>
        <li>
          <a href="/admin/products"
            class="flex items-center rounded hover:shadow-xl hover:bg-gray-100 transition-all  p-2 text-gray-700">All
            Products</a>
        </li>
        <li>
          <a href="/admin/orders"
            class="flex items-center p-2 text-gray-700 hover:shadow-xl rounded-lg hover:bg-gray-100 transition-all">Order
            List</a>
        </li>
        <li>
          <a href="/admin/users"
            class="flex items-center p-2 text-gray-700 hover:shadow-xl rounded-lg hover:bg-gray-100 transition-all">User
            List</a>
        </li>
        <li>
          <a href="/admin/category"
            class="flex items-center p-2 text-gray-700 hover:shadow-xl rounded-lg hover:bg-gray-100 transition-all">
            Product Details</a>
        </li>
        <li>
          <a href="/admin/addProduct" class="flex items-center bg-primary rounded transition-all  p-2 text-gray-700">
            <span class="ml-3">Add Product</span></a>
        </li>
        <li>
          <a href="/admin/banner"
            class="flex items-center rounded hover:bg-gray-100 hover:shadow-xl transition-all  p-2 text-gray-700">Banner</a>
        </li>
      </ul>
    </nav>
    <div class="mt-6">
      <h3 class="text-sm font-semibold ">Categories</h3>
      <hr>
      <ul class="mt-2 space-y-2">
        <li>
          <a href="#" class="flex items-center p-2 hover:bg-gray-200 transition-all rounded text-gray-700">Category
            1</a>
        </li>
        <li>
          <a href="#" class="flex items-center p-2 hover:bg-gray-200 transition-all rounded text-gray-700">Category
            2</a>
        </li>
        <li>
          <a href="#" class="flex items-center p-2 hover:bg-gray-200 transition-all rounded  text-gray-700">Category
            3</a>
        </li>
      </ul>
      <ul>
        <li>
          <form action="/admin/logout" method="POST">
            <a href="/admin/logout">
              <button type="submit"
                class="flex items-center p-2 hover:bg-gray-200 mt-3 transition-all rounded  ">Logout</button>
            </a>
          </form>
        </li>
      </ul>
    </div>
  </div>
  <!-- Content Area -->
  <div class="flex-1 p-8">
    <h1 class="text-2xl font-semibold">Add Product</h1>
    <p class="text-sm text-gray-500 mb-8">Home &gt; All Products &gt; Add New Product</p>
    <!-- Form container -->
    <div class="bg-white p-8 rounded-lg shadow-md">
      <form id="productForm" class="w-3/4 grid grid-cols-2 gap-6" method="POST" action="/admin/addProduct"
        enctype="multipart/form-data">  
        <!-- Product Title -->
        <div class="col-span-2">
          <label class="block text-sm font-medium text-gray-700" for="product-title">Product Title</label>
          <input type="text" id="product-title" name="title" class="mt-1 p-2 w-full border rounded-md"
            placeholder="Type name here" value="">
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.titleError %>
            </p>
            <% } %>
              <p class="text-red-500 text-sm mt-1">
                <%= locals.duplicateError %>
              </p>
        </div>
        <!-- Description 1 -->
        <div class="col-span-2">
          <label class="block text-sm font-medium text-gray-700" for="description1">Description 1</label>
          <textarea id="description1" name="description1" class="mt-1 p-2 w-full border rounded-md"
            placeholder="Type Description here" value="">This is a action toy</textarea>
          <% if(locals.error) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.description1Error %>
            </p>
            <% } %>
        </div>
        <!-- Description 2 -->
        <div class="col-span-2">
          <label class="block text-sm font-medium text-gray-700" for="description2">Description 2</label>
          <textarea id="description2" name="description2" class="mt-1 p-2 w-full border rounded-md"
            placeholder="Type Description here" value="">This toy is good for use</textarea>
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.description2Error %>
            </p>
            <% } %>
        </div>
        <!-- Category -->
        <div>
          <label class="block text-sm font-medium text-gray-700" for="category">Category</label>
          <select id="category" name="category" class="mt-1 p-2 w-full border rounded-md">
            <option value="">Select a Category</option>
            <% if(locals.categories) { %>
              <% categories.forEach(category=> { %> <option value="<%= category._id %>">
                  <%= category.name %>
                </option>
                <% }) %>
                  <% } else { %>
                    <option value="">No categories available</option>
                    <% } %>
          </select>
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.categoryError %>
            </p>
            <% } %>
        </div>
        <!-- Warning -->
        <div>
          <label class="block text-sm font-medium text-gray-700" for="warning">Warning</label>
          <input type="text" id="warning" name="warning" class="mt-1 p-2 w-full border rounded-md"
            placeholder="Type Warning here" value="Not recommented kids below 3">
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.warningError %>
            </p>
            <% } %>
        </div>
        <!-- Type -->
        <div>
          <label class="block text-sm font-medium text-gray-700" for="type">Type</label>
          <input type="text" id="type" name="type" class="mt-1 p-2 w-full border rounded-md"
            placeholder="Enter the type" value="Toy">
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.typeError %>
            </p>
            <% } %>
        </div>
        <!-- Color -->
        <div>
          <label class="block text-sm font-medium text-gray-700" for="color">Color</label>
          <input type="text" id="color" name="color" class="mt-1 p-2 w-full border rounded-md" placeholder="Color"
            value="Red">
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.colorError %>
            </p>
            <% } %>
        </div>
        <!-- Weight -->
        <div>
          <label class="block text-sm font-medium text-gray-700" for="weight">Weight</label>
          <input type="text" id="weight" name="weight" class="mt-1 p-2 w-full border rounded-md"
            placeholder="Enter the weight" value="100">
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.weightError %>
            </p>
            <% } %>
        </div>
        <!-- Discount -->
        <div>
          <label class="block text-sm font-medium text-gray-700" for="discount">Discount</label>
          <input type="text" id="discount" name="discount" class="mt-1 p-2 w-full border rounded-md" placeholder="1258"
            value="20">
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.discountError %>
            </p>
            <% } %>
        </div>
        <!-- SKU -->
        <div>
          <label class="block text-sm font-medium text-gray-700" for="sku">SKU</label>
          <input type="text" id="sku" name="sku" class="mt-1 p-2 w-full border rounded-md" placeholder="Fox-3983"
            value="Fox-34">
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.skuError %>
            </p>
            <% } %>
        </div>
        <!-- Stock Quantity -->
        <div>
          <label class="block text-sm font-medium text-gray-700" for="stock-quantity">Stock Quantity</label>
          <input type="text" id="stock-quantity" name="stock_quantity" class="mt-1 p-2 w-full border rounded-md"
            placeholder="1258" value="50">
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.stock_quantityError %>
            </p>
            <% } %>
        </div>
        <!-- Regular Price -->
        <div>
          <label class="block text-sm font-medium text-gray-700" for="regular-price">Regular Price</label>
          <input type="text" id="regular-price" name="regular_price" class="mt-1 p-2 w-full border rounded-md"
            placeholder="₹1000" value="20">
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.regular_priceError %>
            </p>
            <% } %>
        </div>
        <!-- Sale Price -->
        <div>
          <label class="block text-sm font-medium text-gray-700" for="sale-price">Sale Price</label>
          <input type="text" id="sale-price" name="sale_price" class="mt-1 p-2 w-full border rounded-md"
            placeholder="₹450" value="10">
          <% if(locals.errors) { %>
            <p class="text-red-500 text-sm mt-1">
              <%= errors.sale_priceError %>
            </p>
            <% } %>
        </div>
        <div class="col-span-2">
          <label for="dropzone-file"
            class="flex flex-col items-center justify-center w-full h-64 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50">
            <div class="flex flex-col items-center justify-center pt-5 pb-6">
              <svg class="w-8 h-8 mb-4 text-gray-500" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                viewBox="0 0 20 16">
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M13 13h3a3 3 0 0 0 0-6h-.26a5 5 0 1 0-9.48 0A4.5 4.5 0 0 0 5 13H2"></path>
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="m10 8-3 3m3-3 3 3m-3-3v9"></path>
              </svg>
              <p class="mb-2 text-sm text-gray-500"><span class="font-semibold">Click to upload</span> or drag and drop
              </p>
              <p class="text-xs text-gray-500">SVG, PNG, JPG or GIF (MAX. 800x400px)</p>
            </div>
            <input id="dropzone-file" name="files" type="file" class="hidden" multiple />
          </label>
        </div>
        <!-- Image preview -->
        <div id="image-preview" class="flex flex-wrap mt-4"></div>
        <% if(locals.errors) { %>
          <p class="text-red-500 text-sm mt-1">
            <%= errors.imageError %>
          </p>
          <% } %>
            <!-- Cropper modal -->
            <div id="cropper-modal" class="fixed inset-0 bg-black bg-opacity-50 items-center justify-center hidden">
              <div class="bg-white p-4 rounded-lg max-w-2xl w-full">
                <img id="cropper-image" class="max-w-full h-auto" alt="Crop Image">
                <div class="mt-4 flex justify-end">
                  <button type="button" id="cancel-crop"
                    class="px-4 py-2 bg-gray-500 text-white rounded mr-2">Cancel</button>
                  <button type="button" id="apply-crop" class="px-4 py-2 bg-blue-500 text-white rounded">Apply
                    Crop</button>
                </div>
              </div>
            </div>
            <!-- Submit Button -->
            <div class="col-span-2">
              <button id="submit-button" type="submit"
                class="px-6 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">Add Product </button>
            </div>
      </form>
    </div>
  </div>
</div>
<!-- alert  -->

<!-- HTML remains largely the same, we'll focus on JavaScript changes -->
<script>
  
  document.addEventListener('DOMContentLoaded', function () {
    const fileInput = document.getElementById('dropzone-file');
    const previewContainer = document.getElementById('image-preview');
    const cropperModal = document.getElementById('cropper-modal');
    const cropperImage = document.getElementById('cropper-image');
    const applyCropButton = document.getElementById('apply-crop');
    const cancelCropButton = document.getElementById('cancel-crop');
    const productForm = document.getElementById('productForm');
    const submitButton = document.getElementById('submit-button');
    let cropper;
    let currentImageElement;
    let croppedImages = []; // Array to store cropped image data

    fileInput.addEventListener('change', handleFileSelect);
    applyCropButton.addEventListener('click', applyCrop);
    cancelCropButton.addEventListener('click', closeCropperModal);

    // Prevent form submission when clicking modal buttons
    applyCropButton.addEventListener('click', function (event) {
      event.preventDefault();
      event.stopPropagation();
    });

    cancelCropButton.addEventListener('click', function (event) {
      event.preventDefault();
      event.stopPropagation();
    });

    function handleFileSelect(event) {
      const files = event.target.files;
      if (files.length > 0) {
        Array.from(files).forEach((file, index) => {
          const reader = new FileReader();
          reader.onload = (e) => createImageElement(e.target.result, index, file.name);
          reader.readAsDataURL(file);
        });
      }
    }

    function createImageElement(src, index, fileName) {
      const imageSection = document.createElement('div');
      imageSection.classList.add('relative', 'inline-block', 'mr-4', 'mb-4');
      imageSection.setAttribute('data-image-index', index);

      const img = document.createElement('img');
      img.src = src;
      img.classList.add('w-32', 'h-32', 'object-cover', 'mr-4');

      const cropButton = document.createElement('button');
      cropButton.type = 'button';
      cropButton.innerText = 'Crop Image';
      cropButton.classList.add('bg-blue-500', 'text-white', 'px-2', 'py-1', 'mt-2', 'rounded', 'cursor-pointer');
      cropButton.onclick = (event) => {
        event.preventDefault();
        openCropper(img, fileName);
      };

      const deleteButton = document.createElement('button');
      deleteButton.type = 'button';
      deleteButton.innerHTML = '&times;';
      deleteButton.classList.add('absolute', 'top-0', 'right-0', 'bg-red-500', 'text-white', 'rounded-full', 'w-6', 'h-6', 'flex', 'items-center', 'justify-center', 'cursor-pointer');
      deleteButton.onclick = (event) => {
        event.preventDefault();
        imageSection.remove();
        croppedImages = croppedImages.filter(img => img.fileName !== fileName);
      };

      imageSection.appendChild(img);
      imageSection.appendChild(cropButton);
      imageSection.appendChild(deleteButton);
      previewContainer.appendChild(imageSection);
    }

    function openCropper(imgElement, fileName) {
      cropperImage.src = imgElement.src;
      cropperModal.classList.remove('hidden');
      cropperModal.classList.add('flex');
      currentImageElement = imgElement;

      if (cropper) {
        cropper.destroy();
      }

      cropper = new Cropper(cropperImage, {
        aspectRatio: 1,
        viewMode: 1,
      });

      currentImageElement.setAttribute('data-file-name', fileName);
    }

    function closeCropperModal() {
      cropperModal.classList.add('hidden');
      cropperModal.classList.remove('flex');
      if (cropper) {
        cropper.destroy();
      }
    }
    function applyCrop() {
      if (cropper) {
        const croppedCanvas = cropper.getCroppedCanvas();
        currentImageElement.src = croppedCanvas.toDataURL();
        const fileName = currentImageElement.getAttribute('data-file-name');

        // Store cropped image data
        const existingIndex = croppedImages.findIndex(img => img.fileName === fileName);
        if (existingIndex !== -1) {
          croppedImages[existingIndex] = { fileName, dataUrl: croppedCanvas.toDataURL() };
        } else {
          croppedImages.push({ fileName, dataUrl: croppedCanvas.toDataURL() });
        }

        closeCropperModal();
      }
    }


    // Handle form submission
    productForm.addEventListener('submit', function (event) {
      // event.preventDefault();

      // Create FormData object
      const formData = new FormData(productForm);
      console.log("Appending cropped images: ", croppedImages);
      // Append cropped images to FormData
      croppedImages.forEach((img, index) => {
        formData.append(`croppedImage_${index}`, dataURItoBlob(img.dataUrl), img.fileName);
      });

      // Send FormData to server using fetch or XMLHttpRequest
      fetch('/admin/addProduct', {
        method: 'POST',
        body: formData
      })
        .then(response => response.json())
        .then(data => {
          console.log('Success:', data);
          // Handle successful submission (e.g., show success message, redirect)
        })
        .catch((error) => {
          console.error('Error:', error);
          // Handle errors (e.g., show error message)
        });
    });

    // Helper function to convert data URI to Blob
    function dataURItoBlob(dataURI) {
      const byteString = atob(dataURI.split(',')[1]);
      const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    }
  });

    // Check if there's an alert message from the server
    
    <% if (flashMessage) { %>
    document.addEventListener('DOMContentLoaded', function() {
      toastr['<%= flashMessage.type %>']('<%= flashMessage.message %>');
    });
<% } %>
</script>