<?= $this->include('themes/_commonPartialsBs/datatables') ?>
<?= $this->include("themes/_commonPartialsBs/select2bs5") ?>
<?= $this->include("themes/_commonPartialsBs/sweetalert") ?>
<?= $this->include('themes/_commonPartialsBs/_confirm2delete') ?>
<?= $this->extend('themes/vuexy/main/defaultlayout') ?>

<?= $this->section("content") ?>
<div class="row">
    <div class="col-12">
        <div class="card card-info">
            <div class="card-header">
                <h3 class="card-title"><?= $boxTitle ?? $pageTitle ?></h3>
            </div><!--//.card-header -->
            <form id="tarifaAcabadoForm" class="card-body" method="post" action="<?= $formAction ?>">
                <?= csrf_field() ?>
                <?= view("themes/_commonPartialsBs/_alertBoxes") ?>
                <?= !empty($validation->getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?>
                <?= view("themes/vuexy/form/tarifas/acabado/_tarifaAcabadoFormItems") ?>
                <div class="pt-4">
                    <input type="submit"
                        class="btn btn-primary float-start me-sm-3 me-1"
                        name="save"
                        value="<?= lang("Basic.global.Save") ?>" />
                    <?= anchor(route_to("tarifaAcabadoList"), lang("Basic.global.Cancel"), ["class" => "btn btn-secondary float-start"]) ?>
                </div><!-- /.card-footer -->
            </form>
        </div><!-- //.card -->
    </div><!--//.col -->

    <?php if ($formAction == route_to('tarifaAcabadoAdd')): ?>
        <div class="accordion mt-3" id="accordionAcabadoLineas" style="visibility:hidden">
    <?php else: ?>
            <div class="accordion mt-3" id="accordionAcabadoLineas" style="visibility:visible">
    <?php endif; ?>
                <div class="card accordion-item active">
                    <h2 class="accordion-header" id="headingOne">
                        <button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionTip1" aria-expanded="false" aria-controls="accordionTip1">
                            <h3><?= lang("TarifaAcabadoLineas.moduleTitle") ?></h3>
                        </button>
                    </h2>

                    <div id="accordionTip1" class="accordion-collapse collapse show" data-bs-parent="#accordionAcabadoLineas">
                        <div class="accordion-body">
                            <table id="tableOfTarifaacabadolineas" class="table table-striped table-hover" style="width: 100%;">
                                <thead>
                                    <tr>
                                        <th><?= lang('TarifaAcabadoLineas.proveedor') ?></th>
                                        <th><?= lang('TarifaAcabadoLineas.tiradaMin') ?></th>
                                        <th><?= lang('TarifaAcabadoLineas.precioMax') ?></th>
                                        <th><?= lang('TarifaAcabadoLineas.tiradaMax') ?></th>
                                        <th><?= lang('TarifaAcabadoLineas.precioMin') ?></th>
                                        <th><?= lang('TarifaAcabadoLineas.margen') ?></th>
                                        <th class="noFilter"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div> <!-- //.accordion -->
            <?php if ($tarifaacabadoEntity->id): ?>
                <div class="accordion mt-3" id="accordionTarifaMaquinas" style="visibility:visible">
                    <div class="card accordion-item active">
                        <h2 class="accordion-header" id="headingTwo">
                            <button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionTipTarifaMaquina" aria-expanded="false" aria-controls="accordionTipTarifaMaquina">
                                <h3>Tarifa máquinas</h3>
                            </button>
                        </h2>
                        <div id="accordionTipTarifaMaquina" class="accordion-collapse collapse show" data-bs-parent="#accordionTarifaMaquinas">
                            <div class="accordion-body">
                                <?= view("themes/vuexy/components/forms/tarifa_maquinas", ["id" => "tarifa_maquina_component", "tarifaId" => $tarifaacabadoEntity->id]) ?>
                            </div>
                        </div>
                    </div>
                </div> <!-- //.accordion -->
                <?php endif ?>
        </div><!--//.row -->

        <?= $this->endSection() ?>

        <?= $this->section("additionalExternalJs") ?>
        <script type="module" src="<?= site_url('assets/js/safekat/pages/tarifas/maquinas/acabado/index.js') ?>"></script>
        <?= $this->endSection() ?>

        <?= $this->section("additionalInlineJs") ?>
        const lastColNr = $('#tableOfTarifasacabado').find("tr:first th").length - 1;
        const url = window.location.href;
        const url_parts = url.split('/');
        let id = -1;
        if(url_parts[url_parts.length-2] == 'edit'){
        id = url_parts[url_parts.length-1];
        }

        const actionBtns = function(data) {
        return `
        <span class="edit"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit mx-2" data-id="${data.id}"></i></a></span>
        <a href="javascript:void(0);"><i class="ti ti-trash ti-sm btn-delete mx-2" data-id="${data.id}" data-bs-toggle="modal" data-bs-target="#confirm2delete"></i></a>
        <span class="cancel"></span>
        `;
        };


        var editor = new $.fn.dataTable.Editor( {
        ajax: {
        url: "<?= route_to('tarifaAcabadoLineasDTE') ?>",
        headers: {
        <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
        },
        },
        table : "#tableOfTarifaacabadolineas",
        idSrc: 'id',
        fields: [
        {
        name: "proveedor_id",
        type: "select",
        }, {
        name: "tirada_min",
        attr: {
            type: "text",
            name : "tirada_min",
            class :"autonumeric"
        }
        
        }, {
        name: "precio_max",
        attr: {
            type: "text",
            name : "precio_max",
            class :"autonumeric"
        }
        }, {
        name: "tirada_max",
        attr: {
            type: "text",
            name : "tirada_max",
            class :"autonumeric"
        }
        }, {
        name: "precio_min",
        attr: {
            type: "text",
            name : "precio_min",
            class :"autonumeric"
        }
        },{
        name: "margen",
        attr: {
            type: "text",
            name : "margen",
            class :"autonumeric"
        }
        }, {
        "name": "tarifa_acabado_id",
        "type": "hidden"
        },{
        name: "proveedor_nombre",
        "type": "hidden"
        },{
        "name": "deleted_at",
        "type": "hidden"
        },{
        "name": "is_deleted",
        "type": "hidden"
        },
        ]
        } );

        // Generación de la lista de proveedores (id, nombre) para encuadernación
        const suppliersList = <?php echo json_encode($proveedores); ?>;
        editor.field( 'proveedor_id' ).update( suppliersList );
        editor.on('open',(event)=>{
            $("input.autonumeric").each(function () {
                let autoNumericInstance = AutoNumeric.getAutoNumericElement(this)
                if(autoNumericInstance){
                    autoNumericInstance.remove()

                }
                new AutoNumeric(this, {
                    digitGroupSeparator: ".",
                    decimalCharacter: ",",
                    allowDecimalPadding : 'floats',
                    decimalPlaces: 2,
                    unformatOnSubmit: true,
      
                });
            })
        })
        editor.on( 'preSubmit', function ( e, d, type ) {
            if (d.data) {
            Object.keys(d.data).forEach(function (key) {
                // Find all elements with class .autonumeric
                $("input.autonumeric").each(function () {
                    let autoNumericInstance = AutoNumeric.getAutoNumericElement(this)
                        if (autoNumericInstance) {
                            // Get raw value and update the corresponding field
                            let rawValue = autoNumericInstance.getNumericString();
                            d.data[key][this.name] = rawValue; // Ensure the correct name attribute is used
                        }
                });
            });
        }
        if ( type === 'create'){
        d.data[0]['tarifa_acabado_id'] = id;
        }
        else if(type === 'edit' ) {
        for (v in d.data){
        d.data[v]['tarifa_acabado_id'] = id;
        }
        }
        });


        editor.on( 'postSubmit', function ( e, json, data, action ) {

        yeniden(json.<?= csrf_token() ?>);
        });

        editor.on( 'submitSuccess', function ( e, json, data, action ) {

        theTable.clearPipeline();
        theTable.draw();
        });


        function searchProviders(){
        var values = [];
        $('#select_Proveedor').find(':selected').each(function () {
        values.push($(this).val());
        });
        theTable.column(0).search(values).draw();
        }


        // Setup - add a text input to each footer cell
        $('#tableOfTarifaacabadolineas thead tr').clone(true).appendTo('#tableOfTarifaacabadolineas thead');
        $('#tableOfTarifaacabadolineas thead tr:eq(1) th').each(function (i) {
        if (!$(this).hasClass("noFilter")) {
        var title = $(this).text();
        title = title.replace(/ /g, "_").replace(/\./g, "_");


        if(i==0){

        // Agregar un selector en la primera columna
        $(this).html(`<select id=select_${title} class="form-control select2" style="min-width:100px;max-width:120px;font-size:0.8rem !important;"></select>`);

        // Agregar opciones al selector
        var selector = $('select', this);
        const suppliersList = <?php echo json_encode($proveedores); ?>;
        //selector.append('<option value="">Todos</option>'); // Opción vacía
        for (j = 0; j < suppliersList.length; j++) {
            selector.append('<option value="' + suppliersList[j].value + '">' + suppliersList[j].label + '</option>');
            };

            $('#select_' + title).select2({
            multiple: true,
            placeholder: ""
            });


            selector.bind('select2:select', searchProviders);
            selector.bind('select2:unselect', searchProviders);

            $('#select_' + title).val("").trigger('change');

            }
            else{


            $(this).html(`
            <div class='d-flex'>
                <input name=min_${title} id=min_${title} class="form-control" type='text' min='0' placeholder='Min' style='width: 80px;' />
                <input name=max_${title} id=max_${title} class="form-control ml-1" type='text' min='0' placeholder='Max' style='width: 80px;' />
            </div>
            `);



            $('input', this).on('change clear', function () {
            var minInputValue = parseFloat($(`#min_${title}`).val().replace(',','.')) || "";
            var maxInputValue = parseFloat($(`#max_${title}`).val().replace(',','.')) || "";


            if (theTable.column(i).search() !== [minInputValue,maxInputValue]) {
            theTable
            .column(i)
            .search([minInputValue,maxInputValue])
            .draw();
            }
            });
            }
            }
            else {
            $(this).html('<span></span>');
            }
            });


            var theTable = $('#tableOfTarifaacabadolineas').DataTable( {
            orderCellsTop: true,
            serverSide: true,
            processing: true,
            autoWidth: true,
            responsive: true,
            fixedHeader: true,
            lengthMenu: [ 5, 10, 25],
            order: [[ 0, "asc" ], [ 1, "asc" ]],
            pageLength: 10,
            lengthChange: true,
            paging: true,
            info: false,
            stateSave: false,
            dom: '<"mt-4"><"float-end"B><"float-start"l><t><"mt-4 mb-3"p>',
                                ajax : $.fn.dataTable.pipeline( {
                                url: '<?= route_to('tarifaAcabadoLineasDT') ?>',
                                data: {
                                id_tarifaacabado: id,
                                },
                                method: 'POST',
                                headers: {'X-Requested-With': 'XMLHttpRequest'},
                                async: true,
                                }),
                                columns: [
                                { 'data': 'proveedor_id',
                                render: function(data, type, row, meta) {
                                var value = suppliersList.find(element => element.value === data);
                                return value['label'];
                                },
                                },
                                { 'data': 'tirada_min',render : (d) => `<span class="autonumeric">${d}</span>` },
                                { 'data': 'precio_max',render : (d) => `<span class="autonumeric">${d}</span>` },
                                { 'data': 'tirada_max',render : (d) => `<span class="autonumeric">${d}</span>` },
                                { 'data': 'precio_min',render : (d) => `<span class="autonumeric">${d}</span>` },
                                { 'data': 'margen',render : (d) => `<span class="autonumeric">${d}</span>` },
                                {
                                data: actionBtns,
                                className: 'row-edit dt-center'
                                }
                                ],
                                columnDefs: [
                                {
                                orderable: false,
                                searchable: false,
                                targets: [lastColNr]
                                },

                                ],
                                language: {
                                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"

                                },
                                buttons: [ {
                                className: 'btn btn-primary me-sm-3 me-1',
                                extend: "createInline",
                                editor: editor,
                                formOptions: {
                                submitTrigger: -1,
                                submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'
                                }
                                } ]
                                } );



                                // Activate an inline edit on click of a table cell
                                $('#tableOfTarifaacabadolineas').on( 'click', 'tbody span.edit', function (e) {
                                editor.inline(
                                theTable.cells(this.parentNode.parentNode, '*').nodes(),
                                {
                                cancelHtml: '<a href="javascript:void(0);"><i class="ti ti-x"></i></a>',
                                cancelTrigger: 'span.cancel',
                                submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>',
                                submitTrigger: 'span.edit',
                                submit: 'allIfChanged'
                                }
                                );
                                } );
          

                                // Delete row
                                $(document).on('click', '.btn-delete', function(e) {
                                $(".btn-remove").attr('data-id', $(this).attr('data-id'));
                                });

                                $(document).on('click', '.btn-remove', function(e) {
                                const dataId = $(this).attr('data-id');
                                const row = $(this).closest('tr');
                                if ($.isNumeric(dataId)) {
                                $.ajax({
                                url: `/tarifas/acabados/lineas/delete/${dataId}`,
                                method: 'GET',
                                }).done((data, textStatus, jqXHR) => {
                                $('#confirm2delete').modal('toggle');
                                theTable.clearPipeline();
                                theTable.row($(row)).invalidate().draw();
                                popSuccessAlert(data.msg ?? jqXHR.statusText);
                                }).fail((jqXHR, textStatus, errorThrown) => {
                                popErrorAlert(jqXHR.responseJSON.messages.error)
                                })
                                }
                                });


                                <?= $this->endSection() ?>

                                <?= $this->section('css') ?>
                                <link rel="stylesheet" href="<?= site_url('themes/vuexy/css/datatables-editor/editor.dataTables.min.css') ?>">
                                <link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.css") ?>">
                                <link rel="stylesheet" href="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/fixedheader/fixedHeader.dataTables.min.css") ?>">
                                <?= $this->endSection() ?>


                                <?= $this->section('additionalExternalJs') ?>
                                <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/dataTables.buttons.min.js") ?>"></script>
                                <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.bootstrap5.min.js") ?>"></script>
                                <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.html5.min.js") ?>"></script>
                                <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/buttons/buttons.print.min.js") ?>"></script>
                                <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/jszip/jszip.min.js") ?>"></script>
                                <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/pdfmake.min.js") ?>" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
                                <script src="<?= site_url("/themes/vuexy/vendor/libs/datatables-sk/plugins/pdfmake/vfs_fonts.js") ?>"></script>
                                <script src="<?= site_url('themes/vuexy/js/datatables-editor/dataTables.editor.min.js') ?>"></script>
                                <?= $this->endSection() ?>