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

<?= $this->section('content');  ?>
<div class="row">
    <div class="col-md-12">
        <div class="card card-info">
            <div class="card-header">
                <h3 class="card-title"><?=lang('Clientes.direccionesEnvio') ?></h3>
           </div><!--//.card-header -->
            <div class="card-body">
				<?= view('themes/_commonPartialsBs/_alertBoxes'); ?>
                <?= view("themes/vuexy/form/clientes/cliente/_clienteDireccionesForm") ?>

                <table id="tableOfDireccionesEnvio" class="table dt-responsive dataTable" style="width: 100%;">
                    <thead>
                        <tr>
                        <th><?= lang('ClienteDirecciones.alias') ?></th>
                            <th><?= lang('ClienteDirecciones.att') ?></th>
                            <th><?= lang('ClienteDirecciones.email') ?></th>
                            <th><?= lang('ClienteDirecciones.direccion') ?></th>
                            <th><?= lang('ClienteDirecciones.cp') ?></th>
                            <th><?= lang('ClienteDirecciones.municipio') ?></th>
                            <th><?= lang('ClienteDirecciones.provincia') ?></th>
                            <th><?= lang('ClienteDirecciones.pais') ?></th>
                            <th><?= lang('ClienteDirecciones.telefono') ?></th>
                            <th class="text-nowrap" style="min-width:100px;"><?= lang('Basic.global.Action') ?></th>
                        </tr>
                    </thead>
                    <tbody>
                                                    
                    </tbody>
                </table>
            </div><!--//.card-body -->
            <div class="card-footer">
            </div><!--//.card-footer -->
        </div><!--//.card -->
    </div><!--//.col -->
</div><!--//.row -->

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



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


function saveAdd_callback(){
    if($('#addressForm').attr('action')=='create'){
        editorAddress
            .create( false )
            .set( 'cliente_id', <?= $cliente_id ?> )
            .set( 'alias', $('#add_alias').val() )
            .set( 'att', $('#add_att').val() )
            .set( 'email', $('#add_email').val() )
            .set( 'direccion', $('#add_direccion').val() )
            .set( 'pais_id', $("#add_pais_id option:selected").val())
            .set( 'municipio', $('#add_municipio').val() )
            .set( 'provincia', $('#add_provincia').val() )
            .set( 'cp', $('#add_cp').val() )
            .set( 'telefono', $('#add_telefono').val() )
            .submit();
    }
    else{ // edit
        editorAddress
            .edit( '#tableOfDireccionesEnvio tbody tr:eq('+$("#addressForm").attr('row-index')+ ')', false )
            .set( 'cliente_id', <?= $cliente_id ?> )
            .set( 'alias', $('#add_alias').val() )
            .set( 'att', $('#add_att').val() )
            .set( 'email', $('#add_email').val() )
            .set( 'direccion', $('#add_direccion').val() )
            .set( 'pais_id', $("#add_pais_id option:selected").val())
            .set( 'municipio', $('#add_municipio').val() )
            .set( 'provincia', $('#add_provincia').val() )
            .set( 'cp', $('#add_cp').val() )
            .set( 'telefono', $('#add_telefono').val() )
            .submit();

    }
}


const editorAddress = new DataTable.Editor({
    ajax: {
        url: "<?= route_to('editorOfClienteDirecciones') ?>",
        headers: {
            <?= csrf_token() ?? "token" ?> : <?= csrf_token() ?>v,
        },
    },
    table   : "#tableOfDireccionesEnvio",
    idSrc:  'id',
    fields: [ {
            name: "alias"
        }, {
            name: "att"
        }, {
            name: "email"
        }, {
            name: "direccion"
        }, {
            name: "municipio"
        }, {
            name: "provincia"
        }, {
            name: "pais_id"
        }, {
            name: "cp"
        }, {
            name: "telefono"
        }, {
            "name": "cliente_id",
            "type": "hidden"
        },
    ],
    template: '#direccionesForm'
});

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

    $( ".error-text-form" ).remove();
    if('fieldErrors' in json){
        if(json.fieldErrors.length > 0){
            json.fieldErrors.forEach((error) => {
                $('#add_' + error.name).after(
                    "<p style='font-size: 11px !important;" +  
                        "padding: 0 !important; " + 
                        "color: #b11f1f !important;' " + 
                        "class='error-text-form'>" + error.status + '</p>')
            })
        }
    }
    else{
        $('#addressForm').modal("hide");        
    }

})

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

editorAddress.on( 'close', function ( e, json, data, action ) {
    $('#tableOfDireccionesEnvio').DataTable().ajax.reload();
})

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

var tableDirecciones = $('#tableOfDireccionesEnvio').DataTable( {
		draw:2,
        serverSide: true,
        processing: true,
        autoWidth: true,
        responsive: true,
        order: [0, "asc" ],
        pageLength: 10,
        lengthChange: false,
        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('dataTableOfClienteDirecciones') ?>',
            data: function ( d ) {
                d.cliente_id = <?= $cliente_id ?>;
            },
            method: 'POST',
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            async: true,
        }),
        columns: [
            { 'data': 'alias' },
            { 'data': 'att' },
            { 'data': 'email' },
            { 'data': 'direccion' },
            { 'data': 'cp' },
            { 'data': 'municipio' },
            { 'data': 'provincia' },
            { 'data': 'pais_id'  ,
                "render": function (data, type, row, meta) {
                    return row.pais;
                }},
            { 'data': 'telefono' },
            {
                data: actionBtns_add,
                className: 'row-edit dt-center'
            }
        ],
        columnDefs: [
            {
                orderable: false,
                searchable: false,
                targets: [lastColNr2]
            },
            {"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',
            text: "<?= lang('Basic.global.addNew'); ?>",
            action: function ( e, dt, node, config ) {
                $("#addressForm").attr('action','create')
                var $newAddDialog = $("#addressForm")
                $newAddDialog.modal('show')
            }
        } ]
    } );


$('#tableOfDireccionesEnvio').on( 'click', 'tbody span.edit-add', function (e) {
    
    const row = $(this).closest('tr');
    const data = tableDirecciones.row(row).data() 
    
    $("#addressForm").attr('action','edit')
    $("#addressForm").attr('row-index',row[0]._DT_RowIndex)
    
    $('#add_alias').val(data.alias)
    $('#add_att').val(data.att)
    $('#add_email').val(data.email)
    $('#add_direccion').val(data.direccion)
    $("#add_pais_id").val(data.pais_id).change()
    $('#add_municipio').val(data.municipio)
    $('#add_provincia').val(data.provincia)
    $('#add_cp').val(data.cp)
    $('#add_telefono').val(data.telefono)
    
    var $newAddDialog = $("#addressForm")
    $newAddDialog.modal('show')
})

$(document).on('click', '.btn-delete-add', function(e) {
    $(".btn-remove").attr('data-id', $(this).attr('data-id'));
    $(".btn-remove").attr('table-id', '#tableOfDireccionesEnvio');
});

function delete_direccion_envio(dataId){
    $.ajax({
        url: `/clientes/clientedirecciones/delete/${dataId}`,
        method: 'GET',
    }).done((data, textStatus, jqXHR) => {
        $('#confirm2delete').modal('toggle');
        tableDirecciones.clearPipeline();
        tableDirecciones.ajax.reload();
        popSuccessAlert(data.msg ?? jqXHR.statusText);
    }).fail((jqXHR, textStatus, errorThrown) => {
        popErrorAlert(jqXHR.responseJSON.messages.error)
    })
}

$(document).on('click', '.btn-remove', function(e) {
    
    const dataId = $(this).attr('data-id');
    const tableId = $(this).attr('table-id');
    
    if ($.isNumeric(dataId)) {
        if(tableId=='#tableOfDireccionesEnvio')
            delete_direccion_envio(dataId)            
    }
});


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


<?=$this->section('css') ?>
    <link rel="stylesheet" href="<?= site_url('themes/vuexy/css/datatables-editor/editor.bootstrap5.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-bs5/datatables.bootstrap5.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() ?>