@extends('layouts.admin-layout')
@section('title')
    Edit Product
@endsection
{{-- @dd($product->colour_ids) --}}
@section('content')
    <style>
        .active {
            background-color: #007BFF !important;
            color: white !important;
        }

        .rating {
            width: 400px;
            height: 50px;
            margin: 0 auto;
            padding: 1px 99px;
            border: 1px solid #ccc;
            border-radius: 10px;
            background: #f9f9f9;
        }

        .rating label {
            float: right;
            position: relative;
            width: 40px;
            height: 40px;
            cursor: pointer;
        }

        .rating label:not(:first-of-type) {
            padding-right: 2px;
        }

        .rating label:before {
            content: "\2605";
            font-size: 42px;
            color: #ccc;
            line-height: 1;
        }

        .rating label.active-star::before {
            color: #f9df4a;
        }

        .rating input {
            display: none;
        }

        .rating input:checked~label:before,
        .rating:not(:checked)>label:hover:before,
        .rating:not(:checked)>label:hover~label:before {
            color: #f9df4a;
        }
    </style>
    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-12">

                        <div class="card card-box-shadow mt-5">

                            <div class="card-header">
                                <h3 class="card-title">Edit Product</h3>
                                <a href="{{ route('admin.product.list') }}" class="btn btn-primary btn-sm float-right mr-5 ">

                                    Back

                                </a>
                            </div>
                            <!-- /.card-header -->
                            <div class="card-body">

                                <form action="{{ route('admin.product.update', $find_product->id) }}" method="POST"
                                    enctype="multipart/form-data">
                                    @csrf
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="Name">Product Name *</label>
                                                <input type="text" class="form-control form__field" name="name"
                                                    value="{{ $find_product->name ?? '' }}">
                                            </div>

                                            <small class="text-danger">
                                                @error('name')
                                                    {{ $message }}
                                                @enderror
                                            </small>
                                        </div>
                                        <div class="col-md-6">
                                            <label for="">Product Price *</label>
                                            <input type="number" step="0.01" min="0"
                                                onkeypress="return!(event.charCode == 45)" class="form-control form__field"
                                                name="price" value="{{ $find_product->price ?? '' }}">
                                            <small class="text-danger">
                                                @error('price')
                                                    {{ $message }}
                                                @enderror
                                            </small>

                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="category_id">Category</label>
                                                <select name="category_id" class="form-control form__field">
                                                    <option value="" disabled>Select Category</option>
                                                    @foreach ($categories as $category)
                                                        <option value="{{ $category->id }}"
                                                            {{ $find_product->category_id == $category->id ? 'selected' : '' }}>
                                                            {{ $category->name }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>

                                            <small class="text-danger">
                                                @error('name')
                                                    {{ $message }}
                                                @enderror
                                            </small>
                                        </div>


                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="category_id">Color</label>
                                                <select name="colour_id[]" class="form-control form__field selectpicker"
                                                    multiple data-live-search="true">
                                                    <option value="" disabled>Select Colour</option>
                                                    @foreach ($colors as $color)
                                                        <option value="{{ $color->id }}"
                                                            {{ in_array($color->id, $find_product->colors->pluck('id')->toArray()) ? 'selected' : '' }}>
                                                            {{ $color->name }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>

                                            <small class="text-danger">
                                                @error('name')
                                                    {{ $message }}
                                                @enderror
                                            </small>
                                        </div>


                                        <div class="col-md-6">
                                            <label for="">Product Description</label>
                                            <textarea name="description" rows="4" class="form-control form__field">{{ $find_product->description ?? '' }}</textarea>
                                            <small class="text-danger">
                                                @error('description')
                                                    {{ $message }}
                                                @enderror
                                            </small>

                                        </div>

                                        <div class="col-md-6 mt-4">
                                            <div class="form-group">
                                                <label for="mainProductImageInput">Product Image:</label>
                                                <input type="file" class="form-control form__field visually-hidden"
                                                    name="product_image" id="mainProductImageInput"accept="image/*">
                                                <label for="mainProductImageInput"
                                                    class="file-input-label form__field form-control">
                                                    <i class="fas fa-camera"></i> Choose file
                                                </label>

                                                <small class='text-danger'>
                                                    @error('product_image')
                                                        {{ $message }}
                                                    @enderror
                                                </small>
                                            </div>

                                            <img id="mainProductImagePreview"
                                                src="{{ $find_product->productImage('product_image') ?: asset('upload/placeholder.png') }}"
                                                alt="Profile Preview"
                                                style="width: 200px; height: 150px; margin-top: 10px; ">

                                        </div>

                                        <div class="col-md-12 mt-5">
                                            <div class="form-group pt-4">
                                                <div class="card card-box-shadow">
                                                    <h5 class="card-header bg-dark text-white">Image Gallery
                                                        <button type="button"
                                                            class="btn btn-sm btn-outline-light float-right addImage">
                                                            <i class="la la-fw la-plus"></i>Add More Image
                                                        </button>
                                                    </h5>
                                                    <div class="card-body">
                                                        <div class="row addedField ml-5">
                                                            @if (count($product_gallery_images) > 0)
                                                                @foreach ($product_gallery_images as $index => $image)
                                                                    <div class="image-data"
                                                                        data-index="{{ $index }}">
                                                                        <div class="card shadow"
                                                                            style="width:300px;margin-right:20px;margin-bottom:15px;">
                                                                            <div class="image-upload">
                                                                                <div class="avatar-preview">
                                                                                    <img src="{{ $image->getUrl() }}"
                                                                                        class="card-img-top profilePicPreview"
                                                                                        id="profile-pic-show-{{ $index }}"
                                                                                        style="height:200px;">
                                                                                </div>
                                                                                <div class="card-body">
                                                                                    <div class="avatar-edit my-2">
                                                                                        <label for="id-{{ $index }}"
                                                                                            class="btn btn-success btn-lg w-100">@lang('Change Image')</label>
                                                                                        <button
                                                                                            class="btn btn-danger btn-lg removeBtn w-100"
                                                                                            type="button"
                                                                                            data-index="{{ $index }}"
                                                                                            data-images="{{ $image->id }}">
                                                                                            @lang('Remove Image')
                                                                                        </button>
                                                                                    </div>
                                                                                    <input type="file"
                                                                                        id="id-{{ $index }}"
                                                                                        class="changeImageBtn"
                                                                                        name="change_images[]"
                                                                                        accept=".png, .jpg, .jpeg"
                                                                                        data-old-images="{{ $image->id }}"
                                                                                        style="display: none;">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                @endforeach
                                                            @else
                                                                <div class="card shadow"
                                                                    style="width:300px;margin-right:20px;margin-bottom:15px;">
                                                                    <div class="image-upload">
                                                                        <div class="avatar-preview">
                                                                            <img src="{{ asset('upload/No-Image.png') }}"
                                                                                class=" card-img-top profilePicPreview"
                                                                                id="productFirstGalleryImagePreview"
                                                                                style="height:200px;">
                                                                        </div>
                                                                        <div class="card-body">
                                                                            <div class="avatar-edit my-2">
                                                                                <label for="productFirstGalleryImageInput"
                                                                                    class=" btn btn-success btn-lg w-100">@lang('Upload Image')</label>

                                                                            </div>
                                                                            <input type="file" class="profilePicUpload"
                                                                                name="product_gallery_images[]"
                                                                                id="productFirstGalleryImageInput"
                                                                                accept=".png, .jpg, .jpeg, .webp"
                                                                                style="display:none;">

                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            @endif
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mx-auto mt-5">
                                            <div class="form-group">
                                                <input type="submit" class="form-control btn btn-primary btn-sm "
                                                    value="Submit">
                                            </div>
                                        </div>

                                    </div>
                                </form>

                            </div>
                            <!-- /.card-body -->
                        </div>

                    </div>
                    <!-- /.col -->
                </div>
                <!-- /.row -->
            </div>
            <!-- /.container-fluid -->
        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
@endsection

@section('script')
    <script>
          function showImagePreview(input, previewId) {
            const preview = document.getElementById(previewId);

            if (input.files && input.files[0]) {
                const reader = new FileReader();

                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                };

                reader.readAsDataURL(input.files[0]);
            }
        }

        const mainProductImageInput = document.getElementById('mainProductImageInput');
        mainProductImageInput.addEventListener('change', function() {
            showImagePreview(this, 'mainProductImagePreview');
        });

        const productFirstGalleryImageInput = document.getElementById('productFirstGalleryImageInput');
        productFirstGalleryImageInput.addEventListener('change', function() {
            showImagePreview(this, 'productFirstGalleryImagePreview');
        });
    </script>
    <script>
    function handleImagePreview(fileInput, previewId) {
            if (fileInput.files && fileInput.files[0]) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    $(previewId).attr('src', e.target.result);
                };

                reader.readAsDataURL(fileInput.files[0]);
            }
        }

        $(document).on('click', '.addImage', function() {

            var randomId = Math.floor(Math.random() * 10000);

            var html = `
                            <div class="image-data" data-id="${randomId}">
                            <div class="card shadow" style="width:300px;margin-right:20px;margin-bottom:15px;">
                                <div class="image-upload">
                                <div class="avatar-preview">
                                    <img src="{{ asset('upload/No-Image.png') }}" class="card-img-top profilePicPreview" id="profile-pic-show-${randomId}" style="height:200px;">
                                </div>
                                <div class="card-body">
                                    <div class="avatar-edit my-2">
                                    <label for="add-new-file-${randomId}" class="btn btn-success btn-lg w-100">@lang('Add-new-file')</label>
                                    <button class="btn btn-danger btn-lg removeBtn w-100" type="button">
                                        @lang('Remove Image')
                    </button>
                </div>
                <input type="file" class="profilePicUpload" name="product_gallery_images[]" id="add-new-file-${randomId}" data-id="${randomId}" accept=".png, .jpg, .jpeg" style="display:none;">
                            </div>
                        </div>
                    </div>
                </div>`;

            $('.addedField').append(html);

            // NEW FILE UPLOAD WORK
            $(`#add-new-file-${randomId}`).on('change', function() {
                handleImagePreview(this, `#profile-pic-show-${randomId}`);
            });
        });

        $(document).on('change', 'input[name="change_images[]"]', function() {
            var index = this.id.split('-')[1];
            handleImagePreview(this, `#profile-pic-show-${index}`);
        });

        $(document).on('click', '.removeBtn', function() {
            var elementToRemove = $(this).closest('.image-data');
            elementToRemove.remove();
        });

        $('.removeBtn').on('click', function() {
            var imageId = $(this).data('images');

            var removeImageInput = $('<input>').attr({
                type: 'hidden',
                name: 'remove_images[]',
                value: imageId
            });

            $('input[name="remove_images[]"][value="' + imageId + '"]').remove();

            // Append the new input field to the form
            $('.addedField').append(removeImageInput);
        });
    </script>
@endsection
