@extends('layouts.admin')
@section('content')

    <div class="card">
        <div class="card-header">
            {{ trans('global.edit') }} {{ trans('cruds.product.singular') }}
        </div>
        <div class="card-body">
            <form action="{{ route('admin.products.update', $product->id) }}" method="POST" enctype="multipart/form-data">
                @csrf
                @method('PUT')
                <div class="form-group">
                    <label for="product_type">{{ trans('cruds.product.fields.product_type') }}</label>
                    <select name="product_type" class="form-control select2" id="product_type">
                        <option value="">{{ trans('global.pleaseSelect') }}</option>
                        <option value="1" {{ $product->product_type == 1 ? 'selected' : '' }}>For Auction</option>
                        <option value="2" {{ $product->product_type == 2 ? 'selected' : '' }}>For Sell</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.category') }}</label>
                    <select name="cat_id" class="form-control select2" id="cat_id">
                        <option value="">{{ trans('global.pleaseSelect') }}</option>
                        @foreach ($category as $cat)
                            <option value="{{ $cat->id }}" data-bid_increment_gap="{{ $cat->bid_increment_gap }}" {{ $product->cat_id == $cat->id ? 'selected' : ''}}>{{ $cat->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.name') }}</label>
                    <input type="text" name="name" class="form-control" value="{{ $product->name }}" required>
                </div>
                <div class="form-group">
                    <label for="name_ar">{{ trans('cruds.product.fields.name') }} (In Arabic)</label>
                    <input type="text" name="name_ar" class="form-control" value="{{ $product->name_ar }}" required>
                </div>
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.sku') }}</label>
                    <input type="text" name="sku" class="form-control" value="{{ $product->sku }}" readonly>
                </div>
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.purchase_price') }}</label>
                    <input type="number" step="0.01" name="purchase_price" value="{{ $product->purchase_price }}"
                        class="form-control">
                </div>
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.price') }}</label>
                    <input type="number" step="0.01" name="price" class="form-control" value="{{ $product->price }}"
                        required>
                </div>
                <div class="form-group product_quantity_div">
                    <label for="product_quantity">{{ trans('cruds.product.fields.product_quantity') }}</label>
                    <input type="number" name="product_quantity" class="form-control" value="{{ $product->product_quantity }}">
                </div>
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.user_id') }}</label>
                    <select name="user_id" id="seller_id" class="form-control select2">
                        <option value="">{{ trans('global.pleaseSelect') }}</option>
                        @foreach ($users as $user)
                            <option value="{{ $user->id }}" {{ $product->user_id == $user->id ? 'selected' : ''}}>
                                {{ $user->first_name }} {{ $user->last_name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.commission_percentage') }}</label>
                    <input type="number" name="commission_percentage" class="form-control" id="seller_commission_percentage"
                        value="{{ $product->commission_percentage }}" readonly>
                </div>
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.description') }} (In English)</label>
                    <textarea name="description" class="form-control">{{ $product->description }}</textarea>
                </div>
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.description') }} (In Arabic)</label>
                    <textarea name="description_ar" class="form-control">{{ $product->description_ar }}</textarea>
                </div>
                <div class="form-group live_date_div">
                    <label for="live_date">{{ trans('cruds.product.fields.live_date') }}</label>
                    <input type="text" id="datetimepicker5" name="live_date"
                        class="form-control datetimepicker-input live_date" data-toggle="datetimepicker"
                        data-target="#datetimepicker5">
                </div>
                <div class="form-group duration_day_div">
                    <label>{{ trans('cruds.product.fields.duration_day') }}</label>
                    <select name="duration_day" class="form-control duration_day">
                        @for ($i = 1; $i <= 31; $i++)
                            <option value="{{ $i }}" {{ $product->duration_day == $i ? 'selected' : ''}}>{{ $i }}
                                {{ trans('cruds.product.fields.duration_day') }}
                            </option>
                        @endfor
                    </select>
                </div>
                <input type="hidden" id="finish_date" name="finish_date" value="{{ $product->finish_date }}">
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.status') }}</label>
                    <select name="status" class="form-control">
                        <option value="Draft" {{ $product->status == 'Draft' ? 'selected' : ''}}>
                            {{ trans('cruds.product.status.draft') }}
                        </option>
                        <option value="Pending" {{ $product->status == 'Pending' ? 'selected' : ''}}>
                            {{ trans('cruds.product.status.pending') }}
                        </option>
                        <option value="Approved" {{ $product->status == 'Approved' ? 'selected' : ''}}>
                            {{ trans('cruds.product.status.approved') }}
                        </option>
                        <option value="Rejected" {{ $product->status == 'Rejected' ? 'selected' : ''}}>
                            {{ trans('cruds.product.status.rejected') }}
                        </option>
                        <option value="Save" {{ $product->status == 'Save' ? 'selected' : ''}}>
                            {{ trans('cruds.product.status.save') }}
                        </option>
                    </select>
                </div>
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.condition') }}</label>
                    <select name="condition" class="form-control">
                        <option value="">{{ trans('global.pleaseSelect') }}</option>
                        <option value="1" {{ $product->condition == 1 ? 'selected' : ''}}>
                            {{ trans('cruds.product.condition.new') }}
                        </option>
                        <option value="2" {{ $product->condition == 2 ? 'selected' : ''}}>
                            {{ trans('cruds.product.condition.used') }}
                        </option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="cover_image">{{ trans('cruds.product.fields.cover_image') }}</label>
                    <input type="file" id="cover_image" name="cover_image" class="form-control" onchange="previewCoverImage(event)">
                    <a href="{{ asset($product->cover_image) }}" class="fancybox-popup">
                        <img id="coverPreview" src="{{ asset($product->cover_image) }}" class="mt-2" width="100">
                    </a>
                </div>
                <div class="form-group">
                    <label for="images">{{ trans('cruds.product.fields.images') }}</label>
                    <input type="file" id="images" name="images[]" class="form-control" multiple
                        onchange="previewMultipleImages(event)">
                    @if(isset($product) && $product->images)
                        <div class="row">
                            @foreach($product->images as $old_image)
                                <div class="col-md-3 mt-3">
                                    <a href="{{ asset($old_image->image) }}" class="fancybox-popup">
                                        <img src="{{ asset($old_image->image) }}" class="mt-2" width="100">
                                    </a>
                                </div>
                            @endforeach
                        </div>
                    @endif
                    <div id="imagePreviewContainer" class="row mt-2"></div>
                </div>
                <label>{{ trans('cruds.product.fields.documents') }}</label>
                <div class="form-group row" id="fieldWrapper">
                    {{-- Show existing documents --}}
                    @foreach($product->documents as $index => $doc)
                        <div id="docRow-{{ $doc->id }}" class="col-6">
                            <div class="form-group field-group row">
                                <div class="col-md-9">
                                    <input type="text" name="existing_document_name[{{ $doc->id }}]" class="form-control"
                                        value="{{ $doc->name }}">
                                </div>
                                <div class="col-md-3">
                                    <button type="button" class="btn btn-danger deleteDocument" data-id="{{ $doc->id }}">
                                        <i class="fa-fw fas fa-remove"></i>
                                    </button>
                                    @if ($loop->last)
                                        <button type="button" class="btn btn-success addDocument">
                                            <i class="fa-fw fas fa-plus"></i>
                                        </button>
                                    @endif
                                </div>
                            </div>
                            <div class="form-group field-group row">
                                @php $extension = pathinfo($doc->file_name, PATHINFO_EXTENSION); @endphp
                                @if(strtolower($extension) == 'pdf')
                                    <div class="col-md-2">
                                        <a href="{{ asset($doc->file_name) }}" class="fancybox-popup">
                                            <img src="{{ asset('img/pdf.png') }}" class="mt-2" width="100">
                                        </a>
                                    </div>
                                @else
                                    <div class="col-md-3">
                                        <a href="{{ asset($doc->file_name) }}" class="fancybox-popup">
                                            <img src="{{ asset($doc->file_name) }}" class="mt-2" width="100">
                                        </a>
                                    </div>
                                @endif
                            </div>
                        </div>
                    @endforeach
                </div>
                <div class="form-group">
                    <label>{{ trans('cruds.product.fields.is_admin') }}</label>
                    <select name="is_admin" class="form-control">
                        <option value="">{{ trans('global.pleaseSelect') }}</option>
                        <option value="0" {{ $product->is_admin == 0 ? 'selected' : ''}}>
                            {{ trans('cruds.product.is_admin.no') }}
                        </option>
                        <option value="1" {{ $product->is_admin == 1 ? 'selected' : ''}}>
                            {{ trans('cruds.product.is_admin.yes') }}
                        </option>
                    </select>
                </div>
                <div class="form-group bidding_incremented_price_div">
                    <label for="bidding_incremented_price">{{ trans('cruds.product.fields.bidding_incremented_price') }}</label>
                    <select name="bidding_incremented_price" id="bidding_incremented_price" class="form-control select2">
                        <option value="">{{ trans('global.pleaseSelect') }}</option>
                    </select>
                    <input type="hidden" id="bidding_incremented_price_old" value="{{ $product->bidding_incremented_price }}">
                </div>
                <div class="form-group" id="shippingDetailsFieldWrapper">
                    <label for="shipping_details">{{ trans('cruds.product.fields.shipping_details') }}</label>
                    @php
                        $productShippingDetails = json_decode($product->shippingDetails ?? '[]', true); // Decode shipping details, ensure it's an array
                        // If no existing shipping details, initialize with one empty entry for the form
                        if (empty($productShippingDetails)) {
                            $productShippingDetails = [['country' => '', 'day' => '', 'fee' => '']];
                        }
                    @endphp
                    @foreach($productShippingDetails as $index => $detail)
                        <div class="form-group shipping-details-group row align-items-end">
                            <div class="col-md-4">
                                <label for="country_{{ $index }}">{{ trans('cruds.product.fields.country') }}</label>
                                <select name="country[]" class="form-control country" id="country_{{ $index }}">
                                    <option value="">{{ trans('global.pleaseSelect') }}</option>
                                        @foreach ($country_details as $vlu)
                                            <option value="{{ $vlu->id }}" {{ old('country.'.$index, $detail['country_id'] ?? '') == $vlu->id ? 'selected' : '' }}>{{ $vlu->country_name }}</option>
                                        @endforeach
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="day_{{ $index }}">{{ trans('cruds.product.fields.day') }}</label>
                                <select name="day[]" class="form-control day" id="day_{{ $index }}">
                                    <option value="">{{ trans('global.pleaseSelect') }}</option>
                                    @for ($i = 1; $i <= 30; $i++)
                                        <option value="{{ $i }}" {{ old('day.'.$index, $detail['duration_day'] ?? '') == $i ? 'selected' : '' }}>{{ $i }} {{ trans('cruds.product.fields.day') }}</option>
                                    @endfor
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="fee_{{ $index }}">{{ trans('cruds.product.fields.fee') }}</label>
                                <input type="text" name="fee[]" class="form-control" placeholder="Fee" value="{{ old('fee.'.$index, $detail['shipping_fee'] ?? '') }}">
                            </div>
                            <div class="col-md-2">
                                @if ($loop->last)
                                    <button type="button" class="btn btn-success addShippingDetails">
                                        <i class="fa-fw fas fa-plus"></i>
                                    </button>
                                @endif
                                @if ($loop->index > 0 || count($productShippingDetails) > 1) {{-- Show remove button if not the first row or if there's more than one row --}}
                                    <button type="button" class="btn btn-danger remove-btn-shipping-details" style="margin-left: 5px;">
                                        <i class="fa-fw fas fa-times"></i>
                                    </button>
                                @endif
                            </div>
                        </div>
                    @endforeach
                </div>

                <button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
            </form>
        </div>
    </div>

@endsection

@section('scripts')

    <script>
        $(document).ready(function () {
            let selectedGap = $('#cat_id').find(':selected').data('bid_increment_gap');
            let oldValue = $('#bidding_incremented_price_old').val();

            if (selectedGap) {
                loadBiddingOptions(selectedGap, oldValue);
            }

            $('#datetimepicker5').datetimepicker({
                format: 'YYYY-MM-DD HH:mm',
                minDate: moment(),
                icons: {
                    time: 'fa fa-clock',
                    date: 'fa fa-calendar',
                    up: 'fa fa-chevron-up',
                    down: 'fa fa-chevron-down',
                    previous: 'fa fa-chevron-left',
                    next: 'fa fa-chevron-right',
                    today: 'fa fa-sun',
                    clear: 'fa fa-trash',
                    close: 'fa fa-times'
                },
                showClear: true,
                showClose: true,
                // useCurrent: true,
                sideBySide: true
            });

            $("#datetimepicker5").val("{{ $product->live_date }}");

            $('.live_date, .duration_day').on('change', function () {
                let liveDate = $('.live_date').val();
                let duration = parseInt($('.duration_day').val());

                if (liveDate && duration) {
                    let finishDate = moment(liveDate, 'YYYY-MM-DD HH:mm').add(duration, 'days').format('YYYY-MM-DD HH:mm');
                    $('#finish_date').val(finishDate);
                } else {
                    $('#finish_date').val('');
                }
            });

            $('#seller_id').on('change', function () {
                var sellerId = $(this).val();

                if (sellerId) {
                    $.ajax({
                        url: '/admin/products/get-seller-commission/' + sellerId,
                        type: 'GET',
                        success: function (data) {
                            $('#seller_commission_percentage').val(data.seller_commission_percentage);
                        }
                    });
                }
            });

            // On category change
            $('#cat_id').on('change', function () {
                let gap = $(this).find(':selected').data('bid_increment_gap');
                if (!gap || gap <= 0) {
                    $('#bidding_incremented_price').html('<option value="">{{ trans("global.pleaseSelect") }}</option>');
                    return;
                }

                loadBiddingOptions(gap);
            });

            // Add new field
            $(document).on('click', '.addDocument', function () {
                // Remove all existing add buttons
                $('.addDocument').remove();

                // Append new field
                $('#fieldWrapper').append(getNewField());
            });

            // Remove field
            $(document).on('click', '.remove-btn', function () {
                $(this).closest('.field-group').remove();

                // Ensure only the last row has the add button
                $('.addDocument').remove();
                $('#fieldWrapper .field-group:last .col-md-2').append(
                    `<button type="button" class="btn btn-success addDocument"><i class="fa-fw fas fa-plus"></i></button>`
                );
            });

            $(document).on('click', '.deleteDocument', function () {
                const docId = $(this).data('id');
                const row = $('#docRow-' + docId);

                if (confirm('Are you sure you want to delete this document?')) {
                    $.ajax({
                        url: '/admin/products/document-delete/' + docId,
                        type: 'DELETE',
                        data: {
                            _token: '{{ csrf_token() }}'
                        },
                        success: function (response) {
                            if (response.success) {
                                row.remove();
                            } else {
                                alert('Delete failed. Try again.');
                            }
                        },
                        error: function () {
                            alert('Something went wrong.');
                        }
                    });
                }
            });

            function getNewShippingDetailsField() {
                return `
                <div class="form-group shipping-details-group row align-items-end">
                    <div class="col-md-4">
                        <label for="country">{{ trans('cruds.product.fields.country') }}</label>
                        <select name="country[]" class="form-control country">
                            <option value="">{{ trans('global.pleaseSelect') }}</option>
                            @foreach ($country_details as $vlu)
                                <option value="{{ $vlu->id }}">{{ $vlu->country_name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="day">{{ trans('cruds.product.fields.day') }}</label>
                        <select name="day[]" class="form-control day">
                            <option value="">{{ trans('global.pleaseSelect') }}</option>
                            @for ($i = 1; $i <= 30; $i++)
                                <option value="{{ $i }}">{{ $i }} {{ trans('cruds.product.fields.day') }}</option>
                            @endfor
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="fee">{{ trans('cruds.product.fields.fee') }}</label>
                        <input type="text" name="fee[]" class="form-control" placeholder="Fee">
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-danger remove-btn-shipping-details" style="margin-left: 5px;"><i class="fa-fw fas fa-times"></i></button>
                        <button type="button" class="btn btn-success addShippingDetails"><i class="fa-fw fas fa-plus"></i></button>
                    </div>
                </div>`;
            }

            // Add new Shipping Details
            $(document).on('click', '.addShippingDetails', function () {
                $('.addShippingDetails').remove(); // Remove all existing add buttons
                $('#shippingDetailsFieldWrapper').append(getNewShippingDetailsField());
                updateShippingDetailsButtons(); // Re-evaluate and update buttons
            });

            // Remove field Shipping Details
            $(document).on('click', '.remove-btn-shipping-details', function () {
                $(this).closest('.shipping-details-group').remove();
                updateShippingDetailsButtons(); // Re-evaluate and update buttons
            });

            // Function to update the add/remove buttons for shipping details
            function updateShippingDetailsButtons() {
                $('.addShippingDetails').remove(); // Remove all existing add buttons
                $('.remove-btn-shipping-details').remove(); // Remove all existing remove buttons

                let shippingDetailRows = $('#shippingDetailsFieldWrapper .shipping-details-group');

                shippingDetailRows.each(function(index) {
                    let buttonContainer = $(this).find('.col-md-2:last');

                    if (index === shippingDetailRows.length - 1) { // If it's the last row
                        buttonContainer.append(`<button type="button" class="btn btn-success addShippingDetails"><i class="fa-fw fas fa-plus"></i></button>`);
                    }

                    if (shippingDetailRows.length > 1) { // If there's more than one row, always show remove
                        buttonContainer.append(`<button type="button" class="btn btn-danger remove-btn-shipping-details" style="margin-left: 5px;"><i class="fa-fw fas fa-times"></i></button>`);
                    }
                });

                // Special handling for when there are no shipping details initially (e.g., product has no shipping details)
                if (shippingDetailRows.length === 0) {
                    $('#shippingDetailsFieldWrapper').append(getNewShippingDetailsField());
                    // Remove the remove button from the newly added single field
                    $('#shippingDetailsFieldWrapper .shipping-details-group:first .remove-btn-shipping-details').remove();
                }
            }

            // Call on document ready to set initial shipping detail button states
            updateShippingDetailsButtons();

            toggleAuctionFields();

            $('#product_type').on('change', function() {
                toggleAuctionFields();
            });
        });

        function previewCoverImage(event) {
            var reader = new FileReader();
            reader.onload = function () {
                var output = document.getElementById('coverPreview');
                output.src = reader.result;
                output.style.display = 'block';
            };

            reader.readAsDataURL(event.target.files[0]);
        }

        function previewMultipleImages(event) {
            var previewContainer = document.getElementById('imagePreviewContainer');
            previewContainer.innerHTML = '';

            for (let i = 0; i < event.target.files.length; i++) {
                let file = event.target.files[i];
                let reader = new FileReader();

                reader.onload = function (e) {
                    let div = document.createElement("div");
                    div.setAttribute("class", "col-md-3 mt-3");

                    let img = document.createElement("img");
                    img.setAttribute("src", e.target.result);
                    img.setAttribute("class", "preview-image img-thumbnail");
                    img.setAttribute("width", "100");

                    div.appendChild(img);
                    previewContainer.appendChild(div);
                };

                reader.readAsDataURL(file);
            }
        }

        function loadBiddingOptions(gap, selectedValue = null) {
            let options = '<option value="">{{ trans("global.pleaseSelect") }}</option>';

            for (let j = parseInt(gap); j <= 1000; j += parseInt(gap)) {
                let selected = (selectedValue && parseInt(selectedValue) === j) ? 'selected' : '';
                options += `<option value="${j}" ${selected}>${j}</option>`;
            }

            $('#bidding_incremented_price').html(options);
        }

        function getNewField() {
            return `
                <div class="form-group field-group col-12">
                 <div class="field-group-mian row">
                    <div class="col-md-5">
                        <input type="text" name="document_name[]" class="form-control" placeholder="Document Name">
                    </div>
                    <div class="col-md-5">
                        <input type="file" class="form-control" name="documents[]">
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-danger remove-btn"><i class="fa-fw fas fa-times"></i></button>
                        <button type="button" class="btn btn-success addDocument"><i class="fa-fw fas fa-plus"></i></button>
                    </div>
                    </div>
                </div>`;
        }

        function toggleAuctionFields() {
            var productType = $('#product_type').val();

            if (productType == 1) {
                $('.live_date_div').show();
                $('.duration_day_div').show();
                $('.bidding_incremented_price_div').show();

                $('.product_quantity_div').hide();
            } else {
                $('.live_date_div').hide();
                $('.duration_day_div').hide();
                $('.bidding_incremented_price_div').hide();

                $('.product_quantity_div').show();
            }
        }

    </script>

@endsection
