@extends('admin.layout.dashboard_master')

@section('content')
    <main id="main" class="main">

        <div class="pagetitle">
            <h1>Product</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="#">American Plastic</a></li>
                    <li class="breadcrumb-item">Dashboard</li>
                    <li class="breadcrumb-item active">Product</li>
                </ol>
            </nav>
        </div><!-- End Page Title -->

        <section class="section">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Product Form</h5>
                            <!-- General Form Elements -->
                            <form id="product_form" method="POST" onsubmit="return validateForm()"
                                enctype="multipart/form-data">
                                @csrf
                                <div class="row mb-3">
                                    <div class="col-md-12">
                                        <!-- Upload Area -->
                                        <div id="uploadArea" class="upload-area">
                                            <!-- Header -->
                                            <div class="upload-area__header">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label for="inputText">Product
                                                            Name</label>
                                                        <input type="text" class="form-control" name="product_name"
                                                            id="pro_name" maxlength="40">
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="inputText">Product
                                                            Tags(SEO Optimization)</label>
                                                        <input type="text" class="form-control" name="product_tags"
                                                            id="producttags">
                                                    </div>


                                                </div>
                                            </div>
                                            <!-- End Header -->
                                            <div class="upload-area__header py-2">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <label for="inputText">Category</label>
                                                        <select id="inputText" class="form-control" name="category">
                                                            @php
                                                                $category = App\Models\Category::get();
                                                            @endphp
                                                            @if ($category)
                                                                @foreach ($category as $item)
                                                                    <option value="{{ $item->id }}">
                                                                        {{ $item->category_name }}</option>
                                                                @endforeach
                                                            @else
                                                                <option value="no">Categories not avaialble</option>
                                                            @endif
                                                            <!-- Add more options as needed -->
                                                        </select>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="inputText">Product
                                                            Quantity</label>
                                                        <input type="number" class="form-control" name="product_quantity"
                                                            id="qty">
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="upload-area__header py-2">
                                                <div class="row">
                                                    <div class="col-md-4">
                                                        <label for="inputText">Product
                                                            Group Code</label>
                                                        <input type="text" class="form-control" name="productgroupcode"
                                                            id="product_group">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label for="inputText">Product
                                                            Price</label>
                                                        <input type="number" class="form-control" name="productprice"
                                                            id="product_price">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label>Cutted Price (optional)</label>
                                                        <input type="number" class="form-control" name="cuttedprice"
                                                            id="cutted_price">

                                                        <div class="form-check form-switch mt-3">
                                                            <input class="form-check-input" type="checkbox"
                                                                id="allowDealToggle" name="allowdeal" value="1">
                                                            <label class="form-check-label" for="allowDealToggle">Allow
                                                                Deal</label>

                                                        </div>
                                                    </div>

                                                </div>
                                            </div>

                                            <!-- Drop Zoon -->
                                            <div class="py-2">
                                                <label for="inputText">
                                                    Product Image <br>
                                                    <small class="text-muted">
                                                        Please upload high-quality images (exactly 500 x 500 pixels) in JPG,
                                                        JPEG, or PNG format. Maximum file size: 2MB each.<br>
                                                        <strong>Recommended:</strong> Upload 4 images.
                                                </label>

                                                <div id="drop-area">
                                                    <p>Upload multiple files with the file dialog or by dragging and
                                                        dropping images onto the dashed region</p>
                                                    <input type="file" id="fileElem" multiple accept="image/*"
                                                        onchange="handleFiles(this.files)" name="images">
                                                    <label class="button" for="fileElem">Select files</label>
                                                    <progress id="progress-bar" max=100 value=0></progress>
                                                    <div id="gallery"></div>
                                                </div>

                                                <style>
                                                    #drop-area {
                                                        border: 2px dashed #ccc;
                                                        border-radius: 20px;
                                                        padding: 20px;
                                                        text-align: center;
                                                        font-family: sans-serif;
                                                    }

                                                    #drop-area.highlight {
                                                        border-color: purple;
                                                    }

                                                    #fileElem {
                                                        display: none;
                                                    }

                                                    .button {
                                                        display: inline-block;
                                                        padding: 10px;
                                                        background: #ccc;
                                                        cursor: pointer;
                                                        border-radius: 5px;
                                                        border: 1px solid #999;
                                                    }

                                                    .button:hover {
                                                        background: #ddd;
                                                    }

                                                    #gallery {
                                                        margin-top: 20px;
                                                        display: flex;
                                                        flex-wrap: wrap;
                                                        gap: 10px;
                                                    }

                                                    .thumbnail {
                                                        position: relative;
                                                        width: 150px;
                                                        height: 150px;
                                                        margin-bottom: 10px;
                                                    }

                                                    .thumbnail img {
                                                        width: 100%;
                                                        height: 100%;
                                                        object-fit: cover;
                                                        border-radius: 5px;
                                                    }

                                                    .remove-btn {
                                                        position: absolute;
                                                        top: 5px;
                                                        right: 5px;
                                                        background: red;
                                                        color: white;
                                                        border: none;
                                                        border-radius: 50%;
                                                        width: 20px;
                                                        height: 20px;
                                                        font-size: 12px;
                                                        cursor: pointer;
                                                        display: flex;
                                                        align-items: center;
                                                        justify-content: center;
                                                    }

                                                    .remove-btn:hover {
                                                        background: darkred;
                                                    }

                                                    #progress-bar {
                                                        width: 100%;
                                                        margin-top: 10px;
                                                    }
                                                </style>

                                                <script>
                                                    const dropArea = document.getElementById('drop-area');
                                                    const fileElem = document.getElementById('fileElem');
                                                    const gallery = document.getElementById('gallery');

                                                    // Prevent default drag behaviors
                                                    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                                                        dropArea.addEventListener(eventName, preventDefaults, false);
                                                    });

                                                    function preventDefaults(e) {
                                                        e.preventDefault();
                                                        e.stopPropagation();
                                                    }

                                                    // Highlight drop area when item is dragged over it
                                                    ['dragenter', 'dragover'].forEach(eventName => {
                                                        dropArea.addEventListener(eventName, highlight, false);
                                                    });

                                                    ['dragleave', 'drop'].forEach(eventName => {
                                                        dropArea.addEventListener(eventName, unhighlight, false);
                                                    });

                                                    function highlight() {
                                                        dropArea.classList.add('highlight');
                                                    }

                                                    function unhighlight() {
                                                        dropArea.classList.remove('highlight');
                                                    }

                                                    // Handle dropped files
                                                    dropArea.addEventListener('drop', handleDrop, false);

                                                    function handleDrop(e) {
                                                        const dt = e.dataTransfer;
                                                        const files = dt.files;
                                                        handleFiles(files);
                                                    }

                                                    function handleFiles(files) {
                                                        [...files].forEach(previewFile);
                                                    }

                                                    function previewFile(file) {
                                                        if (!file.type.match('image.*')) return;

                                                        const reader = new FileReader();

                                                        reader.readAsDataURL(file);
                                                        reader.onloadend = function() {
                                                            const thumbnail = document.createElement('div');
                                                            thumbnail.className = 'thumbnail';

                                                            const img = document.createElement('img');
                                                            img.src = reader.result;
                                                            img.alt = file.name;

                                                            const removeBtn = document.createElement('button');
                                                            removeBtn.className = 'remove-btn';
                                                            removeBtn.innerHTML = '×';
                                                            removeBtn.onclick = function() {
                                                                thumbnail.remove();
                                                            };

                                                            thumbnail.appendChild(img);
                                                            thumbnail.appendChild(removeBtn);
                                                            gallery.appendChild(thumbnail);
                                                        }
                                                    }
                                                </script>
                                            </div>
                                        </div>


                                        <div class="upload-area__header py-2">
                                            <label for="product_description">Product
                                                description</label>
                                            <textarea class="form-control" id="product_description" rows="3" name="productdescription"></textarea>
                                        </div>

                                        <div class="upload-area__header py-2">
                                            <label for="inputText">Product
                                                weight</label>
                                            <div class="input-group">
                                                <input id="weight" class="multisteps-form__input form-control"
                                                    type="number" placeholder="eg.100" name="weight" />
                                                <div class="input-group-append" style="background-color: #555;">
                                                    <span class="input-group-text">g</span>
                                                </div>
                                            </div>
                                        </div>

                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <div class="col-md-10">
                                        <button type="button" id="create_admin" class="btn btn-primary"
                                            onclick="validateForm()">Create</button>
                                    </div>
                                </div>
                            </form><!-- End General Form Elements -->
                        </div>
                    </div>
                </div>
                <style>
                    #drop-area {
                        border: 2px dashed #ccc;
                        border-radius: 20px;
                        width: 100%;
                        font-family: sans-serif;
                        margin: auto;
                        padding: 20px;
                    }

                    #drop-area.highlight {
                        border-color: purple;
                    }

                    p {
                        margin-top: 0;
                    }

                    .my-form {
                        margin-bottom: 10px;
                    }

                    #gallery {
                        margin-top: 10px;
                    }

                    #gallery img {
                        width: 150px;
                        margin-bottom: 10px;
                        margin-right: 10px;
                        vertical-align: middle;
                    }

                    .button {
                        display: inline-block;
                        padding: 10px;
                        background: #ccc;
                        cursor: pointer;
                        border-radius: 5px;
                        border: 1px solid #ccc;
                    }

                    .button:hover {
                        background: #ddd;
                    }

                    #fileElem {
                        display: none;
                    }
                </style>

                <div class="modal fade" id="product_modalform" tabindex="-1" role="dialog"
                    aria-labelledby="assignRoleModalLabel" aria-hidden="true" data-bs-backdrop="static"
                    data-bs-keyboard="false">

                    <div class="modal-dialog modal-lg" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Edit Product</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"
                                    onclick="location.reload();"></button>

                            </div>
                            <div class="modal-body">
                                <form id="editproduct_form" method="POST" enctype="multipart/form-data">
                                    @csrf
                                    <div class="row mb-3">
                                        <div class="col-md-12">
                                            <!-- Upload Area -->
                                            <div id="uploadArea" class="upload-area">
                                                <!-- Header -->
                                                <div class="upload-area__header">
                                                    <div class="row">
                                                        <div class="col-md-6">
                                                            <label for="inputText"
                                                                class="col-sm-12 col-form-label">Product
                                                                Name</label>
                                                            <input type="text" class="form-control"
                                                                name="editproduct_name" id="edit_pro_name"
                                                                maxlength="40">
                                                        </div>
                                                        <div class="col-md-6">
                                                            <label for="inputText"
                                                                class="col-sm-12 col-form-label">Product
                                                                Tags(SEO Optimization)</label>
                                                            <input type="text" class="form-control"
                                                                name="editproduct_tags" id="edit_producttags">
                                                        </div>
                                                        <input type="hidden" name="updateid" id="update_id">

                                                    </div>
                                                </div>
                                                <!-- End Header -->
                                                <div class="upload-area__header">
                                                    <div class="row">

                                                        <div class="col-md-6">
                                                            <label for="inputText"
                                                                class="col-sm-12 col-form-label">Product
                                                                Quantity</label>
                                                            <input type="number" class="form-control"
                                                                name="editproduct_quantity" id="edit_qty">
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="upload-area__header">
                                                    <div class="row">
                                                        <div class="col-md-4">
                                                            <label for="inputText"
                                                                class="col-sm-12 col-form-label">Product
                                                                Group Code</label>
                                                            <input type="text" class="form-control"
                                                                name="editproductgroupcode" id="edit_product_group">
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label for="inputText"
                                                                class="col-sm-12 col-form-label">Product
                                                                Price</label>
                                                            <input type="text" class="form-control"
                                                                name="productprice" id="edit_product_price">
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label for="inputText" class="col-sm-12 col-form-label">Cutted
                                                                Price(optional)</label>
                                                            <input type="text" class="form-control" name="cuttedprice"
                                                                id="edit_cutted_price">
                                                           <div class="form-check form-switch mt-3" id="dealDiv" style="display: none;">
    <input class="form-check-input" type="checkbox" id="allowDealToggle" name="allowdeal" value="1">
    <label class="form-check-label" for="allowDealToggle">Allow Deal</label>
      <span  class="text-warning ms-2 ">Note: Please click "Set Update" to save changes</span>
</div>


                                                        </div>

                                                    </div>
                                                </div>

                                                <!-- Drop Zone -->
                                                <label for="productImage" class="col-sm-8 col-form-label">
                                                    Product Image <span class="text-danger">*</span>
                                                    <small class="form-text text-muted d-block">
                                                        Required - Upload a square image (exactly 500×500 pixels) for best
                                                        display.
                                                        Images with incorrect dimensions will not be saved.
                                                    </small>
                                                </label>
                                                <div id="productImageCarousel" class="carousel slide"
                                                    data-bs-ride="carousel">
                                                    <div class="carousel-inner" id="galleryedit">
                                                        <!-- Existing images will be dynamically added here -->
                                                    </div>
                                                </div>
                                                <div class="form-group">
                                                    <label>Product Images</label>
                                                    <div id="drop-areaa" class="drop-area">
                                                        <p id="select-images">Drag and drop images here or click to select
                                                        </p>
                                                        <input type="file" id="edituploadImagesInput" multiple
                                                            accept="image/*" style="display: none;" name="images[]">
                                                        <div id="image-preview" class="d-flex flex-wrap"></div>
                                                    </div>
                                                    <div id="existing-images" class="d-flex flex-wrap mt-3"></div>
                                                </div>

                                                <style>
                                                    .drop-area {
                                                        border: 2px dashed #ccc;
                                                        border-radius: 8px;
                                                        padding: 25px;
                                                        text-align: center;
                                                        transition: border 0.3s ease;
                                                        cursor: pointer;
                                                        margin-bottom: 20px;
                                                    }

                                                    .drop-area.highlight {
                                                        border-color: #4CAF50;
                                                        background-color: #f8f8f8;
                                                    }

                                                    #select-images {
                                                        color: #666;
                                                        margin: 0 0 10px 0;
                                                    }

                                                    #image-preview,
                                                    #existing-images {
                                                        display: flex;
                                                        flex-wrap: wrap;
                                                        gap: 15px;
                                                        margin-top: 20px;
                                                    }

                                                    .preview-item,
                                                    .existing-image-item {
                                                        position: relative;
                                                        width: 120px;
                                                        height: 120px;
                                                        border-radius: 5px;
                                                        overflow: hidden;
                                                        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
                                                    }

                                                    .preview-item img,
                                                    .existing-image-item img {
                                                        width: 100%;
                                                        height: 100%;
                                                        object-fit: cover;
                                                    }

                                                    .remove-btn {
                                                        position: absolute;
                                                        top: 5px;
                                                        right: 5px;
                                                        background: #ff4444;
                                                        color: white;
                                                        border: none;
                                                        border-radius: 50%;
                                                        width: 24px;
                                                        height: 24px;
                                                        font-size: 14px;
                                                        cursor: pointer;
                                                        display: flex;
                                                        align-items: center;
                                                        justify-content: center;
                                                        opacity: 0.8;
                                                        transition: opacity 0.2s;
                                                    }

                                                    .remove-btn:hover {
                                                        opacity: 1;
                                                    }

                                                    .delete-existing-btn {
                                                        position: absolute;
                                                        top: 5px;
                                                        left: 5px;
                                                        background: #ff4444;
                                                        color: white;
                                                        border: none;
                                                        border-radius: 50%;
                                                        width: 24px;
                                                        height: 24px;
                                                        font-size: 14px;
                                                        cursor: pointer;
                                                        display: flex;
                                                        align-items: center;
                                                        justify-content: center;
                                                    }
                                                </style>

                                                <script>
                                                    $(document).ready(function() {
                                                        // Initialize drop area functionality
                                                        const dropArea = document.getElementById('drop-areaa');
                                                        const fileInput = document.getElementById('edituploadImagesInput');
                                                        const previewContainer = document.getElementById('image-preview');
                                                        const existingImagesContainer = document.getElementById('existing-images');

                                                        // Click handler for the drop area
                                                        dropArea.addEventListener('click', function() {
                                                            fileInput.click();
                                                        });

                                                        // File input change handler
                                                        fileInput.addEventListener('change', function(e) {
                                                            handleFiles(e.target.files);
                                                        });

                                                        // Drag and drop handlers
                                                        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                                                            dropArea.addEventListener(eventName, preventDefaults, false);
                                                        });

                                                        ['dragenter', 'dragover'].forEach(eventName => {
                                                            dropArea.addEventListener(eventName, highlight, false);
                                                        });

                                                        ['dragleave', 'drop'].forEach(eventName => {
                                                            dropArea.addEventListener(eventName, unhighlight, false);
                                                        });

                                                        dropArea.addEventListener('drop', function(e) {
                                                            handleFiles(e.dataTransfer.files);
                                                        });

                                                        function preventDefaults(e) {
                                                            e.preventDefault();
                                                            e.stopPropagation();
                                                        }

                                                        function highlight() {
                                                            dropArea.classList.add('highlight');
                                                        }

                                                        function unhighlight() {
                                                            dropArea.classList.remove('highlight');
                                                        }

                                                        function handleFiles(files) {
                                                            if (!files || files.length === 0) return;

                                                            for (let i = 0; i < files.length; i++) {
                                                                const file = files[i];
                                                                if (!file.type.match('image.*')) continue;

                                                                const reader = new FileReader();

                                                                reader.onload = function(e) {
                                                                    const previewItem = document.createElement('div');
                                                                    previewItem.className = 'preview-item';

                                                                    const img = document.createElement('img');
                                                                    img.src = e.target.result;
                                                                    img.alt = file.name;

                                                                    const removeBtn = document.createElement('button');
                                                                    removeBtn.className = 'remove-btn';
                                                                    removeBtn.innerHTML = '×';
                                                                    removeBtn.addEventListener('click', function(e) {
                                                                        e.stopPropagation();
                                                                        previewItem.remove();
                                                                    });

                                                                    previewItem.appendChild(img);
                                                                    previewItem.appendChild(removeBtn);
                                                                    previewContainer.appendChild(previewItem);
                                                                }

                                                                reader.readAsDataURL(file);
                                                            }
                                                        }

                                                        // Edit product handler
                                                        $('body').on('click', '.edit', function() {
                                                            let csrfToken = $('meta[name="csrf-token"]').attr('content');
                                                            let id = $(this).data('id');

                                                            $.ajax({
                                                                url: '{{ route('admin.product.edit', ['id' => 'id']) }}'.replace('id', id),
                                                                method: 'GET',
                                                                success: function(response) {
                                                                    console.log(response);
                                                                    $('#product_modalform').modal('show');
                                                                    $('#update_id').val(response.id);
                                                                    $('#edit_pro_name').val(response.product_name);
                                                                    $('#edit_producttags').val(response.product_tags);
                                                                    $('#edit_qty').val(response.qty);
                                                                    $('#edit_product_price').val(response.product_price);
                                                                    $('#edit_cutted_price').val(response.cutted_price);
                                                                    $('#edit_weight').val(response.weight);
                                                                    $('#edit_product_group').val(response.sku);
                                                                    $("#editproduct_description").summernote('code', response
                                                                        .product_description);

                                                                  const allowDealToggle = $('#allowDealToggle');
            const dealDiv = $('#dealDiv'); // The div you want to show/hide

            // Set initial toggle state and show/hide div
            if (response.dealcheck ) {
                allowDealToggle.prop('checked', true);
                dealDiv.show(); // Show the div when deal is active
            } else {
                allowDealToggle.prop('checked', false);
                dealDiv.show(); // Hide the div when deal is inactive
            }
                                                                    // Clear existing previews
                                                                    previewContainer.innerHTML = '';
                                                                    existingImagesContainer.innerHTML = '';

                                                                    // Handle product images
                                                                    let productImages = response.product_image.split(',');
                                                                    productImages.forEach(function(imageUrl) {
                                                                        if (imageUrl.trim() === '') return;

                                                                        let fullImageUrl = '/admin/assets/img/product/' + imageUrl;

                                                                        let existingItem = document.createElement('div');
                                                                        existingItem.className = 'existing-image-item';

                                                                        let img = document.createElement('img');
                                                                        img.src = fullImageUrl;

                                                                        let deleteBtn = document.createElement('button');
                                                                        deleteBtn.className = 'delete-image-btn';
                                                                        deleteBtn.innerHTML = '×';
                                                                        deleteBtn.setAttribute('data-image', imageUrl);
                                                                        deleteBtn.addEventListener('click', function() {
                                                                            if (confirm(
                                                                                    'Are you sure you want to delete this image?'
                                                                                )) {
                                                                                deleteimg(imageUrl, id);

                                                                            }
                                                                        });

                                                                        existingItem.appendChild(img);
                                                                        existingItem.appendChild(deleteBtn);
                                                                        existingImagesContainer.appendChild(existingItem);
                                                                    });
                                                                },
                                                                error: function(error) {
                                                                    console.error(error);
                                                                }
                                                            });
                                                        });

                                                        function deleteimg(imgurl, imgid) {
                                                            console.log(imgurl, imgid);
                                                            var imageUrl = imgurl;
                                                            var id = imgid;

                                                            // AJAX request to delete the image
                                                            $.ajax({
                                                                url: "{{ route('ajax.delete.exsiting.image') }}", // Replace with your route for deleting images
                                                                method: 'POST',
                                                                data: {
                                                                    imageUrl: imageUrl,
                                                                    id: id
                                                                },
                                                                success: function(response) {
                                                                    // Handle success response (e.g., remove the image from the DOM)
                                                                    window.location.reload();
                                                                    $(this).closest('.image-wrapper').remove();

                                                                },
                                                                error: function(xhr, status, error) {
                                                                    // Handle error
                                                                    console.error(error);
                                                                }
                                                            });
                                                        }

                                                        // Update product handler
                                                        $('#update-product').click(function() {
                                                            let formData = new FormData();
                                                            let productId = $('#update_id').val();

                                                            // Add all form fields
                                                            formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
                                                            formData.append('id', productId);
                                                            formData.append('product_name', $('#edit_pro_name').val());
                                                            // Add other fields...

                                                            // Add new images
                                                            let fileInput = $('#edituploadImagesInput')[0];
                                                            if (fileInput.files.length > 0) {
                                                                for (let i = 0; i < fileInput.files.length; i++) {
                                                                    formData.append('images[]', fileInput.files[i]);
                                                                }
                                                            }


                                                        });
                                                    });
                                                </script>


                                            </div>


                                            <div class="col-md-12">
                                                <label for="product_description" class="form-label">Product
                                                    description</label>
                                                <textarea class="form-control" id="editproduct_description" rows="3" name="edit_productdescription"></textarea>
                                            </div>

                                            <div class="col-md-6">
                                                <label for="inputText" class="col-sm-12 col-form-label">Product
                                                    weight</label>
                                                <div class="input-group">
                                                    <input id="edit_weight" class="multisteps-form__input form-control"
                                                        type="number" placeholder="eg.100" name="editweight" />
                                                    <div class="input-group-append" style="background-color: #555;">
                                                        <span class="input-group-text">g</span>
                                                    </div>
                                                </div>
                                            </div>

                                        </div>
                                    </div>


                                    <div class="modal-footer">

                                        <button type="button" class="btn btn-primary" data-id=""
                                            id="updatebtn">Update</button>
                                    </div>
                                </form>
                            </div>

                        </div>
                    </div>
                </div>

            </div>
            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <div class="row mb-3">
                    <div class="col-md-3">
                        <label for="statusFilter">Filter by Status:</label>
                        <select id="statusFilter" class="form-control">
                            <option value="1">Active</option>
                            <option value="0">Deactive</option>
                            <option value="trash">Trash</option>
                        </select>
                    </div>
                </div>
                            <div class="table-responsive text-nowrap p-4">
                                <table class="table" id="product_table">
                                    <thead>
                                        <tr>
                                            <th>Product Group</th>
                                            <th>Product Name</th>
                                            <th>Category</th>
                                            <th>Qty</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>

                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                </div>


            </div>
            <style>
                /* Style for the drop zone */
                .drop-area {
                    border: 2px dashed #ccc;
                    border-radius: 5px;
                    padding: 20px;
                    text-align: center;
                    margin-bottom: 20px;
                    cursor: pointer;
                }

                .drop-area.highlight {
                    background-color: #f0f0f0;
                }

                .drop-area p {
                    margin: 0;
                }

                /* Style for the uploaded images */
                #galleryedit {
                    margin-top: 10px;
                }

                #galleryedit .carousel-item img {
                    border-radius: 5px;
                    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
                    transition: transform 0.3s ease;
                }

                #galleryedit .carousel-item img:hover {
                    transform: scale(1.1);
                }

                /* Style for the image container */
                .image-wrapper {
                    display: inline-block;
                    margin: 10px;
                    position: relative;
                }

                /* Style for the delete button */
                .delete-image-btn {
                    position: absolute;
                    top: 5px;
                    right: 5px;
                    background-color: #f00;
                    color: #fff;
                    border: none;
                    padding: 5px 10px;
                    border-radius: 50%;
                    cursor: pointer;
                    transition: background-color 0.3s ease;
                }

                .delete-image-btn:hover {
                    background-color: #c00;
                }

                /* Style for the uploaded image */
                .uploaded-image {
                    max-width: 100px;
                    /* Adjust this value as needed */
                    max-height: 100px;
                    /* Adjust this value as needed */
                    display: block;
                    border-radius: 5px;
                    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
                    transition: transform 0.3s ease;
                }

                .uploaded-image:hover {
                    transform: scale(1.1);
                }
            </style>

        </section>

        <script>
            $(document).ready(function() {
                $('#product_modalform').modal({
                    backdrop: 'static',
                    keyboard: false
                });
                $('.btn-close').on('click', function() {
                    window.location.reload();

                });
                $('#edit_job_description').summernote();

                $('#product_description').summernote();



            });
            // ************************ Drag and drop ***************** //
            let dropArea = document.getElementById("drop-area")

            // Prevent default drag behaviors
            ;
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropArea.addEventListener(eventName, preventDefaults, false)
                document.body.addEventListener(eventName, preventDefaults, false)
            })

            // Highlight drop area when item is dragged over it
            ;
            ['dragenter', 'dragover'].forEach(eventName => {
                dropArea.addEventListener(eventName, highlight, false)
            })

            ;
            ['dragleave', 'drop'].forEach(eventName => {
                dropArea.addEventListener(eventName, unhighlight, false)
            })

            // Handle dropped files
            dropArea.addEventListener('drop', handleDrop, false)

            function preventDefaults(e) {
                e.preventDefault()
                e.stopPropagation()
            }

            function highlight(e) {
                dropArea.classList.add('highlight')
            }

            function unhighlight(e) {
                dropArea.classList.remove('active')
            }

            function handleDrop(e) {
                var dt = e.dataTransfer
                var files = dt.files

                handleFiles(files)
            }

            let uploadProgress = []
            let progressBar = document.getElementById('progress-bar')

            function initializeProgress(numFiles) {
                progressBar.value = 0
                uploadProgress = []

                for (let i = numFiles; i > 0; i--) {
                    uploadProgress.push(0)
                }
            }

            function updateProgress(fileNumber, percent) {
                uploadProgress[fileNumber] = percent
                let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length
                console.debug('update', fileNumber, percent, total)
                progressBar.value = total
            }

            function handleFiles(files) {
                // Check if the number of files exceeds the limit (5 in this case)
                if (files.length > 5) {
                    Alert.error('An unexpected error occurred.You can only upload a maximum of 5 images.', 'Error', {
                        displayDuration: 3000
                    });
                    return;
                }
                files = [...files]
                // Proceed with uploading if within the limit
                initializeProgress(files.length);
                files.forEach(uploadFile);
                files.forEach(previewFile);
            }

            function previewFile(file) {
                let reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onloadend = function() {
                    let img = document.createElement('img')
                    img.src = reader.result
                    document.getElementById('gallery').appendChild(img)
                }
            }

            function uploadFile(file, i) {
                var url = 'https://api.cloudinary.com/v1_1/joezim007/image/upload'
                var xhr = new XMLHttpRequest()
                var formData = new FormData()
                xhr.open('POST', url, true)
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')

                // Update progress (can be used to show progress indicator)
                xhr.upload.addEventListener("progress", function(e) {
                    updateProgress(i, (e.loaded * 100.0 / e.total) || 100)
                })

                xhr.addEventListener('readystatechange', function(e) {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        updateProgress(i, 100) // <- Add this
                    } else if (xhr.readyState == 4 && xhr.status != 200) {
                        // Error. Inform the user
                    }
                })

                formData.append('upload_preset', 'ujpu6gyk')
                formData.append('file', file)
                xhr.send(formData)
            }

            document.addEventListener("DOMContentLoaded", function() {
                // Get references to the select-images paragraph and the file input
                var selectImagesText = document.getElementById("select-images");
                var fileInput = document.getElementById("edituploadImagesInput");

                // Add click event listener to the select-images paragraph
                selectImagesText.addEventListener("click", function() {
                    // Trigger click event on file input
                    fileInput.click();
                });

                // Add change event listener to the file input
                fileInput.addEventListener("change", function() {
                    // Handle selected files here (e.g., preview images)
                    var files = fileInput.files;
                    // Clear existing image previews
                    document.getElementById("image-preview").innerHTML = "";
                    // Iterate over selected files
                    for (var i = 0; i < files.length; i++) {
                        var file = files[i];
                        // Create image element for preview
                        var img = document.createElement("img");
                        img.src = URL.createObjectURL(file);
                        img.alt = "Image Preview";
                        img.style.maxWidth = "100px"; // Adjust as needed
                        img.style.maxHeight = "100px"; // Adjust as needed
                        // Append image to image-preview container
                        document.getElementById("image-preview").appendChild(img);
                    }
                });
            });
        </script>
        <script>
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });




            function validateForm() {
                var name = document.getElementById("pro_name").value.trim();
                var product_tags = document.getElementById("producttags").value.trim();
                var imageInput = document.getElementById('fileElem');
                var description = document.getElementById('product_description');
                var productprice = document.getElementById('product_price');
                var productgroup = document.getElementById('product_group');


                // Add more validations as needed
                if (name === "" || product_tags === "" || imageInput.files.length === 0 || description === "" ||
                    productprice === "" || productgroup === "") {
                    Alert.info('Info! All fields are required. Please fill out every field before submitting.', 'Info', {
                        displayDuration: 3000
                    })
                    return false;
                } else {
                    var add_product = $('#product_form')[0];
                    var add_product_ajax = new FormData(add_product);

                    // Append multiple files
                    var files = $('#fileElem')[0].files;
                    for (var i = 0; i < files.length; i++) {
                        add_product_ajax.append('images[]', files[i]);
                    }

                    $.ajax({
                        type: 'POST',
                        url: "{{ route('admin.add.new.product') }}",
                        data: add_product_ajax,
                        contentType: false,
                        processData: false,
                        success: function(response) {
                            if (response) {
                                resetForm();
                                Alert.success('Success! The Product has been successfully added.', 'Success', {
                                    displayDuration: 3000,
                                    pos: 'top'
                                });
                                var selectedColors = add_product_ajax.getAll('colors[]');

                                var selectedSizes = add_product_ajax.getAll('sizes[]');

                                var selectedColor = selectedColors.length > 0 ? selectedColors[0] : "None";
                                var selectedSize = selectedSizes.length > 0 ? selectedSizes[0] : "None";

                                var summernoteInstance = $('#product_description').summernote();

                                summernoteInstance.summernote('reset');
                                table.ajax.reload();
                                window.location.reload();
                            }
                        },
                        error: function(response) {
                            Alert.error('An unexpected error occurred. Please try again later. ', 'Error', {
                                displayDuration: 3000
                            });
                        }
                    }).always(function() {});


                }

            }
$('#statusFilter').on('change', function() {
    table.ajax.reload(); // This will reload the DataTable with the new status filter
});
            function resetForm() {
                document.getElementById('product_form').reset();
            }

            var table = $('#product_table').DataTable({
                processing: true,
                serverSide: true,
          ajax: {
        url: "{{ route('admin.product.data.get') }}",
        data: function (d) {
            d.status = $('#statusFilter').val();
        }
    },
                columns: [{
                        data: 'sku',
                        name: 'sku'
                    },
                    {
                        data: 'product_name',
                        name: 'product_name'
                    },
                    {
                        data: 'category',
                        name: 'category'
                    },
                    {
                        data: 'productqty',
                        name: 'productqty'
                    },
                    {
                        data: 'status',
                        name: 'status'
                    },

                    {
                        data: 'action',
                        name: 'action',
                        orderable: false,
                        searchable: false
                    },
                ]
            });




            $(document).on('click', '.addcolor', function() {
                var id = $(this).data('id');
                window.location.href = '{{ route('admin.product.addcolor') }}?id=' + id;
            });
              $(document).on('click', '.deactivate', function() {
                var id = $(this).data('id');
                window.location.href = '{{ route('admin.product.deactive') }}?id=' + id;
            });

              $(document).on('click', '.activate', function() {
                var id = $(this).data('id');
                window.location.href = '{{ route('admin.product.activate') }}?id=' + id;
            });
            // Assume this code is inside a $(document).ready() function or after the modal HTML is loaded
            // $(document).on('click', '.delete-image-btn', function() {
            //     // Get the image URL from the data-url attribute

            // });

            // Handle delete button click
            $('body').on('click', '.delete-image-btn', function() {
                let imageUrl = $(this).data('url');

                // Perform delete operation here, such as removing the image from the UI or sending an AJAX request to delete it from the server

                // For example, to remove the image from the UI:
                $(this).parent('.image-wrapper').remove();
            });


            $('body').on('click', '#updatebtn', function() {
                var name = document.getElementById("edit_pro_name").value.trim();
                var product_tags = document.getElementById("edit_producttags").value.trim();
                var qty = document.getElementById('edit_qty').value.trim();
                var imageInput = document.getElementById('edituploadImagesInput');
                // Validation checks
                var isValid = true;
                var errorMessage = "";


                if (imageInput.files.length > 0) {
                    for (var i = 0; i < imageInput.files.length; i++) {
                        var file = imageInput.files[i];

                        // Only process image files
                        if (!file.type.match('image.*')) {
                            continue;
                        }

                        var reader = new FileReader();

                        reader.onload = function(e) {
                            var img = new Image();
                            img.onload = function() {
                                if (this.width !== 500 || this.height !== 500) {
                                    isValid = false;
                                    errorMessage = "All images must be exactly 500x500 pixels.";
                                    Alert.info('Info! All images must be exactly 500x500 pixels', 'Info', {
                                        displayDuration: 4000
                                    });
                                }
                            };
                            img.src = e.target.result;
                        };

                        reader.readAsDataURL(file);
                    }
                }
                // If validation fails, show error and return
                if (!isValid) {
                    Alert.info('Info! Validation Error', 'Info', {
                        displayDuration: 3000
                    });
                    return false;
                } else {
                    var update_product = $('#editproduct_form')[0];
                    var update_category_ajax = new FormData(update_product);

                    $.ajax({
                            type: 'POST',
                            url: "{{ route('ajax.update.exsiting.product') }}",
                            data: update_category_ajax,
                            contentType: false,
                            processData: false,
                            success: (response) => {
                                // Hide modal immediately
                                $('#product_modalform').modal('hide');

                                // Reload table immediately
                                table.ajax.reload();

                                // Show success message after 2 seconds (2000 milliseconds)
                                setTimeout(() => {
                                    Alert.success('Success! The post has been successfully updated.',
                                        'Success', {
                                            displayDuration: 3000,
                                            pos: 'top'
                                        });

                                    // Reload window after showing the alert (optional)
                                    window.location.reload();
                                }, 2000);
                            },
                            error: function(response) {
                                Alert.error('An unexpected error occurred. Please try again later. ', 'Error', {
                                    displayDuration: 3000
                                });
                            }
                        })
                        .always(function() {});
                }

            });


            $('body').on('click', '.delete', function() {
                let csrfToken = $('meta[name="csrf-token"]').attr('content');
                let productId = $(this).data('id');
                if (confirm('Are you sure you want to delete this product? It can be restored from the Trash later.')) {
                    $.ajax({
                        type: "POST", // or "GET" depending on your route configuration
                        url: "{{ route('delete.product', ':productId') }}".replace(':productId', productId),
                        headers: {
                            'X-CSRF-TOKEN': csrfToken
                        }, // replace with the actual route URL
                        success: function(response) {
                            // Handle the success response from the server
                            Alert.trash('Delete! The Product has been moved to trash.', 'Delete', {
                                displayDuration: 3000
                            });
                            table.ajax.reload();
                        },
                        error: function(error) {
                            Alert.error(
                                'An error occurred while deleting the product. Please try again later. ',
                                'Error', {
                                    displayDuration: 3000
                                });
                        }
                    });
                }
            });

            $(document).on('click', '.restore', function() {
                let csrfToken = $('meta[name="csrf-token"]').attr('content');
                let productId = $(this).data('id');
                $.ajax({
                    type: "POST",
                    url: "{{ route('restore.product', ':productId') }}".replace(':productId', productId),
                    headers: {
                        'X-CSRF-TOKEN': csrfToken
                    },
                    success: function(response) {
                        Alert.success('Success! The Product has been successfully restored.', 'Restore', {
                            displayDuration: 3000
                        });
                        table.ajax.reload();
                    },
                    error: function(error) {
                        Alert.error(
                            'An error occurred while restoring the product.',
                            'Error', {
                                displayDuration: 3000
                            });
                    }
                });

            });
        </script>
    </main><!-- End #main -->
@endsection
