<?= $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="tarifaEnvioForm" 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/envios/_tarifaEnvioFormItems") ?>
            
                <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("tarifaEnvioList"), lang("Basic.global.Cancel"), ["class" => "btn btn-secondary float-start",]) ?> 	
                </div>
			</form>
        </div><!-- //.card -->
    </div><!--//.col -->

	<?php if(str_contains($formAction, 'edit')): ?>
        <div class="accordion mt-3" id="accordionZonas" 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("TarifasEnviosZonas.moduleTitle") ?></h3>
                    </button>
                    
                </h2>

                <div id="accordionTip1" class="accordion-collapse collapse show" data-bs-parent="#accordionZonas">
                    <div class="accordion-body">
                        
                        <table id="tableOfZonas" class="table table-striped table-hover" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th><?= lang('TarifasEnviosZonas.nombre') ?></th>
                                    <th><?= lang('TarifasEnviosZonas.cpInicial') ?></th>
                                    <th><?= lang('TarifasEnviosZonas.cpFinal') ?></th>
                                    <th><?= lang('TarifasEnviosZonas.importeFijo') ?></th>
                                    <th style="min-width:100px"></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>   
                    </div>
                </div>
            </div>
	    </div> <!-- //.accordion -->


        <div class="accordion mt-3" id="accordionPrecios" 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="#accordionTip2" aria-expanded="false" aria-controls="accordionTip2">
                        <h3><?= lang("TarifasEnviosPrecios.moduleTitle") ?></h3>
                    </button>
                    
                </h2>

                <div id="accordionTip2" class="accordion-collapse collapse show" data-bs-parent="#accordionPrecios">
                    <div class="accordion-body">
                        <div id="newButton" class="mb-4 float-end"></div>
                        <table id="tableOfPrecios" class="table table-striped table-hover" style="width: 100%;">
                            <thead>
                                <tr>
                                    <th><?= lang('TarifasEnviosPrecios.proveedorId') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.tipoEnvio') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.pesoMin') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.pesoMax') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.precio_min') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.precio_max') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.precioAdicional') ?></th>
                                    <th><?= lang('TarifasEnviosPrecios.margen') ?></th>
                                    <th style="min-width:100px"></th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>   
                    </div>
                </div>
            </div>
	    </div> <!-- //.accordion -->
	<?php endif; ?>

</div><!--//.row -->
<?= $this->endSection() ?>



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


<!------------------------------------------->
<!-- 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('Zonas')){
            $(".btn-remove").attr('table', "zonas");
        }
        else if($(this).closest('table').attr('id').includes('Precios')){
            $(".btn-remove").attr('table', "precios");
        }
        else{
            $(".btn-remove").attr('table', );
        }
    });

    
    $(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('zonas')){
                remove_zonas(dataId, row);
            }
            else if ($(this).attr('table').includes('precios')){
                remove_precios(dataId, row);
            }
        }
    });
    <?php endif; ?>
<?= $this->endSection() ?>


<!------------------------------------------->
<!-- Código JS para  tableOfZonas -->
<!------------------------------------------->
<?= $this->section("additionalInlineJs") ?>
	const lastColNr = $('#tableOfZonas').find("tr:first th").length - 1;

	var editor = new $.fn.dataTable.Editor( {
        ajax: {
            url: "<?= route_to('editorOfTarifasEnvioZonas') ?>", 
            headers: {
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
            },
        },
        table   : "#tableOfZonas",
        idSrc:  'id',
        fields: [ {
                name: "nombre"
            },
            {
                name: "cp_inicial"
            }, {
                name: "cp_final"
            }, {
                name: "importe_fijo",
                attr: {
                type: "text",
                name : "importe_fijo",
                class :"autonumeric"
            }
            }, {
                "name": "tarifa_envio_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_envio_id'] = id;
        }
        else if(type === 'edit' ) {
            for (v in d.data){
                d.data[v]['tarifa_envio_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 = $('#tableOfZonas').DataTable( {
		serverSide: true,
        processing: true,
        autoWidth: true,
        responsive: true,
        lengthMenu: [ 5, 10, 25],
        order: [[ 0, "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>',
        "buttons": [
            'copy', 'csv', 'excel', 'print', {
                extend: 'pdfHtml5',
                orientation: 'landscape',
                pageSize: 'A4'
            }
        ],
		ajax : $.fn.dataTable.pipeline( {
            url: '<?= route_to('dataTableOfTarifasEnvioZonas') ?>',
            data: {
                tarifa_envio_id: id,
            },
            method: 'POST',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            async: true,
        }),
        columns: [
            { 'data': 'nombre' },
            { 'data': 'cp_inicial' },
            { 'data': 'cp_final' },
            { 'data': 'importe_fijo',render : (d) => `<span class="autonumeric">${d}</span>` },
            {
                data: actionBtns,
                className: 'row-edit dt-center'
            }
        ],
        columnDefs: [
            {
                orderable: false,
                searchable: false,
                targets: [lastColNr]
            },
            {"orderData": [ 0],    "targets": 0 },

        ],
        language: {
            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
        },
        buttons: [ {
            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
    $('#tableOfZonas').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_zonas(dataId, row){

        $.ajax({
                url: `/tarifas/tarifasenvioszonas/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) => {
                if(typeof jqXHR.responseJSON.messages != "undefined")
                    popErrorAlert(jqXHR.responseJSON.messages.error);
                else 
                    popErrorAlert(jqXHR.responseJSON.message);
                $('#confirm2delete').modal('toggle');
        });
    }      
	
<?= $this->endSection() ?>


<!------------------------------------------->
<!-- Código JS para  tableOfPrecios -->
<!------------------------------------------->
<?= $this->section("additionalInlineJs") ?>
const lastColNr2 = $('#tableOfPrecios').find("tr:first th").length - 1;

	var editor2 = new $.fn.dataTable.Editor( {
        ajax: {
            url: "<?= route_to('editorOfTarifasEnvioPrecios') ?>", 
            headers: {
                <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
            },
        },
        table   : "#tableOfPrecios",
        idSrc:  'id',
        fields: [ 
            {
                "name": "proveedor_id",
                "type": "select"
            }, {
                name: "tipo_envio",
                "type": "select"
            }, {
                name: "peso_min",
                attr: {
        type: "text",
        name : "peso_min",
        class :"autonumeric"
        }
            }, {
                name: "peso_max",
                attr: {
        type: "text",
        name : "peso_max",
        class :"autonumeric"
        }
            }, {
                name: "precio_min",
                attr: {
        type: "text",
        name : "precio_min",
        class :"autonumeric"
        }
            }, {
                name: "precio_max",
                attr: {
        type: "text",
        name : "precio_max",
        class :"autonumeric"
        }
            }, {
                name: "precio_adicional",
                def: 0,
                attr: {
        type: "text",
        name : "precio_adicional",
        class :"autonumeric"
        }
            }, {
                name: "margen",
                attr: {
        type: "text",
        name : "margen",
        class :"autonumeric"
        }
            }, {
                "name": "tarifa_envio_id",
                "type": "hidden"
            }, {
                "name": "deleted_at",
                "type": "hidden"
            },{
                "name": "is_deleted",
                "type": "hidden"
            },
        ]
    } );
    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
                        }
                    });
                });
            }
        })
    // Generación de la lista de proveedores (id, nombre) 
    const suppliersList = <?php echo json_encode($proveedores); ?>;
    editor2.field( 'proveedor_id' ).update( suppliersList );

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

    editor2.dependent('proveedor_id', function (val, data, callback, e ) {
        
        var supplier = suppliersList.find(o => o.value === val);
        values = [];
        
        if(supplier.options != null)
        {
            if(supplier.options.includes("cajas")){
                values.push({label:'<?= lang('TarifasEnviosPrecios.cajas') ?>', value: "cajas"});
            }
            if(supplier.options.includes("palets")){
                values.push({label:'<?= lang('TarifasEnviosPrecios.palets') ?>', value: "palets"});
            }
        }
        editor2.field( 'tipo_envio' ).update( values );
        callback(true);
    });

    editor2.on( 'postSubmit', function ( e, json, data, action ) {
        
        yeniden(json.<?= csrf_token() ?>);
    });


    editor2.on( 'submitSuccess', function ( e, json, data, action ) {
        
        theTable2.clearPipeline();
        theTable2.draw();
    });

    
    var theTable2 = $('#tableOfPrecios').DataTable( {
		serverSide: true,
        processing: true,
        autoWidth: true,
        responsive: true,
        lengthMenu: [ 5, 10, 25, 50, 100],
        order: [ 0, "asc" ],
        pageLength: 25,
        lengthChange: true,
        searching: true,
        paging: true,
        info: false,
        //dom: '<"mt-4"><"float-end"B><"float-start"l><t><"mt-4 mb-3"p>',
        dom: 'Brtip',
		ajax : $.fn.dataTable.pipeline( {
            url: '<?= route_to('dataTableOfTarifasEnvioPrecios') ?>',
            data: function ( d ) {
                d.tarifa_envio_id =  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': 'tipo_envio',  "render": function ( data, type, row, meta ) {
                    if (data=='cajas')
                        return '<?= lang('TarifasEnviosPrecios.cajas') ?>';
                    else if (data=='palets')
                        return '<?= lang('TarifasEnviosPrecios.palets') ?>';
                }
            },
            { 'data': 'peso_min',render : (d) => `<span class="autonumeric">${d}</span>` },
            { 'data': 'peso_max',render : (d) => `<span class="autonumeric">${d}</span>` },
            { 'data': 'precio_min',render : (d) => `<span class="autonumeric">${d}</span>` },
            { 'data': 'precio_max',render : (d) => `<span class="autonumeric">${d}</span>` },
            { 'data': 'precio_adicional',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: [lastColNr2]
            },
            {"orderData": [ 0, 1 ],    "targets": 0 },

        ],
        language: {
            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json",
        },
        buttons: [ 'copy', 'csv', 'excel', 'print', {
            extend: 'pdfHtml5',
            orientation: 'landscape',
            pageSize: 'A4'
        }],

        initComplete: function () {

            new $.fn.dataTable.Buttons(theTable2, {
                name: 'btn_new',
                buttons: [{
                    className: 'btn btn-primary float-end',
                    extend: "createInline",
                    editor: editor2,
                    formOptions: {
                        submitTrigger: -1,
                        submitHtml: '<a href="javascript:void(0);"><i class="ti ti-device-floppy"></i></a>'

                    }
                }]
            });

            var $newbtncontainer = $("<div style='float: right;'></div>");
            $("#tableOfPrecios_wrapper").prepend($newbtncontainer);
            

            theTable2.buttons('btn_new', null)
                .container()
                .appendTo($newbtncontainer);
        }
    } );




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

        $.ajax({
                url: `/tarifas/tarifasenviosprecios/delete/${dataId}`,
                method: 'GET',
            }).done((data, textStatus, jqXHR) => {
                $('#confirm2delete').modal('toggle');
                theTable2.clearPipeline();
                theTable2.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/css/sk-datatables.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() ?>


<?php endif; ?>

