
<?php
$table_preview_id = uniqid("table-importation-preview_");
$offcanvas_preview_id = uniqid("offcanvas-importation-preview_");
?>

<div x-data="stocks_importations_preview({
                table_id : '<?php echo e($table_preview_id); ?>',
                offcanvas_id : '<?php echo e($offcanvas_preview_id); ?>',
                })">
    <?php if (isset($component)) { $__componentOriginal47cbb53c90e5d97428e9c4bd5c6f751e01de00d5 = $component; } ?>
<?php $component = App\View\Components\Offcanvas::resolve(['closable' => true] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? (array) $attributes->getIterator() : [])); ?>
<?php $component->withName('offcanvas'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag && $constructor = (new ReflectionClass(App\View\Components\Offcanvas::class))->getConstructor()): ?>
<?php $attributes = $attributes->except(collect($constructor->getParameters())->map->getName()->all()); ?>
<?php endif; ?>
<?php $component->withAttributes(['id' => ''.e($offcanvas_preview_id).'','data-bs-scroll' => 'true','data-bs-backdrop' => 'true','class' => 'offcanvas-end offcanvas-size-xl offcanvas-size-fulls']); ?>
         <?php $__env->slot('title', null, []); ?> 
            <?php echo e(__("Importations Preview")); ?>

            <template x-if="_warehouse?.name">
                <span x-text="' >> '+_warehouse.name"></span>
            </template>
         <?php $__env->endSlot(); ?>

        <div class="row">
            <div class="col-lg-12 table-responsive">
                <table class="table table-bordered table-striped"
                       style="width:100%"
                       id="<?php echo e($table_preview_id); ?>">
                </table>
            </div>
        </div>
     <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal47cbb53c90e5d97428e9c4bd5c6f751e01de00d5)): ?>
<?php $component = $__componentOriginal47cbb53c90e5d97428e9c4bd5c6f751e01de00d5; ?>
<?php unset($__componentOriginal47cbb53c90e5d97428e9c4bd5c6f751e01de00d5); ?>
<?php endif; ?>
</div>


<?php $__env->startPush('js'); ?>

    <script>

        document.addEventListener("alpine:init", e=> {

            Alpine.data('stocks_importations_preview',(param = {})=> ({
                _dt_url : "<?php echo e(route('admin.stocks.importations.preview.index')); ?>",
                _rows : [],
                _warehouse : null,
                _table_id : param?.table_id ?? "<?php echo e(uniqid("table-importation-preview_")); ?>",
                _offcanvas_id : param?.offcanvas_id ?? "<?php echo e(uniqid("offcanvas-preview_")); ?>",

                init(){
                    const that = this;

                    const {_table_id,_offcanvas_id,_dt_url} = that;

                    that.$watch("_warehouse",(newVal)=>{


                        if (newVal){
                            const param = new URLSearchParams({warehouse_id : newVal.id})
                          //  that._dt_url = _dt_url+"?"+param.toString();
                        }
                    })


                    document.addEventListener("stocks:importations.preview.loaded", function (e) {
                        const data = e.detail;
                        const warehouse = data?.warehouse;

                        if (warehouse){

                            that._warehouse = warehouse
                            const param = new URLSearchParams({warehouse_id : warehouse.id})
                             that._dt_url = _dt_url+"?"+param.toString();
                            if ($.fn.dataTable.isDataTable('#'+_table_id)){
                                refresh_datatable(_table_id,that._dt_url)
                            }else{
                                const dataTable = initDataTable(_table_id,that.table_options);

                                dataTable.on('click','tbody tr td .action-click',function (e) {
                                    const $button = $(this); // <button></button>
                                    const $td = $button.closest("td"); // <td></td>
                                    const index = $td.index();  // l'index de la colonne [1]
                                    const rowData = dataTable.row($td).data(); // Les données de la ligne
                                    const editor = that.editor;
                                    editor.hide(editor.order()) // cache tous les champs du formulaire

                                    if($button.hasClass("btn-remove-row")){

                                        editor.remove($td.parent(),false)
                                                    .submit(
                                                        (response)=>{
                                                            if(response.success ?? false){
                                                                refresh_datatable(_table_id)
                                                            }
                                                        },
                                                        null,
                                                        (data) => {
                                                            let d = data.data;
                                                            data.rowIds = [];
                                                            $.each(d , (index,val)=>{
                                                              //  data.data[index] = val.rowId
                                                                data.rowIds.push(val.rowId)
                                                            });

                                                            delete data.data
                                                        },
                                                    )

                                    }else  if($button.hasClass("btn-edit-qty")){

                                    }
                                });
                            }
                            showOffcanvas(_offcanvas_id,true);

                        }else{
                            toast({title : "Select Warehouse", icon : "error"})
                        }

                    });

                    that.$nextTick( () => {


                    });
                },

                get editor(){
                    const that = this;

                    return DataTableEditor( {
                        table : "#"+that._table_id,
                        idSrc : 'rowId',
                        ajax: {
                            edit : {
                                url : "<?php echo e(route("admin.stocks.importations.preview.edit-column")); ?>",
                                type : "post",
                            },
                            remove : {
                                url : "<?php echo e(route("admin.stocks.importations.preview.remove-row")); ?>",
                                type : "post",
                            }
                        },
                        fields: [
                            {
                                label: "<?php echo e(__('Expired At')); ?> : ",
                                name: "expired_at" ,
                                data:  "expired_at",
                                type: "datetime",
                                format : "<?php echo e(__('DD-MM-YYYY')); ?>",
                                attr : {  focus : false },
                            },

                            {
                                label: '<?php echo e(__("Qty")); ?>',
                                name: 'qty',
                                data: 'qty',
                                attr : {type : "number"}
                            },

                        ],
                    } )
                },

                get table_options(){
                    const that = this;
                    const {_table_id,editor,_offcanvas_id,_warehouse,_dt_url} = that;

                    const renderColumn = (data,type,row)=>{
                        let result = data;
                        console.log("data =>",data)
                        console.log("row =>",row.errors)
                        if (row?.error_message) {
                            result += `<br><small class="text-red mt-0" >${row.error_message}</small>`
                        }
                        return result;
                    }

                    return {
                        paginate : false,
                        dom : "Bfrtilp",
                        info: false,
                        paging: false,
                        select : {style: 'multi', selector: 'td:first-child.select-checkbox'},

                        ajax: _dt_url,

                        columns : [
                            { // idx = 0
                                title : headerCheckAll(),
                                data : null,
                                name : null,
                                orderable :false,
                                searchable :false,
                                className :"select-checkbox center",
                                defaultContent :""
                            },
                            {
                                data: 'product_id',
                                title: 'Product Id',
                                name: 'product_id' ,
                                searchable: true,
                                orderable: true,
                                className: "right",
                                render : renderColumn
                            },
                            {
                                data: 'product_reference',
                                title: 'Product Reference',
                                name: 'product_reference' ,
                                searchable: true,
                                orderable: true,
                                className: "left",
                                render : renderColumn,
                            },
                            {
                                data: 'product_name',
                                title: 'Product Name',
                                name: 'product_name' ,
                                searchable: true,
                                orderable: true,
                                className: "right",
                                render : renderColumn,
                            },
                            {
                                data: 'lot_id',
                                title: 'Lot Id',
                                name: 'lot_id' ,
                                searchable: true,
                                orderable: true,
                                className: "left",
                                render : renderColumn,
                            },
                            {
                                data: 'qty',
                                title: 'Qty',
                                name: 'qty' ,
                                searchable: true,
                                orderable: true,
                                className: "right",
                                render : renderColumn,
                            },
                            {
                                data: 'expired_at',
                                title: 'Expired At',
                                name: 'expired_at' ,
                                searchable: true,
                                orderable: true,
                                className: "left",
                                render : renderColumn,
                            },

                            { // idx = 7
                                title: 'Action',
                                data: 'actions',
                                name: 'actions' ,
                                searchable: false,
                                orderable:false,
                                printable:false,
                                exportable:false,
                                className: "right"
                            },
                        ],

                        buttons : [
                            { extend: "reload" },
                            // {extend: "export" ,},
                            {
                                extend : "selected",
                                className: "btn-success",
                                attr : {
                                    title: '<?php echo e(__("Confirm")); ?>',
                                    icon: '<i class="fa fa-check-double"></i> ',
                                    "data-toggle":"tooltip",
                                    "data-original-title" : '<?php echo e(__("Confirm")); ?>',
                                },
                                text: function (dt,button,config) {
                                    let label = config.attr.title;
                                    return config.attr.icon;
                                },
                                // columns: 'th:nth-child(n+2)',
                                action: (e, dt, node, config ) => {
                                    const table = dt.table();
                                    editor.hide(editor.order()) // cache tous les champs du formulaire
                                  //  editor.show(["scheduled_at"]);

                                    return editor.edit( table.rows( {selected: true} ).indexes(), {
                                                title: "Confirmation",
                                                message: "Confirm this selection?",
                                                buttons: {
                                                    className : "btn-success",
                                                    text : "<i class='fa fa-check-double'></i> <?php echo e(__("Confirm")); ?>",
                                                    fn : function (e) {
                                                        this.submit(
                                                            (response) => {
                                                                if(response.success){ // en cas de success
                                                                    refresh_datatable(_table_id); // refresh le table
                                                                    showOffcanvas(_offcanvas_id,false)
                                                                    that.$dispatch("stocks:importations.preview.confirmed")
                                                                }
                                                            },
                                                            null,
                                                            (data)=>{
                                                                let d = data.data;
                                                                $.each(d , (index,{scheduled_at})=>{
                                                                    console.log('in ',index)
                                                                    data.data[index] = { scheduled_at}
                                                                });
                                                            }
                                                        );
                                                    }
                                                }
                                            })

                                }
                            },
                        ],

                        drawCallback (settings){

                            const api = this.api();
                            const table = api.table(); // Datatable
                            const $table = table.tables()
                                                .nodes() // context
                                                .to$(); // converti en dom Jquery

                            const data = api.ajax.json()?.data ?? []; // les données récupérées du endpoint

                            that._rows = data;

                            if ( data.length){
                            }

                        },

                        rowCallback : function (row, data) {
                            const errors = data?.options?.error_message ?? null;

                            if(errors){
                                row.classList.add('table-danger');
                            }
                            row.classList.add('selectable');
                        }
                    }
                }
            }))
        })
    </script>

<?php $__env->stopPush(); ?>
<?php /**PATH /home/lekruu/public_html/resources/views/backend/stocks/management/tabs/importations/blocs/importations-preview.blade.php ENDPATH**/ ?>