<?= $this->include("themes/_commonPartialsBs/datatables") ?>
<?= $this->include("themes/_commonPartialsBs/select2bs5") ?>
<?= $this->include("themes/_commonPartialsBs/sweetalert") ?>
<?= $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="tarifaManipuladoForm" 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/manipulado/_tarifaManipuladoFormItems") ?>
                <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("tarifaManipuladoList"), lang("Basic.global.Cancel"), ["class" => "btn btn-secondary float-start",]) ?>

                </div><!-- /.card-footer -->
            </form>
        </div><!-- //.card -->
    </div><!--//.col -->

    <?php if ($formAction == site_url('tarifas/tarifasmanipulado/add')): ?>
        <div class="accordion mt-3" id="accordionManipuladoLineas" style="visibility:hidden">
        <?php else: ?>
            <div class="accordion mt-3" id="accordionManipuladoLineas" 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("TarifaManipuladoLineas.moduleTitle") ?></h3>
                    </button>

                </h2>

                <div id="accordionTip1" class="accordion-collapse collapse show" data-bs-parent="#accordionManipuladoLineas">
                    <div class="accordion-body">

                        <table id="tableOfTarifamanipuladolineas" class="table table-striped table-hover" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th><?= lang('TarifaManipuladoLineas.tiradaMin') ?></th>
                                    <th><?= lang('TarifaManipuladoLineas.precioMax') ?></th>
                                    <th><?= lang('TarifaManipuladoLineas.tiradaMax') ?></th>
                                    <th><?= lang('TarifaManipuladoLineas.precioMin') ?></th>
                                    <th><?= lang('TarifaManipuladoLineas.margen') ?></th>
                                    <th style="min-width:100px"></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            </div> <!-- //.accordion -->
            <?php if ($tarifaManipuladoEntity?->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" => $tarifaManipuladoEntity?->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/manipulado/index.js') ?>"></script>
        <?= $this->endSection() ?>


        <?= $this->section("additionalInlineJs") ?>

        const lastColNr = $('#tableOfTarifamanipuladolineas').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>
        `;
        };


        editor = new $.fn.dataTable.Editor( {
        ajax: {
        url: "<?= route_to('editorOfTarifaManipuladoLineas') ?>",
        headers: {
        <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
        },
        },
        table : "#tableOfTarifamanipuladolineas",
        idSrc: 'id',
        fields: [ {
        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_manipulado_id",
        "type": "hidden"
        },{
        "name": "deleted_at",
        "type": "hidden"
        },{
        "name": "is_deleted",
        "type": "hidden"
        },
        ]
        } );

        editor.on('open', (event) => {
        $("input.autonumeric").each(function () {
            let autoNumericInstance = AutoNumeric.getAutoNumericElement(this)
            if (autoNumericInstance) {
                autoNumericInstance.remove()

            }
            new AutoNumeric(this, {
                decimalCharacter: ",",
                digitGroupSeparator: ".",
                allowDecimalPadding : 'floats',
                decimalPlaces: 2,
                unformatOnSubmit: true,
            });
        })
    })
        editor.on('preSubmit', (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
                        }
                    });
                });
            }
        })
        editor.on( 'preSubmit', function ( e, d, type ) {

        if ( type === 'create'){
        d.data[0]['tarifa_manipulado_id'] = id;
        }
        else if(type === 'edit' ) {
        for (v in d.data){
        d.data[v]['tarifa_manipulado_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();
        });


        var theTable = $('#tableOfTarifamanipuladolineas').DataTable( {
        serverSide: true,
        processing: true,
        autoWidth: true,
        responsive: true,
        lengthMenu: [ 5, 10, 25],
        order: [[ 0, "asc" ], [ 1, "asc" ]],
        pageLength: 10,
        lengthChange: true,
        searching: false,
        paging: true,
        info: false,
        dom: '<"mt-4"><"float-end"B><"float-start"l><t><"mt-4 mb-3"p>',
                            ajax : $.fn.dataTable.pipeline( {
                            url: '<?= route_to('dataTableOfTarifaManipuladoLineas') ?>',
                            data: {
                            id_tarifamanipulado: id,
                            },
                            method: 'POST',
                            headers: {'X-Requested-With': 'XMLHttpRequest'},
                            async: true,
                            }),
                            columns: [
                            { '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]
                            },
                            {"orderData": [ 0, 1 ], "targets": 0 },

                            ],
                            language: {
                            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
                            },
                            buttons: [
                            {
                            extend: 'collection',
                            text: 'Exportar',
                            buttons:[
                            'copy', 'csv', 'excel', 'print', {
                            extend: 'pdfHtml5',
                            orientation: 'landscape',
                            pageSize: 'A4'
                            }
                            ]
                            },
                            {
                            className: 'btn btn-primary float-end 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
                            $('#tableOfTarifamanipuladolineas').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
                            $('#tableOfTarifamanipuladolineas').on( 'click', 'tbody span.remove', function (e) {

                            Swal.fire({
                            title: '<?= lang('Basic.global.sweet.sureToDeleteTitle', [mb_strtolower(lang('Basic.global.sweet.line'))]) ?>',
                            text: '<?= lang('Basic.global.sweet.sureToDeleteText') ?>',
                            icon: 'warning',
                            showCancelButton: true,
                            confirmButtonColor: '#3085d6',
                            confirmButtonText: '<?= lang('Basic.global.sweet.deleteConfirmationButton') ?>',
                            cancelButtonText: '<?= lang('Basic.global.Cancel') ?>',
                            cancelButtonColor: '#d33'
                            })
                            .then((result) => {
                            const dataId = $(this).data('id');
                            const row = $(this).closest('tr');
                            if (result.value) {
                            editor
                            .create( false )
                            .edit( this.parentNode, false)
                            .set( 'deleted_at', new Date().toISOString().slice(0, 19).replace('T', ' ') )
                            .set( 'is_deleted', 1 )
                            .submit();

                            }
                            });
                            });


                            // 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/tarifamanipuladolineas/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") ?>">
                            <?= $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() ?>