<?= $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="tarifaEncuadernacionForm" 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/encuadernacion/_tarifaEncuadernacionFormItems") ?>
                <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("tarifaEncuadernacionList"), lang("Basic.global.Cancel"), ["class" => "btn btn-secondary float-start",]) ?>

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


    <?php if (str_contains($formAction, 'edit')): ?>
        <div class="accordion mt-3" id="accordionEncuadernacionTiradas" style="visibility:visible">
            <div class="card accordion-item active">
                <h2 class="accordion-header" id="headingZero">
                    <button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionTip0" aria-expanded="false" aria-controls="accordionTip0">
                        <h3><?= lang("TarifaEncuadernacionTiradas.moduleTitle") ?></h3>
                    </button>

                </h2>

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

                        <table id="tableOfTarifaencuadernaciontiradas" class="table table-striped table-hover" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th><?= lang('TarifaEncuadernacionTiradas.proveedor') ?></th>
                                    <th><?= lang('TarifaEncuadernacionTiradas.tiradaMin') ?></th>
                                    <th><?= lang('TarifaEncuadernacionTiradas.tiradaMax') ?></th>
                                    <th><?= lang('Tarifaencuadernacion.importeFijo') ?></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div> <!-- //.accordion -->

        <div class="accordion mt-3" id="accordionEncuadernacionLineas" style="visibility:visible">
            <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("TarifaEncuadernacionLineas.moduleTitle") ?></h3>
                    </button>
                </h2>
                <div id="accordionTip1" class="accordion-collapse collapse show" data-bs-parent="#accordionEncuadernacionLineas">
                    <div class="accordion-body">

                        <p><?= lang("TarifaEncuadernacionLineas.moduleExplanation") ?></p>

                        <table id="tableOfTarifaencuadernacionlineas" class="table table-striped table-hover" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th><?= lang('TarifaEncuadernacionLineas.dimensiones') ?></th>
                                    <th><?= lang('TarifaEncuadernacionLineas.paginasMin') ?></th>
                                    <th><?= lang('TarifaEncuadernacionLineas.precioMin') ?></th>
                                    <th><?= lang('TarifaEncuadernacionLineas.paginasMax') ?></th>
                                    <th><?= lang('TarifaEncuadernacionLineas.precioMax') ?></th>
                                    <th><?= lang('Tarifaencuadernacion.importeMin') ?></th>
                                    <th><?= lang('TarifaEncuadernacionLineas.margen') ?></th>
                                    <th style="min-width:100px"></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div> <!-- //.accordion -->

        <div class="accordion mt-3 d-none" id="accordionEncuadernacionLineasHoras" style="visibility:visible">
            <div class="card accordion-item active">
                <h2 class="accordion-header" id="headingThree">
                    <button type="button" class="accordion-button" data-bs-toggle="collapse" data-bs-target="#accordionTip3" aria-expanded="false" aria-controls="accordionTip3">
                        <h3><?= lang("TarifaEncuadernacionLineas.moduleTitle") ?></h3>
                    </button>
                </h2>
                <div id="accordionTip3" class="accordion-collapse collapse show" data-bs-parent="#accordionEncuadernacionLineasHoras">
                    <div class="accordion-body">

                        <table id="tableOfTarifaencuadernacionlineasHoras" class="table table-striped table-hover" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th><?= lang('TarifaEncuadernacionLineas.tiempoMin') ?></th>
                                    <th><?= lang('TarifaEncuadernacionLineas.tiempoMax') ?></th>
                                    <th><?= lang('TarifaEncuadernacionLineas.precioHora') ?></th>
                                    <th><?= lang('Tarifaencuadernacion.importeMin') ?></th>
                                    <th><?= lang('TarifaEncuadernacionLineas.margen') ?></th>
                                    <th style="min-width:100px"></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div> <!-- //.accordion -->
        <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" => $tarifaEncuadernacionEntity->id]) ?>
                    </div>
                </div>
            </div>
        </div> <!-- //.accordion -->




        <?= view("themes/_commonPartialsBs/_modalConfirmDialog") ?>
    <?php endif; ?>
</div><!--//.row -->

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

<?= $this->section("additionalExternalJs") ?>
<script type="module" src="<?= site_url('assets/js/safekat/pages/tarifas/maquinas/encuadernacion/index.js') ?>"></script>
<?= $this->endSection() ?>
<!------------------------------------------->
<!-- Código JS para  general -->
<!------------------------------------------->
<?= $this->section("additionalInlineJs") ?>
const url = window.location.href;
const url_parts = url.split('/');
var id = -1;
if (url_parts[url_parts.length - 2] == 'edit') {
    id = url_parts[url_parts.length - 1];
}
else {
    id = -1;
}

<?php if (str_contains($formAction, 'edit')): ?>
    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>
            `;
};

// Delete row
$(document).on('click', '.btn-delete', function (e) {
    $(".btn-remove").attr('data-id', $(this).attr('data-id'));
    if ($(this).closest('table').attr('id').includes('tiradas')) {
        $(".btn-remove").attr('table', "tiradas");
    }
    else if ($(this).closest('table').attr('id').includes('lineas')) {
        $(".btn-remove").attr('table', "lineas");
    }
    else {
        $(".btn-remove").attr('table',);
    }
});

var selected_tirada_id = -1;


$(document).on('click', '.btn-remove', function (e) {
    const dataId = $(this).attr('data-id');
    const row = $(this).closest('tr');
    if ($.isNumeric(dataId)) {

        if ($(this).attr('table').includes('tiradas')) {
            remove_tiradas(dataId, row);
        }
        else if ($(this).attr('table').includes('lineasHoras')) {
            remove_lineas_horas(dataId, row);
        }
        else {
            remove_lineas(dataId, row);
        }
    }
});

function check_por_horas() {
    if ($('#por_horas').is(':checked')) {
        $('#accordionEncuadernacionLineasHoras').removeClass("d-none");
        $('#accordionEncuadernacionLineas').addClass("d-none");
    }
    else {
        $('#accordionEncuadernacionLineasHoras').addClass("d-none");
        $('#accordionEncuadernacionLineas').removeClass("d-none");
    }
}
check_por_horas()

$("#por_horas").change(function () {
    asyncConfirmDialog('<?= lang('Tarifaencuadernacion.sureToChange') ?>',
        '<?= lang('Tarifaencuadernacion.sureToChangePorHorasText') ?>', yesCallback, noCallback);
});

function yesCallback() {

    check_por_horas()
    if ($('#por_horas').is(':checked')) {

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

        $.ajax({
            url: '<?= route_to('dataTableOfTarifaEncuadernacionLineas') ?>',
            data: {
                cleandatatable: 1,
                tarifa_encuadernacion_id: id,
                <?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
            },
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            success: function (response) {
                token = response.<?= csrf_token() ?>;
                yeniden(token);

                theTable3.clearPipeline();
                theTable3.draw();

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

    }else {

        theTable3.clearPipeline();
        theTable3.draw();

        $.ajax({
            url: '<?= route_to('dataTableOfTarifaEncuadernacionLineasHoras') ?>',
            data: {
                cleandatatable: 1,
                tarifa_encuadernacion_id: id,
               <?= csrf_token() ?? "token" ?>: <?= csrf_token() ?>v,
            },
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            success: function (response) {

                token = response.<?= csrf_token() ?>;
                yeniden(token);

                theTable3.clearPipeline();
                theTable3.draw();

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

function noCallback() {
    // Toggle behaviour
    $('#por_horas').prop("checked", !$('#por_horas').prop("checked"));
}
<?php endif; ?>
<?= $this->endSection() ?>


<?php if (str_contains($formAction, 'edit')): ?>

<!------------------------------------------->
<!-- Código JS para  tableOfTarifaencuadernacionlineashoras -->
<!------------------------------------------->
<?= $this->section("additionalInlineJs") ?>

const lastColNr3 = $('#tableOfTarifaencuadernacionlineasHoras').find("tr:first th").length - 1;

var editor3 = new $.fn.dataTable.Editor({
    ajax: {
        url: "<?= route_to('editorOfTarifaEncuadernacionLineasHoras') ?>",
        headers: {
        <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
        },
    },
    table : "#tableOfTarifaencuadernacionlineasHoras",
    idSrc: 'id',
        fields: [
        {
            name: "id",
            "type": "readonly"
        },
        {
            name: "tiempo_min",
            attr: {
                type: "text",
                name: "tiempo_min",
                class: "autonumeric"
            }
        }, {
            name: "tiempo_max",
            attr: {
                type: "text",
                name: "tiempo_max",
                class: "autonumeric"
            }
        }, {
            name: "precio_hora",
            attr: {
                type: "text",
                name: "precio_hora",
                class: "autonumeric"
            }
        }, {
            name: "total_min",
            attr: {
                type: "text",
                name: "total_min",
                class: "autonumeric"
            }
        }, {
            name: "margen",
            attr: {
                type: "text",
                name: "margen",
                class: "autonumeric"
            }
        }, {
            "name": "tirada_encuadernacion_id",
            "type": "hidden"
        }, {
            "name": "deleted_at",
            "type": "hidden"
        }, {
            "name": "is_deleted",
            "type": "hidden"
        },
    ]
});

editor3.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,
        });
    })
})

editor3.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
                }
            });
        });
    }
})

editor3.on('preSubmit', function (e, d, type) {
    if (type === 'create') {
        d.data[0]['tirada_encuadernacion_id'] = selected_tirada_id;
    }
    else if (type === 'edit') {
        for (v in d.data) {
            d.data[v]['tirada_encuadernacion_id'] = selected_tirada_id;
        }
    }
});


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

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


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

    theTable3.clearPipeline();
    theTable3.draw();
});


var theTable3 = $('#tableOfTarifaencuadernacionlineasHoras').DataTable({
    draw: 3,
    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('dataTableOfTarifaEncuadernacionLineasHoras') ?>',
        data: function (d) {
            d.tirada_id = selected_tirada_id;
        },
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        async: true,
    }),
    columns: [
        { 'data': 'id' },
        { 'data': 'tiempo_min', render: (d) => `<span class="autonumeric">${d}</span>` },
        { 'data': 'tiempo_max', render: (d) => `<span class="autonumeric">${d}</span>` },
        { 'data': 'precio_hora', render: (d) => `<span class="autonumeric">${d}</span>` },
        { 'data': 'total_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: [lastColNr3]
        },
        { "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: editor3,
            formOptions: {
                submitTrigger: -1,
                submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'

            },
            action: function (e, dt, node, config) {
                if (selected_tirada_id == -1) {
                    popErrorAlert("<?= lang('TarifaEncuadernacionLineas.validation.error_seleccion_tiradas') ?>");
                }
                else {
                    formOptions = {
                        submitTrigger: -1,
                        submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'

                    };
                    editor3.inlineCreate(config.position, formOptions);
                }
            },
        }
    ]
});


// Activate an inline edit on click of a table cell
$('#tableOfTarifaencuadernacionlineasHoras').on('click', 'tbody span.edit', function (e) {
    editor3.inline(
        theTable3.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
function remove_lineas_horas(dataId, row) {

    $.ajax({
        url: `/tarifas/tarifaencuadernacionlineashoras/delete/${dataId}`,
        method: 'GET',
    }).done((data, textStatus, jqXHR) => {
        $('#confirm2delete').modal('toggle');
        theTable3.clearPipeline();
        theTable3.row($(row)).invalidate().draw();
        popSuccessAlert(data.msg ?? jqXHR.statusText);
    }).fail((jqXHR, textStatus, errorThrown) => {
        popErrorAlert(jqXHR.responseJSON.messages.error)
    });

}

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


<!------------------------------------------->
<!-- Código JS para  tableOfTarifaencuadernacionlineas -->
<!------------------------------------------->
<?= $this->section("additionalInlineJs") ?>

const lastColNr = $('#tableOfTarifaencuadernacionlineas').find("tr:first th").length - 1;

var editor = new $.fn.dataTable.Editor({
    ajax: {
        url: "<?= route_to('editorOfTarifaEncuadernacionLineas') ?>",
        headers: {
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
        },
    },
    table : "#tableOfTarifaencuadernacionlineas",
    idSrc: 'id',
    fields: [
    {
        name: "id",
        "type": "readonly"
    },
    {
        name: "dimensiones_id",
        "type": "select"
    },
    {
        name: "paginas_libro_min",
        attr: {
            type: "text",
            name: "paginas_libro_min",
            class: "autonumeric"
        }
    }, {
        name: "precio_min",
        attr: {
            type: "text",
            name: "precio_min",
            class: "autonumeric"
        }
    }, {
        name: "paginas_libro_max",
        attr: {
            type: "text",
            name: "paginas_libro_max",
            class: "autonumeric"
        }
    }, {
        name: "precio_max",
        attr: {
            type: "text",
            name: "precio_min",
            class: "autonumeric"
        }
    }, {
        name: "total_min",
        attr: {
            type: "text",
            name: "total_min",
            class: "autonumeric"
        }
    }, {
        name: "margen",
        attr: {
            type: "text",
            name: "margen",
            class: "autonumeric"
        }
    }, {
        "name": "tirada_encuadernacion_id",
        "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 dimensionesList = <?php echo json_encode($dimensiones); ?>;
editor.field('dimensiones_id').update(dimensionesList);
editor.on('open', (event) => {
    $("input.autonumeric").each(function () {
        let autoNumericInstance = AutoNumeric.getAutoNumericElement(this)
        if (autoNumericInstance) {
            autoNumericInstance.remove()

        }
        new AutoNumeric(this, {
            alwaysAllowDecimalCharacter: true,
            decimalCharacter: ",",
            decimalPlaces: 2,
            allowDecimalPadding: 'floats',
            digitGroupSeparator: ".",
            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]['tirada_encuadernacion_id'] = selected_tirada_id;
    }
    else if (type === 'edit') {
        for (v in d.data) {
            d.data[v]['tirada_encuadernacion_id'] = selected_tirada_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 = $('#tableOfTarifaencuadernacionlineas').DataTable({
    draw: 2,
    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('dataTableOfTarifaEncuadernacionLineas') ?>',
        data: function (d) {
            d.tirada_id = selected_tirada_id;
        },
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        async: true,
    }),
    columns: [
        { 'data': 'id' },
        {
            'data': 'dimensiones_id',
            render: function (data, type, row, meta) {
                var value = dimensionesList.find(element => element.value === data);
                return value['label'];
            },
        },
        { 'data': 'paginas_libro_min', render: (d) => `<span class="autonumeric">${d}</span>` },
        { 'data': 'precio_max', render: (d) => `<span class="autonumeric">${d}</span>` },
        { 'data': 'paginas_libro_max', render: (d) => `<span class="autonumeric">${d}</span>` },
        { 'data': 'precio_min', render: (d) => `<span class="autonumeric">${d}</span>` },
        { 'data': 'total_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>'

            },
            action: function (e, dt, node, config) {
                if (selected_tirada_id == -1) {
                    popErrorAlert("<?= lang('TarifaEncuadernacionLineas.validation.error_seleccion_tiradas') ?>");
                }
                else {
                    formOptions = {
                        submitTrigger: -1,
                        submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'

                    };
                    editor.inlineCreate(config.position, formOptions);
                }
            },
        }
    ]
});


// Activate an inline edit on click of a table cell
$('#tableOfTarifaencuadernacionlineas').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
function remove_lineas(dataId, row) {

    $.ajax({
        url: `/tarifas/tarifaencuadernacionlineas/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() ?>

<!------------------------------------------->
<!-- Código JS para  tableOfTarifaencuadernaciontiradas -->
<!------------------------------------------->
<?= $this->section("additionalInlineJs") ?>

// Definicion de la ultima columna de la tabla
const lastColNr2 = $('#tableOfTarifaencuadernaciontiradas').find("tr:first th").length - 1;

// Datatables Editor
var editor2 = new $.fn.dataTable.Editor({
    ajax: {
        url: "<?= route_to('editorOfTarifaEncuadernacionTiradas') ?>",
        headers: {
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
            },
        },
    table : "#tableOfTarifaencuadernaciontiradas",
    idSrc: 'id',
    fields: [{
        name: "proveedor_id",
        "type": "select"
    }, {
        name: "tirada_min",
        attr: {
            type: "text",
            name: "tirada_min",
            class: "autonumeric"
        }
    }, {
        name: "tirada_max",
        attr: {
            type: "text",
            name: "tirada_max",
            class: "autonumeric"
        }
    }, {
        name: "importe_fijo",
        attr: {
            type: "text",
            name: "importe_fijo",
            class: "autonumeric"
        }
    }, {
        "name": "tarifa_encuadernacion_id",
        "type": "hidden"
    }, {
        name: "proveedor",
        "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); ?>;
editor2.field('proveedor_id').update(suppliersList);

editor2.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,
        });
    })
})
editor2.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
                }
            });
        });
    }
})
editor2.on('preSubmit', function (e, d, type) {
    if (type === 'create') {
        d.data[0]['tarifa_encuadernacion_id'] = id;
    }
    else if (type === 'edit') {
        for (v in d.data) {
            d.data[v]['tarifa_encuadernacion_id'] = id;
        }
    }
});


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

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


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

    theTable2.clearPipeline();
    theTable2.draw();
});


// Tabla de tiradas
var theTable2 = $('#tableOfTarifaencuadernaciontiradas').DataTable({
    draw: 1,
    serverSide: true,
    processing: true,
    autoWidth: true,
    responsive: true,
    lengthMenu: [5, 10, 25],
    order: [0, "asc"],
    pageLength: 10,
    lengthChange: true,
    searching: false,
    paging: true,
    select: 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('dataTableOfTarifaEncuadernacionTiradas') ?>',
        data: {
            id_tarifaencuadernacion: 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': 'tirada_max', render: (d) => `<span class="autonumeric">${d}</span>` },
        { 'data': 'importe_fijo', render: (d) => `<span class="autonumeric">${d}</span>` },
        {
            data: actionBtns,
            className: 'row-edit dt-center'
        }
    ],
    columnDefs: [
        {
            orderable: false,
            searchable: false,
            targets: [lastColNr2]
        },

    ],
    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: editor2,
            formOptions: {
                submitTrigger: -1,
                submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'
            }
        }]
});


// Obtener la id de la fila seleccionada o ponerla a -1 cuando no haya ninguna seleccionada
var selected_tirada_id = -1;
theTable2.on('select', function (e, dt, type, indexes) {
    if (type === 'row') {

        selected_tirada_id = parseInt(theTable2.rows(indexes).data().pluck('id')[0]);
        if ($('#por_horas').is(':checked')) {
            theTable3.clearPipeline();
            theTable3.draw();
        }
        else {
            theTable.clearPipeline();
            theTable.draw();
        }
    }
});

theTable2.on('deselect', function (e, dt, type, indexes) {
    if (theTable2.rows('.selected').count() == 0) {
        selected_tirada_id = -1;
        if ($('#por_horas').is(':checked')) {
            theTable3.clearPipeline();
            theTable3.draw();
        }
        else {
            theTable.clearPipeline();
            theTable.draw();
        }
    }
});


// Activate an inline edit on click of a table cell
$('#tableOfTarifaencuadernaciontiradas').on('click', 'tbody span.edit', function (e) {
    editor2.inline(
        theTable2.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
function remove_tiradas(dataId, row) {

    $.ajax({
        url: `/tarifas/tarifaencuadernaciontiradas/delete/${dataId}`,
        method: 'GET',
    }).done((data, textStatus, jqXHR) => {
        $('#confirm2delete').modal('toggle');
        theTable2.clearPipeline();
        theTable2.row($(row)).invalidate().draw();
        theTable.clearPipeline();
        theTable.draw();
        popSuccessAlert(data.msg ?? jqXHR.statusText);
    }).fail((jqXHR, textStatus, errorThrown) => {
        popErrorAlert(jqXHR.statusText)
    });
}

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

<?php endif; ?>

<?= $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/select/dataTables.select.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() ?>