{{>header}}
<title>Product Details</title>
<section class="content">
    <div class="container-fluid">
        <div class="row pb-2 pr-2 pl-2">
            <div class="col-md-12">
                <div class="card card-primary card-outline mt-3">
                    <div class="card-header" style="background-color: white; color:white;">
                        <h4><b style="color: #4B0F77 !important">Product Details</b></h4>
                    </div>
                </div>
            </div>
            <div class="col-md-3 ">
                <div class="card card-primary card-outline">
                    <div class="card-body box-profile">
                        <div class="text-center">
                            <img class="img-fluid" src="{{productExists.pictures.[0]}}" alt="Product picture"
                                onerror="this.onerror=null;this.src='/admin/images/zipck.png'">
                        </div><br>
                        <ul class="list-group list-group-unbordered mb-3">
                            <div>
                                <label for="" style="color: white;"><b>Product Status</b></label>
                                <input type="checkbox" class="statuss" name="status" {{#ifEquals
                                    productExists.status "Active" }} checked {{/ifEquals}} data-on-text="Active"
                                    data-off-text="Inactive" data-on-color="green" data-off-color="red"
                                    data-product-id="{{productExists._id}}">
                            </div>
                            <li class="list-group-item">
                                <b>Name</b>
                                <p class="float-right">
                                    <b>{{productExists.productName}}</b>
                                </p>
                            </li>
                            <li class="list-group-item">
                                <b>Category</b>
                                <p class="float-right">
                                    <b>{{productExists.categoryName}}</b>
                                </p>
                            </li>
                            <li class="list-group-item">
                                <b>Price</b>
                                <p class="float-right">
                                    <b>{{productExists.price}}</b>
                                </p>
                            </li>
                            <li class="list-group-item">
                                <b>Availability</b>
                                <p class="float-right">
                                    <b>{{productExists.availability}}</b>
                                </p>
                            </li>
                            <li class="list-group-item">
                                <b>Created At</b>
                                <p class="float-right">
                                    <b>{{DateTime productExists.createdAt}}</b>
                                </p>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="col-md-9">
                <div class="card">
                    <div class="card-header p-2">
                        <div class="form-group float-right d-flex align-items-center">
                            <label class="mb-0 mr-2 text-dark">Vendor</label>
                            <a href="/admin/v1/singlevendor/{{productExists.vendor._id}}" class="btn btn-md btn-info m-1">
                                <i class="fa-solid fa-eye"></i>
                            </a>
                        </div>
                        <ul class="nav nav-pills">
                            <li class="nav-item"><a class="nav-link active" href="#arts" data-toggle="tab">Details</a>
                            </li>
                            <li class="nav-item"><a class="nav-link" href="#pictures" data-toggle="tab">Pictures</a>
                            </li>
                            {{!-- <li class="nav-item"><a class="nav-link" href="#ratings" data-toggle="tab">Ratings &
                                    Reviews</a>
                            </li> --}}
                        </ul>
                    </div>
                    <div class="card-body">
                        <div class="tab-content">
                            <div class="tab-pane active" id="arts">
                                <form method="post" id="productForm" action="/admin/v1/updateproduct/{{productExists._id}}"
                                    onsubmit="changeUpdateButtonState()">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="col-form-label">Name <span class="text-danger">*</span>
                                                </label>
                                                <input type="text" class="form-control" required name="productName"
                                                    pattern="^\S(.*\S)?$"
                                                    title="Product name should not have leading or trailing spaces"
                                                    minlength="1" maxlength="100" value="{{productExists.productName}}">
                                            </div>
                                            <p id="nameP" style="color: red !important;"></p>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="col-form-label">Description  <span class="text-danger">*</span>
                                                </label>
                                                <textarea class="form-control description" name="description" required
                                                    minlength="10" rows="1">{{productExists.description}}</textarea>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        {{!-- <div class="col-md-3">
                                            <div class="form-group">
                                                <label for="type" class="col-form-label">Select Type <span
                                                        class="text-danger">*</span></label>
                                                <input type="text" class="form-control" id="type"
                                                    name="productCategoryPreference" readonly
                                                    value="{{productExists.productCategoryPreference}}">
                                                <select class="col-md-12 p-2" id="type"
                                                    name="productCategoryPreference"
                                                    style="border-radius: 5px; pointer-events:none;" required>
                                                    <option value="ecommerce" {{#if (eql
                                                        productExists.productCategoryPreference 'ecommerce'
                                                        )}}selected{{/if}}>E-commerce</option>
                                                    <option value="food" {{#if (eql
                                                        productExists.productCategoryPreference 'food'
                                                        )}}selected{{/if}}>Food</option>
                                                    <option value="grocery" {{#if (eql
                                                        productExists.productCategoryPreference 'grocery'
                                                        )}}selected{{/if}}>Grocery</option>
                                                </select>
                                            </div>
                                        </div> --}}
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label for="categorySelect" class="col-form-label">Category <span
                                                        class="text-danger">*</span></label>
                                                <select id="categorySelect" name="categoryId" class="col-md-12 p-2"
                                                    style="border-radius: 5px;" required>
                                                    <option value="{{productExists.category}}">
                                                        {{productExists.categoryName}}</option>
                                                    {{#each allCategories}}
                                                    <option value="{{this._id}}" data-type="{{this.type}}">
                                                        {{this.name}}
                                                    </option>
                                                    {{/each}}
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label class="col-form-label">Price <span class="text-danger">*</span>
                                                </label>
                                                <input type="number" min="0.01" max="9999999" class="form-control" step="0.01"
                                                    id="price" name="price" required value="{{productExists.price}}"
                                                    oninput="calculateDiscountedPrice()">
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label class="col-form-label">Discount(%)</label>
                                                <input type="number" id="discount" class="form-control" name="discount"
                                                    value="{{productExists.discount}}" step="1" min="0" max="100" placeholder="0"
                                                    oninput="calculateDiscountedPrice()">
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label for="tax" class="col-form-label">Discounted Price </label>
                                                <input type="number" id="discountedPrice" class="form-control"
                                                    name="discountedPrice" value="{{productExists.discountedPrice}}"
                                                    placeholder="Discounted Price" min="1" readonly>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label class="col-form-label">Availability<span
                                                        class="text-danger">*</span>
                                                </label>
                                                <select name="availability" class="form-control">
                                                    <option value="Instock" {{#if (eql
                                                        productExists.availability "Instock" )}}selected{{/if}}>
                                                        Instock
                                                    </option>
                                                    <option value="Out-of-stock" {{#if (eql
                                                        productExists.availability "Out-of-stock" )}}selected{{/if}}>Out
                                                        Of Stock</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label for="tax" class="col-form-label">CGST(%) <span
                                                        class="text-danger">*</span></label>
                                                <input type="number" min="0" max="100" step="0.01" required class="form-control" name="cgst"
                                                    value="{{productExists.cgst}}" placeholder="Enter CGST here">
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label for="tax" class="col-form-label">SGST(%) <span
                                                        class="text-danger">*</span></label>
                                                <input type="number" min="0" max="100" step="0.01" required class="form-control" name="sgst"
                                                    value="{{productExists.sgst}}" placeholder="Enter SGST here">
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Special Offer</label><br>
                                                    <input type="checkbox" class="status" name="specialOffer"
                                                        {{#ifEquals productExists.specialOffer "yes" }} checked
                                                        {{/ifEquals}} data-on-text="yes" data-off-text="no"
                                                        data-on-color="green" data-off-color="red">
                                                </div>
                                            </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label class="col-form-label">Unit Type <span
                                                        class="text-danger">*</span></label>
                                                <select id="unitTypeSelect" name="unitType" class="form-control"
                                                    onchange="updateQuantityPlaceholder()">
                                                    <option value="" disabled selected hidden>Select Unit Type
                                                    </option>
                                                    <option value="piece" {{#if (eql productExists.unitType "piece"
                                                        )}}selected{{/if}}>Piece</option>
                                                    <option value="kilogram" {{#if (eql
                                                        productExists.unitType "kilogram" )}}selected{{/if}}>Kilogram
                                                    </option>
                                                    <option value="gram" {{#if (eql productExists.unitType "gram"
                                                        )}}selected{{/if}}>Gram</option>
                                                    <option value="litre" {{#if (eql productExists.unitType "litre"
                                                        )}}selected{{/if}}>Gram</option>
                                                    <option value="millilitre" {{#if (eql
                                                        productExists.unitType "millilitre" )}}selected{{/if}}>
                                                        Millilitre</option>
                                                    <option value="pack" {{#if (eql productExists.unitType "pack"
                                                        )}}selected{{/if}}>Pack</option>
                                                    <option value="box" {{#if (eql productExists.unitType "box"
                                                        )}}selected{{/if}}>Box</option>
                                                    <option value="jar" {{#if (eql productExists.unitType "jar"
                                                        )}}selected{{/if}}>Jar</option>
                                                    <option value="can" {{#if (eql productExists.unitType "can"
                                                        )}}selected{{/if}}>Can</option>
                                                    <option value="meter" {{#if (eql productExists.unitType "meter"
                                                        )}}selected{{/if}}>Meter</option>
                                                    <option value="pair" {{#if (eql productExists.unitType "pair"
                                                        )}}selected{{/if}}>Pair</option>
                                                    <option value="set" {{#if (eql productExists.unitType "set"
                                                        )}}selected{{/if}}>Set</option>
                                                    <option value="bundle" {{#if (eql productExists.unitType "bundle"
                                                        )}}selected{{/if}}>Bundle</option>
                                                    <option value="dozen" {{#if (eql productExists.unitType "dozen"
                                                        )}}selected{{/if}}>Dozen</option>
                                                    <option value="sheet" {{#if (eql productExists.unitType "sheet"
                                                        )}}selected{{/if}}>Sheet</option>
                                                    <option value="ream" {{#if (eql productExists.unitType "ream"
                                                        )}}selected{{/if}}>Ream</option>
                                                    <option value="inches" {{#if (eql productExists.unitType "inches"
                                                        )}}selected{{/if}}>Inches</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label class="col-form-label">Quantity
                                                </label>
                                                <input type="number" class="form-control" name="quantity" min="1" max="999"
                                                    id="quantityInput" value="{{productExists.quantity}}"
                                                    placeholder="Enter Quantity in No's">
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label class="col-form-label">Stock<span class="text-danger">*</span>
                                                </label>
                                                <input type="number" class="form-control" name="stock" min="1" max="999"
                                                    placeholder="Enter Available Stock" required
                                                    value="{{productExists.stock}}">
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label class="col-form-label">Stock Alert <span
                                                        class="text-danger">*</span>
                                                </label>
                                                <input type="number" min="0" max="999" class="form-control"
                                                    name="stockAlert" required value="{{productExists.stockAlert}}">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="type-fields grocery">
                                        <div class="row">
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label for="harvestDate" class="form-label">Harvest Date </label>
                                                    <input type="date" class="form-control" id="harvestDate"
                                                        name="harvestDate"
                                                        value="{{formatDate productExists.harvestDate}}">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Organic Label</label><br>
                                                    <input type="checkbox" class="status" name="organicLabel"
                                                        {{#ifEquals productExists.organicLabel "yes" }} checked
                                                        {{/ifEquals}} data-on-text="yes" data-off-text="no"
                                                        data-on-color="green" data-off-color="red">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label for="expiryDate" class="form-label">Expiry Date</label>
                                                    <input type="date" class="form-control" id="expiryDate2"
                                                        name="expiryDate"
                                                        value="{{formatDate productExists.expiryDate}}" disabled>
                                                </div>
                                            </div>
                                        </div>
                                        {{!-- <div class="row">
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Freshest Veggies</label><br>
                                                    <input type="checkbox" class="status" name="freshestVeggies"
                                                        {{#ifEquals productExists.freshestVeggies "Active" }} checked
                                                        {{/ifEquals}} data-on-text="on" data-off-text="off"
                                                        data-on-color="green" data-off-color="red">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Dairy, Bread & Eggs</label><br>
                                                    <input type="checkbox" class="status" name="dairyProducts"
                                                        {{#ifEquals productExists.dairyProducts "Active" }} checked
                                                        {{/ifEquals}} data-on-text="on" data-off-text="off"
                                                        data-on-color="green" data-off-color="red">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label">Juiciest Fruits</label><br>
                                                    <input type="checkbox" class="status" name="juiciestFruits"
                                                        {{#ifEquals productExists.juiciestFruits "Active" }} checked
                                                        {{/ifEquals}} data-on-text="on" data-off-text="off"
                                                        data-on-color="green" data-off-color="red">
                                                </div>
                                            </div>
                                        </div> --}}
                                    </div>
                                    <br>
                                    <div class="form-group d-flex justify-content-center">
                                        <button class="saveButton btn btn-info col-md-4 btn-block" id="updateButton"
                                            type="submit">Update</button>
                                    </div>
                                </form>
                                <div class="form-group d-flex justify-content-center">
                                    <a href="javascript:void(0);" data-bs-toggle="modal" data-id="{{productExists._id}}"
                                        data-bs-target="#deleteModal" class="btn btn-danger col-md-4 btn-block">
                                        Delete
                                    </a>
                                </div>
                            </div>
                            <div class="tab-pane" id="pictures">
                                <form method="post" action="/admin/v1/updateproductpictures/{{productExists._id}}"
                                    enctype="multipart/form-data">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <div class="form-group">
                                                <label class="col-form-label">Pictures
                                                </label>
                                                <input type="file" class="form-control" accept="image/*" multiple
                                                    name="pictures" id="imageInput" required>
                                            </div>
                                        </div>
                                        <div class="col-md-2 d-flex align-items-end">
                                            <div class="form-group">
                                                <button class="btn btn-info w-100" type="submit">Update</button>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                                {{!-- <div class="row">
                                    {{#each productExists.pictures}}
                                    <div class="col-md-4 col-sm-6 mb-4">
                                        <div class="form-group">
                                            <img class="img-fluid rounded shadow-sm" src="/{{this}}" alt="Product image"
                                                onerror="this.onerror=null;this.src='/admin/images/zipck.png'">
                                        </div>
                                    </div>
                                    {{/each}}
                                </div> --}}
                                <table class="table table-bordered">
                        <thead>
                            <tr>
                            <th>S.No</th>
                            <th>Image</th>
                            <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            {{#each (reverse productExists.pictures)}}
                            <tr>
                            <td>{{inc @index}}</td>
                            <td>
                                <img src="/{{this}}" alt="Product image" class="img-thumbnail" style="max-width: 220px;"
                                    onerror="this.onerror=null;this.src='/admin/images/zipck.png'">
                            </td>
                            <td>
                                <a href="/admin/v1/deleteproductimage/{{../productExists._id}}/{{reverseIndex @index ../productExists.pictures.length}}" 
                                class="btn btn-danger btn-sm"
                                onclick="return confirm('Are you sure to delete this image?');">
                                Delete
                                </a>
                            </td>
                            </tr>
                            {{/each}}
                        </tbody>
                        </table>
                            </div>
                            <div class="tab-pane" id="ratings">
                                <div class="row">
                                    <div class="col-sm-12 table-responsive">
                                        <table id="example2" class="table table-striped table-bordered"
                                            aria-describedby="example1_info">
                                            <thead>
                                                <tr>
                                                    <th class="sorting" tabindex="0" aria-controls="example1">S.No</th>
                                                    <th class="sorting" tabindex="0" aria-controls="example1">Order Id</th>
                                                    <th class="sorting" tabindex="0" aria-controls="example1">First Name
                                                    </th>
                                                    <th class="sorting" tabindex="0" aria-controls="example1">Last Name
                                                    </th>
                                                    <th class="sorting" tabindex="0" aria-controls="example1">Phone</th>
                                                    <th class="sorting" tabindex="0" aria-controls="example1">Review
                                                    </th>
                                                    <th class="sorting" tabindex="0" aria-controls="example1">Rating
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {{#each allRatingsAndReviews}}
                                                <tr class="odd">
                                                    <td>{{inc @index}}</td>
                                                    <td>{{this.order.orderId}}</td>
                                                    <td>{{this.firstName}}</td>
                                                    <td>{{this.lastName}}</td>
                                                    <td>{{this.phone}}</td>
                                                    <td>{{this.review}}</td>
                                                    <td>{{this.ratings}}</td>
                                                </tr>
                                                {{/each}}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<script>
document.getElementById("imageInput").addEventListener("change", function (event) {
    const files = event.target.files;
    const maxSize = 1 * 1024 * 1024; // 1 MB
    const requiredRatio = 4 / 3;
    const tolerance = 0.02; // allow small floating point difference

    for (let i = 0; i < files.length; i++) {
        const file = files[i];

        if (file.size > maxSize) {
            alert(`"${file.name}" exceeds 1 MB size limit`);
            event.target.value = "";
            return;
        }

        const img = new Image();
        img.src = URL.createObjectURL(file);

        img.onload = function () {
            const width = img.width;
            const height = img.height;
            const ratio = width / height;

            if (Math.abs(ratio - requiredRatio) > tolerance) {
                alert(`"${file.name}" must have 4:3 aspect ratio`);
                document.getElementById("imageInput").value = "";
            }

            URL.revokeObjectURL(img.src);
        };
    }
});
</script>

<script>
    const pictureInput = document.getElementById('imageInput'); // Correct ID

    pictureInput.addEventListener("change", function () {
        const files = this.files;
        const validTypes = ["image/jpeg", "image/png", "image/webp", "image/jpg"];
        let isValid = true;

        for (let i = 0; i < files.length; i++) {
            if (!validTypes.includes(files[i].type)) {
                isValid = false;
                alert(`File "${files[i].name}" is not a valid image format.`);
                this.value = ""; // Clear all files
                break;
            }
        }

        if (isValid) {
            console.log("All selected files are valid images:");
            for (let i = 0; i < files.length; i++) {
                //console.log(`- ${files[i].name}`);
            }
        }
    });
</script>
<script>
    let addonIndex = {{ productExists.extras.length }} || 0;

    document.getElementById('addAddon').addEventListener('click', () => {
        const nameInputs = document.querySelectorAll("input[name^='extraAddons'][name$='[addOn]']");
        const priceInputs = document.querySelectorAll("input[name^='extraAddons'][name$='[price]']");

        let hasEmpty = false;

        nameInputs.forEach(input => {
            if (input.value.trim() === "") {
                hasEmpty = true;
            }
        });

        priceInputs.forEach(input => {
            if (input.value.trim() === "") {
                hasEmpty = true;
            }
        });

        if (hasEmpty) {
            alert("Please fill in all existing add-on name and price fields before adding a new one.");
            return;
        }
        const wrapper = document.getElementById('extraAddonsWrapper');
        const div = document.createElement('div');
        div.classList.add('addon-group', 'd-flex', 'align-items-center', 'mb-2');
        div.innerHTML = `
      <input type="text" name="extraAddons[${addonIndex}][addOn]" class="form-control mr-2" placeholder="Product Name">
      <input type="number" name="extraAddons[${addonIndex}][price]" class="form-control mr-2" placeholder="Price (₹)" min="0" max="9999999">
      <button type="button" class="btn btn-danger remove-addon"><i class="fa fa-trash"></i></button>
    `;
        wrapper.appendChild(div);
        addonIndex++;
    });

    document.addEventListener('click', function (e) {
        if (e.target.closest('.remove-addon')) {
            e.target.closest('.addon-group').remove();
        }
    });
</script>
<script>
document.getElementById("productForm").addEventListener("submit", function (e) {
    // Get all addon groups
    const addonGroups = document.querySelectorAll(".addon-group");

    addonGroups.forEach(group => {
        const nameInput = group.querySelector("input[name$='[addOn]']");
        const priceInput = group.querySelector("input[name$='[price]']");

        if (!nameInput.value.trim() || !priceInput.value.trim()) {
            group.remove(); // remove the whole group so backend never sees it
        }
    });
});
</script>
{{!-- to change the placeholder of quantity based on the unit type changed --}}
<script>
    function updateQuantityPlaceholder() {
        const unitType = document.getElementById("unitTypeSelect").value;
        const quantityInput = document.getElementById("quantityInput");
        // Capitalize the first letter of unit type for placeholder
        const formattedUnit = unitType.charAt(0).toUpperCase() + unitType.slice(1);

        // Set new placeholder and clear value
        quantityInput.placeholder = `Enter Quantity in ${formattedUnit}`;
        quantityInput.value = ''; // clear field on change
    }
</script>
{{!-- discounted price calculation --}}
<script>
    function calculateDiscountedPrice() {
        const price = parseFloat(document.getElementById("price").value) || 0;
        const discount = parseFloat(document.getElementById("discount").value) || 0;

        if (price > 0 && discount >= 0 && discount <= 100) {
            let discountedPrice = price;
            if (discount > 0) {
                discountedPrice = price - (price * discount / 100);
            }
            document.getElementById("discountedPrice").value = discountedPrice.toFixed(2);
        } else {
            document.getElementById("discountedPrice").value = "";
        }
    }
</script>
<script>
    window.onload = function () {
        calculateDiscountedPrice();
    };
</script>

<script>
    function changeUpdateButtonState() {
        var submitButton = document.getElementById('updateButton');
        submitButton.textContent = 'updating...';
        submitButton.disabled = true;
    }
</script>
{{!-- script for description trim --}}
<script>
    document.querySelector('form').addEventListener('submit', function (e) {
        const descField = document.querySelector('textarea[name="description"]');
        const ingredientsField = document.querySelector('textarea[name="ingredients"]');
        const packagingTypeFeild = document.querySelector('textarea[name="packagingType"]');
        const returnPolicyFeild = document.querySelector('textarea[name="returnPolicy"]');
        const manufacturerNameFeild = document.querySelector('textarea[name="manufacturerName"]');

        if (descField) descField.value = descField.value.trim();
        if (ingredientsField) ingredientsField.value = ingredientsField.value.trim();
        if (packagingTypeFeild) packagingTypeFeild.value = packagingTypeFeild.value.trim();
        if (returnPolicyFeild) returnPolicyFeild.value = returnPolicyFeild.value.trim();
        if (manufacturerNameFeild) manufacturerNameFeild.value = manufacturerNameFeild.value.trim();
    });
</script>

<script>
    $(document).ready(function () {
        $("input[data-bootstrap-switch]").each(function () {
            $(this).bootstrapSwitch('state', $(this).prop('checked'));
        });
        $('.status').bootstrapSwitch('state');
    });
</script>
<script>
    $(document).ready(function () {
        $("input[data-bootstrap-switch]").each(function () {
            $(this).bootstrapSwitch('state', $(this).prop('checked'));
        });
        $('.statuss').bootstrapSwitch('state');
    });
</script>
{{!-- bootstrap for product active and inactive --}}
<script>
    $(document).ready(function () {
        // Initialize Bootstrap Switch for all checkboxes with data-bootstrap-switch attribute
        $("input[data-bootstrap-switch]").bootstrapSwitch();
        // Trigger the API call when the switch changes
        $('.statuss').on('switchChange.bootstrapSwitch', function (event, state) {
            // Get the vendor ID from the data attribute
            var productId = $(this).data('product-id');
            // 'state' is true if the switch is turned on, false if off
            var isChecked = state;
            // Prepare data for the API call
            var data = {
                status: isChecked ? 'Active' : 'Inactive'  // Send 'Active' if checked, 'Inactive' if unchecked
            };
            // Send an AJAX request to the backend API
            $.ajax({
                url: `/admin/v1/updateproductstatus/${productId}`,  // Use the product ID in the URL
                method: 'POST',
                data: data,
                success: function (response) {
                    console.log("success");
                    //alert('Status updated successfully');
                },
                error: function (xhr, status, error) {
                    alert('Error updating status');
                }
            });
        });
    });
</script>
<script>
    function toggleExpiryInputs(category) {
        const foodExpiry = document.getElementById('expiryDate');
        const groceryExpiry = document.getElementById('expiryDate2');
        foodExpiry.style.display = 'none';
        foodExpiry.disabled = true;
        groceryExpiry.style.display = 'none';
        groceryExpiry.disabled = true;
        if (category === 'food') {
            foodExpiry.style.display = 'block';
            foodExpiry.disabled = false;
        } else if (category === 'grocery') {
            groceryExpiry.style.display = 'block';
            groceryExpiry.disabled = false;
        }
    }
    // Call once when the DOM is ready
    document.addEventListener('DOMContentLoaded', function () {
        const categoryInput = document.querySelector('[name="productCategoryPreference"]');
        if (categoryInput) {
            toggleExpiryInputs(categoryInput.value);
        }
    });
</script>
{{!-- show and hide functionality based on type changed --}}
<script>
    document.addEventListener('DOMContentLoaded', () => {
        const typeSelect = document.getElementById('type');
        const typeFields = document.querySelectorAll('.type-fields');

        // Function to show only selected type fields
        function showTypeFields(selected) {
            typeFields.forEach(div => {
                div.style.display = 'none';
                Array.from(div.querySelectorAll('input, select')).forEach(el => {
                    el.required = false;
                });
            });

            if (selected) {
                const selectedFields = document.querySelector('.' + selected);
                if (selectedFields) {
                    selectedFields.style.display = 'block';
                    Array.from(selectedFields.querySelectorAll('input, select')).forEach(el => {
                        if (el.hasAttribute('data-required')) {
                            el.required = true;
                        }
                    });
                }
            }
        }

        // 🔁 Run once on page load (for edit mode)
        showTypeFields(typeSelect.value);

        // 🔁 Run every time dropdown changes
        typeSelect.addEventListener('change', function () {
            showTypeFields(this.value);
        });
    });

    //for expiry date
    document.addEventListener('DOMContentLoaded', () => {
        const expiryInput = document.getElementById('expiryDate');
        if (expiryInput) {
            const today = new Date().toISOString().split('T')[0];
            expiryInput.setAttribute('min', today);
        }
    });
    document.addEventListener('DOMContentLoaded', () => {
        const expiryInput = document.getElementById('expiryDate2');
        if (expiryInput) {
            const today = new Date().toISOString().split('T')[0];
            expiryInput.setAttribute('min', today);
        }
    });
    //for harvest date
    document.addEventListener('DOMContentLoaded', () => {
        const harvestInput = document.getElementById('harvestDate');
        if (harvestInput) {
            const today = new Date().toISOString().split('T')[0];
            harvestInput.setAttribute('max', today);
        }
    });
</script>
{{!-- script for adding sizes --}}
<script>
    //script for adding sizes
    document.getElementById("add-size").addEventListener("click", () => {
        const sizeInputs = document.querySelectorAll("input[name='availableSizes[]']");
        let hasEmpty = false;

        sizeInputs.forEach(input => {
            if (input.value.trim() === "") {
                hasEmpty = true;
            }
        });

        if (hasEmpty) {
            alert("Please fill all existing size fields before adding a new one.");
            return;
        }

        const container = document.getElementById("sizes-container");
        const div = document.createElement("div");
        div.className = "input-group mb-2";
        div.innerHTML = `
            <input type="text" class="form-control" name="availableSizes[]" placeholder="Enter Size">
            <button class="btn btn-danger remove-size" type="button">&times;</button>
        `;
        container.appendChild(div);
    });

    document.addEventListener("click", function (e) {
        if (e.target.classList.contains("remove-size")) {
            e.target.closest(".input-group").remove();
        }
    });

    document.querySelector("form").addEventListener("submit", function (e) {
        e.preventDefault();

        const sizeInputs = document.querySelectorAll("input[name='availableSizes[]']");
        sizeInputs.forEach(input => {
            const trimmed = input.value.trim();
            if (!trimmed) {
                input.closest(".input-group").remove(); // Remove empty/whitespace-only
            } else {
                input.value = trimmed; // Clean the value
            }
        });

        this.submit();
    });
</script>
{{!-- script for adding colors --}}
<script>
    // Script for adding colors
    document.getElementById("add-color").addEventListener("click", () => {
        const colorInputs = document.querySelectorAll("input[name='availableColors[]']");
        let hasEmpty = false;

        colorInputs.forEach(input => {
            if (input.value.trim() === "") {
                hasEmpty = true;
            }
        });

        if (hasEmpty) {
            alert("Please fill all existing color fields before adding a new one.");
            return;
        }

        const container = document.getElementById("colors-container");
        const div = document.createElement("div");
        div.className = "input-group mb-2";
        div.innerHTML = `
            <input type="text" class="form-control" name="availableColors[]" placeholder="Enter Color">
            <button class="btn btn-danger remove-color" type="button">&times;</button>
        `;
        container.appendChild(div);
    });

    // Remove color field on button click
    document.addEventListener("click", function (e) {
        if (e.target.classList.contains("remove-color")) {
            e.target.closest(".input-group").remove();
        }
    });

    // Trim and clean up on form submit
    document.querySelector("form").addEventListener("submit", function (e) {
        e.preventDefault();

        const colorInputs = document.querySelectorAll("input[name='availableColors[]']");
        colorInputs.forEach(input => {
            const trimmed = input.value.trim();
            if (!trimmed) {
                input.closest(".input-group").remove(); // Remove empty/whitespace-only
            } else {
                input.value = trimmed; // Clean the value
            }
        });

        this.submit();
    });
</script>

{{!-- script for changing subcategories based on category change --}}
<script>
    document.getElementById("categorySelect").addEventListener("change", function () {
        const categoryId = this.value;
        const brandSelect = document.getElementById("brandSelect");
        brandSelect.innerHTML = '<option value="">Select Sub Category</option>';
        if (categoryId) {
            fetch(`/admin/getsubcategories/${categoryId}`)
                .then(response => response.json())
                .then(data => {
                    data.allSubCategories.forEach(subCategory => {
                        const option = document.createElement("option");
                        option.value = subCategory._id;
                        option.textContent = subCategory.name;
                        brandSelect.appendChild(option);
                    });
                })
                .catch(error => alert("Error fetching brands"));
        }
    });
</script>
{{!-- script for changing categories based on type change --}}
{{!--
<script>
    //triger api on type change
    document.addEventListener("DOMContentLoaded", function () {
        const typeSelect = document.getElementById("type");
        const categorySelect = document.getElementById("categorySelect");

        typeSelect.addEventListener("change", function () {
            const selectedType = this.value;

            // Clear the current categories
            categorySelect.innerHTML = '<option value="">Select Category</option>';

            if (selectedType) {
                fetch(`/admin/getcategoriesbytype/${selectedType}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data && data.allCategories) {
                            data.allCategories.forEach(category => {
                                const option = document.createElement("option");
                                option.value = category._id;
                                option.textContent = category.name;
                                option.setAttribute("data-type", category.type);
                                categorySelect.appendChild(option);
                            });
                        }
                    })
                    .catch(error => {
                        alert("Error fetching categories");
                        console.error(error);
                    });
            }
        });
    });
</script> --}}
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 style="color: black; font-weight: 480;">Are you sure you want to delete this?</h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
                <a href="" id="deleteBannerLink" type="button" class="btn btn-danger">Yes</a>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        $('#deleteModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget);
            var bannerId = button.data('id');
            var modal = $(this);
            modal.find('#deleteBannerLink').attr('href', '/admin/v1/deleteproduct/' + bannerId);
        });
    });
</script>


{{>footer}}