@extends('admin.main')
@php
    use App\Helpers\Form as FormTemplate;
    use App\Helpers\Template;
    
    $formInputAttr = config('zvn.template.form_input');
    $formLabelAttr = config('zvn.template.form_label');
    $formCkeditor = config('zvn.template.form_ckeditor');
    $statusValue = ['default' => 'Select status', 'active' => config('zvn.template.status.active.name'), 'inactive' => config('zvn.template.status.inactive.name')];
    
    $srcThumb = asset('images/product');
    $inputHiddenID = Form::hidden('id', @$item['id']);
    
    $elements = [
        [
            'label' => Form::label('name', 'Name', $formLabelAttr),
            'element' => Form::text('name', @$item['name'], $formInputAttr),
        ],
        [
            'label' => Form::label('content', 'Content', $formLabelAttr),
            'element' => Form::textArea('content', @$item['content'], $formCkeditor),
        ],
        [
            'label' => Form::label('status', 'Status', $formLabelAttr),
            'element' => Form::select('status', $statusValue, @$item['status'], $formInputAttr),
        ],
        [
            'label' => Form::label('category_id', 'Category', $formLabelAttr),
            'element' => Form::select('category_id', $itemsCategory, @$item['category_id'], $formInputAttr),
        ],
        [
            'label' => Form::label('thumb', 'Thumb', $formLabelAttr),
            'element' => Form::file('thumb', $formInputAttr),
            'thumb' => !empty(@$item['id']) ? Template::showItemThumb($controllerName, @$item['thumb'], @$item['name']) : null,
            'type' => 'dropzone',
        ],
        [
            'element' => $inputHiddenID . Form::submit('Save', ['class' => 'btn btn-success']),
            'type' => 'btn-submit',
        ],
    ];
    $attributeElements = [];

    $itemsAttribute = [
        [
            "id" => 2,
            "name" => "Slogan"
        ],
        [
            "id" => 1,
            "name" => "Màu sắc"
        ]
    ];
    foreach ($itemsAttribute as $key => $value) {
        $id = $value['id'];
        $func = function ($funcValue) use ($value) {
            if ($funcValue['attribute_id'] == $value['id']) {
                return $funcValue['value'];
            }
        };
        $productAttributeValues = [];
        if ($itemsProductAttribute) {
            $productAttributeValues = array_filter(array_map($func, $itemsProductAttribute));
            
        }
        $attributeItem = [
            'label' => Form::label($id, $value['name'] ?? '', $formLabelAttr),
            'element' => Form::text($id, implode(',', $productAttributeValues) ?? null, array_merge($formInputAttr, ['data-role' => 'tagsinput'])),
        ];
        $attributeElements[] = $attributeItem ?? null;
    }
    $attributeElements[] = [
        'element' => $inputHiddenID . Form::submit('Save', ['class' => 'btn btn-success']),
        'type' => 'btn-submit',
    ];

    $itemsAttributePrice = [
        [
            "id" => 3,
            "name" => "Màu"
        ]
    ];
    $xhtml = '';
    $sortableOrdering = [];
    $ordering = 0;
    $defaultDeleteButton          = Template::showItemDeleteButton($controllerName, 0); 
    foreach ($itemsProductAttribute as $key => $valuePA) {
        if ($valuePA['attribute_id'] == 3) {
            $itemValue = $valuePA['value'] ?? '';
            $itemValuePrice = $valuePA['value_price'] ?? 0;
            $itemId = $valuePA['id'] ?? 0;
            $ordering++;
            $sortableOrdering[] = $ordering;
            $itemDefault = (int)$valuePA['default'];
            $itemDefaultCheck = ($itemDefault) ? 'checked="true"': '';
            $deleteButton          = Template::showItemDeleteButton($controllerName, $itemId); 
            $xhtml .= sprintf('<li id="%d" class="attribute-row  ui-state-default">
            <span class="ui-icon ui-icon-arrowthick-2-n-s"></span>
            <div class="form-group">
                <input class="form-control " name="color[value][]" type="text" value="%s" >
                <input class="form-control " name="color[value_price][]" type="text" value="%s" >
                <input type="hidden" name="color[id][]" value="%d" />
                <input type="hidden" name="color[default][]" value="%d" />
                <input class="form-control " name="color[radio][]" type="radio" value="%d" %s >
                Default
                %s
            </div>
        </li>', $ordering, $itemValue, $itemValuePrice, $itemId, $itemDefault, $itemDefault, $itemDefaultCheck, $deleteButton);
        }
    }
    $sortableOrderingString = implode(',', $sortableOrdering);
    $inputHiddenSortable = Form::hidden('sortable-9', $sortableOrderingString, ['id' => 'sortable-9']);
    $value = $itemsAttributePrice[0];
    $attributePriceItem = [
            'label' => Form::label($id, $value['name'] ?? '', $formLabelAttr),            
            'element' => '<ul class="sortable" id="box_add_price">'.$xhtml.'</ul>',
        ];
    $attributePriceElements[] = $attributePriceItem ?? null;
    $attributePriceElements[] = [
        'element' => $inputHiddenID . $inputHiddenSortable . Form::button('Add', ['class' => 'btn btn-primary', 'id' => 'btn_add_price']) . Form::submit('Save', ['class' => 'btn btn-success']),
        'type' => 'btn-submit',
    ];
@endphp

@section('content')
    @include ('admin.templates.page_header', ['pageIndex' => false])
    @include ('admin.templates.error')

    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                @include('admin.templates.x_title', ['title' => 'Thông tin cơ bản của sản phẩm'])
                <div class="x_content">
                    {{ Form::open([
                        'method' => 'POST',
                        'url' => route("$controllerName/save"),
                        'accept-charset' => 'UTF-8',
                        'enctype' => 'multipart/form-data',
                        'class' => 'form-horizontal form-label-left',
                        'id' => 'main-form',
                    ]) }}
                    {!! FormTemplate::show($elements) !!}
                    {{ Form::close() }}
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                @include('admin.templates.x_title', ['title' => 'Thuộc tính sản phẩm'])
                <div class="x_content">
                    {{ Form::open([
                        'onkeydown' => "return event.key != 'Enter';",
                        'method' => 'POST',
                        'url' => route("$controllerName/save-attribute"),
                        'accept-charset' => 'UTF-8',
                        'enctype' => 'multipart/form-data',
                        'class' => 'form-horizontal form-label-left',
                        'id' => 'attribute-form',
                    ]) }}
                    {!! FormTemplate::show($attributeElements) !!}
                    {{ Form::close() }}
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <div class="x_panel">
                @include('admin.templates.x_title', ['title' => 'Giá sản phẩm'])
                <div class="x_content">
                    {{ Form::open([
                        'onkeydown' => "return event.key != 'Enter';",
                        'method' => 'POST',
                        'url' => route("$controllerName/save-attribute-price"),
                        'accept-charset' => 'UTF-8',
                        'enctype' => 'multipart/form-data',
                        'class' => 'form-horizontal form-label-left',
                        'id' => 'attribute-form',
                    ]) }}
                    {!! FormTemplate::show($attributePriceElements) !!}
                    {{ Form::close() }}
                </div>
            </div>
        </div>
    </div>

    <div id="template-container" style="display: none;">
        <div class="dz-preview dz-file-preview">
            <div class="dz-image"><img data-dz-thumbnail /></div>
            <div class="dz-details">
                <div class="dz-filename"><span data-dz-name></span></div>
                <div class="dz-size" data-dz-size></div>
            </div>
            <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
            <div class="dz-success-mark"><span>✔</span></div>
            <div class="dz-error-mark"><span>✘</span></div>
            <div class="dz-error-message"><span data-dz-errormessage></span></div>
            <div class="dz-alt">
                <input type="text" class="form-control " name="thumb[alt][]" placeholder="Alt">
            </div>
        </div>
    </div>

    <div id="row_add_price" style="display: none;">
        <li id="" class="attribute-row  ui-state-default">
            <span class="ui-icon ui-icon-arrowthick-2-n-s"></span>
            <div class="form-group">
                <input class="form-control " name="color[value][]" type="text" value="" >
                <input class="form-control " name="color[value_price][]" type="text" value="" >
                <input type="hidden" name="color[id][]" value="0" />
                <input type="hidden" name="color[default][]" value="0" />
                <input class="form-control " name="color[radio][]" type="radio" value="0" >
                Default
                {!! $defaultDeleteButton !!}
            </div>
        </li>
    </div>
@endsection

@push('custom-script')
    <script>
        $(document).ready(function() {
            $( "#box_add_price" ).sortable({
                update: function(event, ui) {
                    var productOrder = $(this).sortable('toArray').toString();
                    $("#sortable-9").val (productOrder);
                }
            });            

            $('#btn_add_price').click(function (e) {
                const $ordering = [];
                $('#box_add_price li').each(function( index ) {
                    $ordering.push($(this).attr('id'));
                });
                $max = Math.max(...$ordering);
                var $row_add_price_html = $('#row_add_price').html();
                $('#box_add_price').append($row_add_price_html.replace(`id=""`, `id="${$max*1 + 1}"`));    
            });


            $( "#box_add_price" ).on( "click", 'input[name="color[radio][]"]', function() {
                $( 'input[name="color[radio][]"]' ).val(0);
                $( 'input[name="color[radio][]"]' ).prop('checked', 0);
                $('input[name="color[default][]"]').val(0);

                $( this ).prev().val(1);
                $( this ).prop('checked', 1);
                $(this).val(1);
            });

            var uploadedDocumentMap = {}
            Dropzone.options.uploadForm  = {
                url: "{{ route($controllerName.'/upload-image') }}",
                addRemoveLinks: true,
                method: "post",
                acceptedFiles: ".jpeg,.jpg,.png,.gif",
                headers: {
                    'X-CSRF-TOKEN': "{{ csrf_token() }}"
                },
                previewTemplate: document.querySelector('#template-container').innerHTML,
                success: function(file, response) {
                    $(file.previewElement).find('.dz-alt').append('<input type="hidden" name="thumb[name][]" value="' + response.name + '">')
                    uploadedDocumentMap[file.name] = response.name
                },
                removedfile: function(file) {
                    file.previewElement.remove()
                    var name = ''
                    if (typeof file.file_name !== 'undefined') {
                        name = file.file_name
                    } else {
                        name = uploadedDocumentMap[file.name]
                    }
                },
                error: function(file, response) {
                    return false
                },
                @if (isset($item) && $item['thumb'] != '')
                    init: function() {
                        var myDropzone = this;
                        var files = JSON.parse({!! json_encode($item['thumb']) !!});
                        for (var i in files) {
                            var file = files[i]
                            var src = "{{ $srcThumb }}" + `/${file.name}`;
                            this.displayExistingFile(file, src);
                            file.previewElement.classList.add('.dz-complete')
                            $(file.previewElement).find('.dz-alt').append(`<input type="hidden" name="thumb[name][]" value="${file.name}">`)
                            $(file.previewElement).find('.dz-alt [name="thumb[alt][]"]').val(file.alt)
                        }
                        
                    }
                @endif
            }
        });
    </script>
@endpush

    
