@extends('admin.layout.dashboard_master')

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

        <div class="pagetitle">
            @php
                $productData = App\Models\Product::where('id', $id)->first();
            @endphp
            <h1>Product/{{ $productData->product_name }}/Colors</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>
                    <li class="breadcrumb-item active">Product Colors</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 colors form</h5>
                            <!-- General Form Elements -->
                            <form id="productcolor_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">
                                                    <!-- End Upload Area -->
                                                    <div class="col-md-12 py-2">
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <input type="text" name="product_id"
                                                                    value="{{ $id }}" hidden>
                                                                <!-- Color Select Option -->
                                                                <div class="form-group">
                                                                    <label for="color-select">Select Color(s):</label>
                                                                    <select class="form-control" id="color-select"
                                                                        name="color">
                                                                        <option value="#A78B8D"
                                                                            style="background-color: #A78B8D;">Marble Pink
                                                                        </option>
                                                                        <option value="#C55C82"
                                                                            style="background-color: #c55c82;">Pink</option>
                                                                        <option value="#FFFFFF"
                                                                            style="background-color: #ffffff;">Pure White
                                                                        </option>
                                                                        <option value="#88DB86"
                                                                            style="background-color: #88db86;">Apple Green
                                                                        </option>
                                                                        <option value="#DEE4EE"
                                                                            style="background-color: #dee4ee;">Marble White
                                                                        </option>
                                                                        <option value="#BDB8EE"
                                                                            style="background-color: #bdb8ee;">Marble Violet
                                                                        </option>
                                                                        <option value="#FEF250"
                                                                            style="background-color: #fef250;">Lemon Yellow
                                                                        </option>
                                                                        <option value="#f4c2c2"
                                                                            style="background-color: #f4c2c2;">Baby Pink
                                                                        </option>
                                                                        <option value="#D2C77D"
                                                                            style="background-color: #d2c77d;">Metallic Gold
                                                                        </option>
                                                                        <option value="#DAD9C6"
                                                                            style="background-color: #dad9c6;">Buttermilk
                                                                        </option>
                                                                        <option value="#D3CBC4"
                                                                            style="background-color: #d3cbc4;">Gray Beige
                                                                        </option>
                                                                        <option value="#BF8BFF"
                                                                            style="background-color: #bf8bff;">Violet
                                                                        </option>
                                                                        <option value="#C0C0C0"
                                                                            style="background-color: #c0c0c0;">Silver
                                                                        </option>
                                                                        <option value="#808080"
                                                                            style="background-color: #808080;">Gray</option>

                                                                        <option value="#13598B"
                                                                            style="background-color: #13598B;">Metallic Blue
                                                                        </option>
                                                                        <option value="#9582BB"
                                                                            style="background-color: #9582bb;">Metallic
                                                                            Violet</option>
                                                                        <option value="#A286F4"
                                                                            style="background-color: #a286f4;">Purple
                                                                        </option>
                                                                        <option value="#80355C"
                                                                            style="background-color: #80355c;">Marble Red
                                                                        </option>
                                                                        <option value="#2FCBD4"
                                                                            style="background-color: #2FCBD4;">Avocado Green
                                                                        </option>
                                                                        <option value="#61A8F8"
                                                                            style="background-color: #61a8f8;">Baby Blue
                                                                        </option>
                                                                        <option value="#FF0000"
                                                                            style="background-color: #ff0000;">Red</option>
                                                                        <option value="#CAD3D0"
                                                                            style="background-color: #cad3d0; opacity:0.5;">
                                                                            Clear</option>
                                                                        <option value="#BA9978"
                                                                            style="background-color: #ba9978;">Beige
                                                                        </option>
                                                                        <option value="#E9CBB9"
                                                                            style="background-color: #e9cbb9;">Marble Orange
                                                                        </option>
                                                                        <option value="#E9C500"
                                                                            style="background-color: #e9c500;">Yellow
                                                                        </option>
                                                                        <option value="#0F2D8D"
                                                                            style="background-color: #0f2d8d;">Blue</option>
                                                                        <option value="#005E3A"
                                                                            style="background-color: #005e3a;">Green
                                                                        </option>
                                                                        <option value="#6B4B36"
                                                                            style="background-color: #6b4b36;">Brown
                                                                        </option>
                                                                        <option value="#6CD2FA"
                                                                            style="background-color: #6cd2fa;">Sky Blue
                                                                        </option>
                                                                        <option value="#D09305"
                                                                            style="background-color: #d09305;">Orange
                                                                        </option>
                                                                        <option value="#62ADE6"
                                                                            style="background-color: #62ade6;">Marble Blue
                                                                        </option>
                                                                        <option value="#D4AF37"
                                                                            style="background-color: #D4AF37;">Marble gold
                                                                        </option>
                                                                        <option value="#FFA07A"
                                                                            style="background-color: #ffa07a;">Light Orange
                                                                        </option>
                                                                        <option value="#DDD3D1"
                                                                            style="background-color: #DDD3D1;">Marble Beige
                                                                        </option>
                                                                        <option value="#58C3C2"
                                                                            style="background-color: #58C3C2;">Marble Green
                                                                        </option>
                                                                        <option value="#B4B4B8"
                                                                            style="background-color: #B4B4B8;">Metalic
                                                                            silver</option>
                                                                        <option value="#F4C430"
                                                                            style="background-color: #f4c430;">Saffron
                                                                        </option>
                                                                        <option value="#000000"
                                                                            style="background-color: #000000;">Black
                                                                        </option>

                                                                        <option value="#3D7764"
                                                                            style="background-color: #3D7764;">Metalicgreen
                                                                        </option>
                                                                        <option value="#F8B700"
                                                                            style="background-color: #F8B700;">
                                                                            Metalicyellow
                                                                        </option>
                                                                        <option value="#6F4E37"
                                                                            style="background-color: #6F4E37;">Coffee
                                                                        </option>
                                                                        <option value="#FFFDD0"
                                                                            style="background-color: #FFFDD0;">Cream
                                                                        </option>
                                                                        <option value="#A9A9A9"
                                                                            style="background-color: #A9A9A9;">Dark Gray
                                                                        </option>
                                                                        <option value="#006A4E"
                                                                            style="background-color: #006A4E;">Bottle Green
                                                                        </option>



                                                                        <!-- Add more color options as needed -->
                                                                    </select>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label for="price-input-label">Price</label>
                                                                    <div class="input-group">
                                                                        <div class="input-group-prepend">
                                                                            <span class="input-group-text">LKR</span>
                                                                        </div>
                                                                        <input type="number" name="color_price"
                                                                            class="form-control" id="price-input"
                                                                            required>
                                                                    </div>
                                                                </div>

                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label for="qty-input-label">Qty</label>
                                                                    <div class="input-group">

                                                                        <input type="number" name="color_qty"
                                                                            class="form-control" id="color-qty" required>
                                                                    </div>
                                                                </div>

                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label for="qty-input-label">Code</label>
                                                                    <div class="input-group">

                                                                        <input type="text" name="code"
                                                                            class="form-control" id="productcode"
                                                                            required>
                                                                    </div>
                                                                </div>

                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label for="recycling-points-label">Recycling Points</label>
                                                                    <div class="input-group">
                                                                        <input type="number" name="recycling_points"
                                                                            class="form-control" id="recycling-points"
                                                                            value="0" required>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>


                                                </div>
                                            </div>



                                            <!-- Drop Zoon -->
                                            <label for="inputText" class="col-sm-8 col-form-label">
                                                Product Image <span class="text-muted">(Only one image is accepted)</span>
                                            </label>
                                            <div id="drop-area">
                                                <p>Upload an image with the file dialog or by dragging and dropping it onto
                                                    the dashed region</p>
                                                <input type="file" id="fileElem" accept="image/*"
                                                    onchange="handleFile(this.files)" name="image">
                                                <label class="button" for="fileElem">Select file</label>
                                                <progress id="progress-bar" max=100 value=0></progress>
                                                <div id="gallery"></div>
                                            </div>
                                            <script>
                                                function handleFile(files) {
                                                    const gallery = document.getElementById('gallery');
                                                    gallery.innerHTML = ''; // Clear any existing images
                                                    if (files.length > 0) {
                                                        const file = files[0];
                                                        if (file.type.startsWith('image/')) {
                                                            const img = document.createElement('img');
                                                            img.classList.add('obj');
                                                            img.file = file;
                                                            gallery.appendChild(img);

                                                            const reader = new FileReader();
                                                            reader.onload = (function(aImg) {
                                                                return function(e) {
                                                                    aImg.src = e.target.result;
                                                                };
                                                            })(img);
                                                            reader.readAsDataURL(file);
                                                        } else {
                                                            alert('Please upload an image file.');
                                                        }
                                                    } else {
                                                        alert('Please select an image to upload.');
                                                    }
                                                }
                                            </script>

                                        </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()">Add</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="productcolor_modal" tabindex="-1" role="dialog"
                    aria-labelledby="assignRoleModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered" role="document">
                        <div class="modal-content border-0">
                            <div class="modal-header bg-primary text-white">
                                <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Product Details</h5>
                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                                    aria-label="Close"></button>
                            </div>

                            <div class="modal-body">
                                <form id="edit_colorform" class="needs-validation" novalidate>
                                    <!-- Price Field -->
                                    <div class="mb-3">
                                        <label for="edit_price" class="form-label fw-bold">Price <span
                                                class="text-danger">*</span></label>
                                        <div class="input-group">
                                            <span class="input-group-text">LKR</span>
                                            <input type="number" class="form-control" id="edit_price"
                                                name="update_price" required>
                                            <div class="invalid-feedback">
                                                Please enter a valid price
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="edit_qty" class="form-label fw-bold">Qty <span
                                                class="text-danger">*</span></label>
                                        <input type="number" class="form-control" id="edit_qty" name="edit_color_qty"
                                            required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="edit_code" class="form-label fw-bold">Code <span
                                                class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="edit_code" name="edit_color_code"
                                            required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="edit_recycling_points" class="form-label fw-bold">Recycling Points <span
                                                class="text-danger">*</span></label>
                                        <input type="number" class="form-control" id="edit_recycling_points" name="edit_recycling_points"
                                            required>
                                    </div>

                                    <!-- Color Selection -->
                                    <div class="mb-2">
                                        <label for="color-select" class="form-label fw-bold">Color <span
                                                class="text-danger">*</span></label>
                                        <select class="form-select" id="edit-color-select" name="color" required>
                                            <option value="" selected disabled>Select a color</option>
                                            <option value="#A78B8D" style="background-color: #A78B8D;">Marble Pink
                                            </option>
                                            <option value="#C55C82" style="background-color: #c55c82;">Pink</option>
                                            <option value="#FFFFFF" style="background-color: #ffffff;">Pure White</option>
                                            <option value="#88DB86" style="background-color: #88db86;">Apple Green
                                            </option>
                                            <option value="#DEE4EE" style="background-color: #dee4ee;">Marble White
                                            </option>
                                            <option value="#BDB8EE" style="background-color: #bdb8ee;">Marble Violet
                                            </option>
                                            <option value="#FEF250" style="background-color: #fef250;">Lemon Yellow
                                            </option>
                                            <option value="#f4c2c2" style="background-color: #f4c2c2;">Baby Pink</option>
                                            <option value="#D2C77D" style="background-color: #d2c77d;">Metallic Gold
                                            </option>
                                            <option value="#DAD9C6" style="background-color: #dad9c6;">Buttermilk</option>
                                            <option value="#D3CBC4" style="background-color: #d3cbc4;">Gray Beige</option>
                                            <option value="#BF8BFF" style="background-color: #bf8bff;">Violet</option>
                                            <option value="#C0C0C0" style="background-color: #c0c0c0;">Silver</option>
                                            <option value="#808080" style="background-color: #808080;">Gray</option>

                                            <option value="#13598B" style="background-color: #13598B;">Metallic Blue
                                            </option>
                                            <option value="#9582BB" style="background-color: #9582bb;">Metallic Violet
                                            </option>
                                            <option value="#A286F4" style="background-color: #a286f4;">Purple</option>
                                            <option value="#80355C" style="background-color: #80355c;">Marble Red</option>
                                            <option value="#2FCBD4" style="background-color: #2FCBD4;">Avocado Green
                                            </option>
                                            <option value="#61A8F8" style="background-color: #61a8f8;">Baby Blue</option>
                                            <option value="#FF0000" style="background-color: #ff0000;">Red</option>
                                            <option value="#CAD3D0" style="background-color: #cad3d0; opacity:0.5;">Clear
                                            </option>
                                            <option value="#BA9978" style="background-color: #ba9978;">Beige</option>
                                            <option value="#E9CBB9" style="background-color: #e9cbb9;">Marble Orange
                                            </option>
                                            <option value="#E9C500" style="background-color: #e9c500;">Yellow</option>
                                            <option value="#0F2D8D" style="background-color: #0f2d8d;">Blue</option>
                                            <option value="#005E3A" style="background-color: #005e3a;">Green</option>
                                            <option value="#6B4B36" style="background-color: #6b4b36;">Brown</option>
                                            <option value="#6CD2FA" style="background-color: #6cd2fa;">Sky Blue</option>
                                            <option value="#D09305" style="background-color: #d09305;">Orange</option>
                                            <option value="#62ADE6" style="background-color: #62ade6;">Marble Blue
                                            </option>
                                            <option value="#D4AF37" style="background-color: #D4AF37;">Marble gold
                                            </option>
                                            <option value="#FFA07A" style="background-color: #ffa07a;">Light Orange
                                            </option>
                                            <option value="#DDD3D1" style="background-color: #DDD3D1;">Marble Beige
                                            </option>
                                            <option value="#58C3C2" style="background-color: #58C3C2;">Marble Green
                                            </option>
                                            <option value="#B4B4B8" style="background-color: #B4B4B8;">Metalic silver
                                            </option>
                                            <option value="#F4C430" style="background-color: #f4c430;">Saffron</option>
                                            <option value="#000000" style="background-color: #000000;">Black</option>
                                            <option value="#3D7764"style="background-color: #3D7764;">Metalicgreen</option>
                                            <option value="#F8B700" style="background-color: #F8B700;">Metalicyellow
                                            </option>
                                            <option value="#6F4E37" style="background-color: #6F4E37;">Coffee</option>
                                            <option value="#FFFDD0" style="background-color: #FFFDD0;">Cream</option>
                                            <option value="#A9A9A9" style="background-color: #A9A9A9;">Dark Gray</option>
                                            <option value="#006A4E" style="background-color: #006A4E;">Bottle Green
                                            </option>

                                        </select>
                                        <div class="invalid-feedback">
                                            Please select a color
                                        </div>
                                        <!-- Persistent note -->
                                        {{-- <div class="mt-2 text-muted small">
                                            <i class="fas fa-info-circle text-primary me-1"></i>
                                            <em>Note: When changing price, please select the corresponding color</em>
                                        </div> --}}
                                    </div>

                                    <div class="mb-3">
                                        <label for="edit_color_image" class="form-label fw-bold">Color Image <span
                                                class="text-danger">*</span></label>
                                        <input type="file" class="form-control" id="edit_color_image"
                                            name="color_image" accept="image/*">
                                        <div class="invalid-feedback">
                                            Please upload an image for this color
                                        </div>
                                        <small class="text-muted">Accepted formats: JPG, PNG, GIF. Max size: 2MB</small>
                                        <!-- Image preview container -->
                                        <div class="mt-2">
                                            <img id="edit_color_image_preview" src="#" alt="Image preview"
                                                class="img-thumbnail d-none" style="max-height: 150px;">
                                        </div>
                                        <script>
                                            document.getElementById('edit_color_image').addEventListener('change', function(e) {
                                                const preview = document.getElementById('edit_color_image_preview');
                                                const file = e.target.files[0];

                                                if (file) {
                                                    const reader = new FileReader();

                                                    reader.onload = function(e) {
                                                        preview.src = e.target.result;
                                                        preview.classList.remove('d-none');
                                                    }

                                                    reader.readAsDataURL(file);
                                                } else {
                                                    preview.src = '#';
                                                    preview.classList.add('d-none');
                                                }
                                            });
                                        </script>
                                    </div>
                                    <input type="hidden" id="update_id" name="updateid">
                                </form>
                            </div>

                            <div class="modal-footer">
                                <button type="button" class="btn btn-outline-secondary"
                                    data-bs-dismiss="modal">Cancel</button>
                                <button type="button" class="btn btn-primary" id="updatebtn">Save Changes</button>
                            </div>
                        </div>
                    </div>
                </div>

                <style>
                    #productcolor_modal .form-control:focus,
                    #productcolor_modal .form-select:focus {
                        border-color: #86b7fe;
                        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
                    }

                    #productcolor_modal .is-invalid {
                        border-color: #dc3545;
                    }

                    #productcolor_modal .is-invalid:focus {
                        box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
                    }
                </style>

                <script>
                    document.addEventListener('DOMContentLoaded', function() {
                        const form = document.getElementById('edit_colorform');
                        const priceInput = document.getElementById('edit_price');
                        const colorSelect = document.getElementById('color-select');

                        // Real-time validation for price changes
                        priceInput.addEventListener('input', function() {
                            if (this.value && !colorSelect.value) {
                                colorSelect.classList.add('is-invalid');
                            } else {
                                colorSelect.classList.remove('is-invalid');
                            }
                        });

                        // Form submission validation
                        document.getElementById('updatebtn').addEventListener('click', function() {
                            if (!form.checkValidity()) {
                                form.classList.add('was-validated');

                                // Special case: if price has value but color doesn't
                                if (priceInput.value && !colorSelect.value) {
                                    colorSelect.focus();
                                }
                                return;
                            }

                            // Proceed with form submission
                            // ...
                        });
                    });
                </script>

                <!-- Font Awesome for icons -->
                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
            </div>
            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive text-nowrap p-4">
                                <table class="table" id="product_color_table">
                                    <thead>
                                        <tr>
                                            <th>Product ID</th>
                                            <th>Color</th>
                                            <th>Image</th>
                                            <th>Price</th>
                                            <th>Qty</th>
                                            <th>Code</th>
                                            <th>Points</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 imageInput = document.getElementById('fileElem');
                var colorSelect = document.getElementById('color-select');
                var priceField = document.getElementById('price-input');
                var qtyField = document.getElementById('color-qty');
                var colorproductField = document.getElementById('productcode');


                // Helper function to validate image size
                function validateImageSize(file, callback) {
                    var img = new Image();
                    var objectUrl = URL.createObjectURL(file);

                    img.onload = function() {
                        URL.revokeObjectURL(objectUrl);
                        callback(img.width === 500 && img.height === 500);
                    };

                    img.src = objectUrl;
                }

                // Check for required fields
                if (imageInput.files.length === 0 || colorSelect.value === "" || priceField.value === "" || qtyField.value ===
                    "" || colorproductField.value === "") {
                    Alert.info('Info! All fields are required. Please fill out every field before submitting.', 'Info', {
                        displayDuration: 3000
                    });
                    return false;
                }

                // Validate image dimensions
                var file = imageInput.files[0];
                validateImageSize(file, function(isValid) {
                    if (!isValid) {
                        Alert.info('Info! Image size should be exactly 500x500 pixels.', 'Info', {
                            displayDuration: 3000
                        });
                        return false;
                    } else {
                        // Proceed with form submission via AJAX if everything is valid
                        var add_product = $('#productcolor_form')[0];
                        var add_product_ajax = new FormData(add_product);

                        $.ajax({
                            type: 'POST',
                            url: "{{ route('admin.add.product.color') }}",
                            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'
                                        });

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

                // Prevent form submission to wait for image validation
                return false;
            }

            // Example form submission
            var form = document.getElementById('productcolor_form');
            form.addEventListener('submit', function(event) {
                event.preventDefault();
                validateForm();
            });


            function resetForm() {
                document.getElementById('productcolor_form').reset();
            }
            var productId = {{ $id }};
            var table = $('#product_color_table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('admin.product.color.data.get', ['productId' => ':productId']) }}".replace(
                        ':productId', productId),
                    dataSrc: 'data', // Adjust based on your API response structure
                },
                columns: [{
                        data: 'product_id',
                        name: 'product_id'
                    },
                    {
                        data: 'product_color',
                        name: 'product_color',

                    },

                    {
                        data: 'image',
                        name: 'image'
                    },
                    {
                        data: 'price',
                        name: 'price'
                    },
                    {
                        data: 'pc_qty',
                        name: 'pc_qty'
                    },
                    {
                        data: 'code',
                        name: 'code'
                    },
                    {
                        data: 'recycling_points',
                        name: 'recycling_points'
                    },
                    {
                        data: 'status',
                        name: 'status'
                    },


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


            $('body').on('click', '.edit_price', function() {
                let csrfToken = $('meta[name="csrf-token"]').attr('content');
                let id = $(this).data('id');
                $.ajax({
                    type: "GET", // or "GET" depending on your route configuration
                    url: "{{ route('edit.colorid', ':id') }}".replace(':id', id),
                    headers: {
                        'X-CSRF-TOKEN': csrfToken
                    }, // replace with the actual route URL
                    success: function(response) {

                        $('#productcolor_modal').modal('show');

                        $('#update_id').val(response.id);
                        $('#edit_price').val(response.price);
                        $('#edit_qty').val(response.pc_qty);
                        $('#edit_code').val(response.code);
                        $('#edit_recycling_points').val(response.recycling_points);


                        $('#edit-color-select').val(response.product_color);
                        table.ajax.reload();


                    },
                    error: function(error) {

                    }
                });

            });


            $('body').on('click', '#updatebtn', function() {
                var edit_color = $('#edit_colorform')[0];
                var edit_color_ajax = new FormData(edit_color);
                $.ajax({
                        type: 'POST',
                        url: "{{ route('ajax.update.exsiting.color') }}",
                        data: edit_color_ajax,
                        contentType: false,
                        processData: false,
                        success: (response) => {
                            if (response) {
                                Alert.success(
                                    'Success! The product color details has been successfully updated.',
                                    'Success', {
                                        displayDuration: 3000,
                                        pos: 'top'
                                    });
                                $('#productcolor_modal').modal('hide');
                                table.ajax.reload();

                            }
                        },
                        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 id = $(this).data('id');
                $.ajax({
                    type: "POST", // or "GET" depending on your route configuration
                    url: "{{ route('delete.colorid', ':id') }}".replace(':id', id),
                    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 color has been successfully deleted.', 'Delete', {
                            displayDuration: 3000
                        });
                        table.ajax.reload();


                    },
                    error: function(error) {
                        Alert.error(
                            'There are currently ongoing orders associated with this product. Please try again later. ',
                            'Error', {
                                displayDuration: 3000
                            });
                    }
                });

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