<!doctype html>
<?php 

use Jackiedo\DotenvEditor\Facades\DotenvEditor;
$editor = DotenvEditor::load(storage_path('app/settings.env'));

?>
<html lang="en" class="h-100">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Kundenverwaltung - {{$editor->getKey('APP_TITLE')['value']}}</title>
    <link rel="icon" type="image/vnd.microsoft.icon" href="/images/bürozeit.ico">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.2/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@7.4.47/css/materialdesignicons.min.css">
    
    <!-- JQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    
<!-- Bootstrap Table -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/bootstrap-table.min.css">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/bootstrap-table.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/extensions/cookie/bootstrap-table-cookie.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/locale/bootstrap-table-de-DE.js"></script>

    <!-- Bootstrap -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>

    
    
    <link rel="stylesheet" href="{{url('/css/xeditable.css')}}">
    <!--script src="{{url('/js/bootstrap.editable.js')}}"></script -->
    <script src="{{url('/js/x-editable.js')}}"></script>
    <script src="{{url('/js/bootstrap-table.editable.js')}}"></script>
    
    <link rel="stylesheet" href="{{url('/css/bootstrap/bootstrap.dialogs.css')}}">
    <script src="{{url('/js/bootstrap.dialogs.js')}}"></script>
    
    <script src="{{url('js/hwplus.js')}}"></script>
    <link rel="stylesheet" href="{{url('css/hwplus.css')}}">

    <style>

        .form-control.search-input {
            background-color:var(--warning);
            color:var(--white);
            border-color:var(--warning);
        }

        .form-control.search-input::placeholder {
            color:var(--white);
            opacity: 1; /* Firefox */
        }

        .form-control.search-input::-ms-input-placeholder { /* Edge 12 -18 */
            color:var(--white);
        }

    </style>
    
    <script>
   
    
  function buttons () {
    return {
       btnHome: {
            html: '<button class="btn btn-warning text-white"><span class="mdi mdi-menu"></span></button>',
            attributes: {
                title: 'Sie befinden sich hier:',
                disabled:'disabled',
                style:"color:white !important; background-color:var(--warning); opacity:1"
            },
      },
      btnAdd: {
        html: '<button class="btn btn-warning text-white" onclick="add_client()"><span class="mdi mdi-plus-circle"></span> Neuer Kunde</button>',
        text: 'Neuer Kunde',
        icon: 'mdi mdi-plus-circle',
        event: function() { add_client(); },
        attributes: {
          title: 'Stammdaten eines neuen Kunden erfassen',
        }
      },
      btnDropDown:{
        text: 'Neu anlegen',
        icon: 'bi bi-file-plus',
        html: '' +
                '<button class="btn btn-warning text-white dropdown-toggle" title="selektierten Kunden bearbeiten" type="button" id="menu_button" data-toggle="dropdown" aria-expanded="false" disabled>' +
                '<i class="mdi mdi-account-circle"></i> ausgewählter Kunde' +
                '</button>' +
                '<div class="dropdown-menu">' +
                '<a class="dropdown-item" href="#" id="edit">Bearbeiten</a>' +
                '<div class="dropdown-divider"></div>'+
                '<a class="dropdown-item" href="#" id="new_offer_button">Neues Angebot</a>' +
                '<a class="dropdown-item" href="#" id="new_material_offer_button" disabled>Neues Materialangebot</a>' +
                '<a class="dropdown-item" href="#" id="new_shipping_order_button">Neuer Lieferschein</a>' +
                '<a class="dropdown-item" href="#" id="new_order_button">Neuer Auftrag</a>' +
                '<a class="dropdown-item" href="#" id="new_lot_button">Neuer Materialbedarf</a>' +
                '<a class="dropdown-item" href="#" id="new_invoice_button" disabled>Neue Rechnung</a>' +
                '<div class="dropdown-divider"></div>'+
                '<a class="dropdown-item" href="#" id="drop_client_button">Löschen</a>' +
                '</div>' +
                '',
        attributes: {
          title: 'Stammdaten erfassen'
        }
      }
    }
  }
  
  $(function() {
  
        $('.clients_table').on('check.bs.table', function(event, row, $element) {
            if(!row.fare_rate || !row._payment_term) {
                BootstrapDialog.alert({
                    title: 'Warnung',
                    message: 'Fehlende oder fehlerhafte Kundendaten. Bitte hinterlegen Sie ein gültiges Zahlungsziel und/oder eine gültige Fahrtkostenpauschale',
                    type: BootstrapDialog.TYPE_DANGER, // <-- Default value is BootstrapDialog.TYPE_PRIMARY
                    closable: true, // <-- Default value is false
                    draggable: true, // <-- Default value is false
                    buttonLabel: 'Schließen', // <-- Default value is 'OK',
                    callback: function(result) {

                    }
                });
                $('.clients_table').bootstrapTable('uncheck', $element.data('index'));
                return false;
            }
            $('#menu_button').prop("disabled",false);
        });
            
        $('.clients_table').on('uncheck.bs.table', function() {
            $('#menu_button').prop("disabled",true);
        });
  
        $('.clients_table').on('post-header.bs.table', function (e, arg1, arg2) {
            //$('.clients_table').bootstrapTable('resetView');
        })
            
        $('#drop_client_button').click(function() {
        
            let rows = $.map($('.clients_table').bootstrapTable('getSelections'), function (row) {
                return row;
            })
        
            BootstrapDialog.confirm({
                message: rows[0].descriptor + ' - soll der gewählte Kunden abschließend gelöscht werden?',
                type:BootstrapDialog.TYPE_DANGER,
                title:'gewählten Kunden löschen',
                btnCancelLabel: 'Abbrechen',
                btnOKLabel:'Löschen',
                callback: function(result) {
        
                        if(!result) return;
                        
                        let postData = {
                            _token:'{{csrf_token()}}',
                            _method: 'DELETE',
                        }
                        
                        let ids = $.map($('.clients_table').bootstrapTable('getSelections'), function (row) {
                            return row.ID
                        })
                        
                            
                        $.post("../../api/{{$repository->getConfig()->_service->url}}/86343e16c8551a46bdd6560814444580b3833a53/" + ids[0], postData)
                        
                            .done(function() {
                            
                                $('#menu_button').prop('disabled' ,true);
                            
                                $('.clients_table').bootstrapTable('remove', {
                                    field: 'ID',
                                    values: ids
                                })
                            
                            })
                            
                            .fail(function(xhr) {
                            
                                alertException(xhr);
                            });
                        
                }
            
            
            });
            
        });
  
        //$('.clients_table').on('editable-save.bs.table', function(field, row, rowIndex, oldValue, $el) {
        $('.clients_table').on('editable-save.bs.table', function ( $el, field, row, rowIndex, oldValue) {
            // ...
            
            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }


            
            postData.data[field] = row[field];

            $.post("../../api/{{$repository->getConfig()->_service->url}}/86343e16c8551a46bdd6560814444580b3833a53/" + row.ID, postData)
                
                .fail(function(xhr, status, error) {
                          
                    $('.clients_table').bootstrapTable('updateCell', {index: rowIndex, field: field, value: oldValue});
                                
                    alertException(xhr);
                    
                    
        
                });
            
            })
            
        $('#edit').on('click', function() {
        
            let ids = $.map($('.clients_table').bootstrapTable('getSelections'), function (row) {
                return row;
            })
        
            BootstrapDialog.show({
                    message: $('<div></div>').load('../edit/86343e16c8551a46bdd6560814444580b3833a53/' + ids[0].ID),
                    title: ids[0].descriptor + ' - Kunde bearbeiten',
                    type:BootstrapDialog.TYPE_LIGHT,
                    buttons: [{
                        label: 'Speichern',
                        title: 'Kunde speichen',
                        cssClass:'btn-success',
                        action: function(dialogItself){
                        
                            let postData = $('#edit_client').serialize();
                                                                                   
                            $.post("../../api/{{$repository->getConfig()->_service->url}}/86343e16c8551a46bdd6560814444580b3833a53/" + ids[0].ID, postData)
                            
                            .done(function(data) {
                            
                                $('.clients_table').bootstrapTable('updateByUniqueId', { id:ids[0].ID, row:data[0], replace:true });
                                dialogItself.close();
                            })
                            
                            .fail(function(xhr) {
                            
                                if(422 == xhr.status) {
                                    $('#edit_client').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON, function(index, item) {
                                        let array = index.split('.');
                                        $('#edit_client').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                    });
                                
                                    alertValidationError();
                                
                                } else alertException(xhr);
                            
                            });
                        
                        }
                    }, {
                        label: 'Abbrechen',
                        action: function(dialogItself){
                            dialogItself.close();
                        }
                    }]
                });
        
        })
        
        $(document).on('click', '.edit_billing_addresses', function() {
            
            let ids = $.map($('.clients_table').bootstrapTable('getSelections'), function (row) {
                return row;
            })
        
            BootstrapDialog.show({
                message: $('<div></div>').load('../e81a5165442a46ed2472910480093241b988f454/86343e16c8551a46bdd6560814444580b3833a53/' + ids[0].ID),
                title: ids[0].descriptor + ' - Übersicht Rechnungsadressen',
                type:BootstrapDialog.TYPE_LIGHT,
                size:BootstrapDialog.SIZE_WIDE
            });
        
        })


        $('#new_offer_button').on('click', function() {

            let ids = $.map($('.clients_table').bootstrapTable('getSelections'), function (row) {
                return row.ID
            })

            BootstrapDialog.show({
                    message: $('<div></div>').load('../create/afe4f16263308b092d15e04719f202efe1326813/d239e7cfd1029e141e34d4a8d724158e9032aced?data[_client]=' + ids[0]),
                    title:'Neues Angebot',
                    type:BootstrapDialog.TYPE_LIGHT,
                    buttons: [{
                        label: 'Speichern',
                        title: 'Auftrag speichen',
                        cssClass:'btn-success',
                        action: function(dialogItself){

                            let postData = $('#new_offer').serialize();

                            postData._token = '{{csrf_token()}}';

                            $.post("../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/d239e7cfd1029e141e34d4a8d724158e9032aced", postData)
                            .done(function(data) {

                                dialogItself.close();
                                window.parent.load_frame(
                                    'offers',
                                    "d774d83528528c1bb8aa3f8a18d6bd66a9c76e66/afe4f16263308b092d15e04719f202efe1326813/" + data[0].ID,
                                    true
                                );

                            })
                            .fail(function(xhr) {

                                if(422 == xhr.status) {
                                    $('#new_offer').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON, function(index, item) {
                                        let array = index.split('.');
                                        $('#new_offer').find('[name="data['+array[1]+']"]').addClass('is-invalid');
                                    });

                                    alertValidationError();

                                } else alertException(xhr);

                            });

                        }
                    }, {
                        label: 'Abbrechen',
                        action: function(dialogItself){
                            dialogItself.close();
                        }
                    }]
                });

        });


        $('#new_material_offer_button').on('click', function() {

            let ids = $.map($('.clients_table').bootstrapTable('getSelections'), function (row) {
                return row.ID
            })

            BootstrapDialog.show({
                    message: $('<div></div>').load('../create/afe4f16263308b092d15e04719f202efe1326813/d3bcca67e8f5c508feaff813de03a789feecaec8?data[_client]=' + ids[0]),
                    title:'Neues Materialangebot',
                    type:BootstrapDialog.TYPE_LIGHT,
                    buttons: [{
                        label: 'Speichern',
                        title: 'Auftrag speichen',
                        cssClass:'btn-success',
                        action: function(dialogItself){

                            let postData = $('#new_offer').serialize();

                            postData._token = '{{csrf_token()}}';

                            $.post("../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/d3bcca67e8f5c508feaff813de03a789feecaec8", postData)
                            .done(function(data) {

                                dialogItself.close();
                                window.parent.load_frame(
                                    'offers',
                                    "6d77b29c0dbef9457ebadc4a368b393434a30fb7/afe4f16263308b092d15e04719f202efe1326813/" + data[0].ID,
                                    true
                                );

                            })
                            .fail(function(xhr) {

                                if(422 == xhr.status) {
                                    $('#new_offer').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON, function(index, item) {
                                        let array = index.split('.');
                                        $('#new_offer').find('[name="data['+array[1]+']"]').addClass('is-invalid');
                                    });

                                    alertValidationError();

                                } else alertException(xhr);

                            });

                        }
                    }, {
                        label: 'Abbrechen',
                        action: function(dialogItself){
                            dialogItself.close();
                        }
                    }]
                });

        });

            
            
        $('#new_order_button').on('click', function() {
        
            let ids = $.map($('.clients_table').bootstrapTable('getSelections'), function (row) {
                return row.ID
            })
        
            BootstrapDialog.show({
                    message: $('<div></div>').load('../create/afe4f16263308b092d15e04719f202efe1326813/b1454e7841ee1d49f594494b0eaa35748029280a?data[_client]=' + ids[0]),
                    title:'Neuer Auftrag',
                    type:BootstrapDialog.TYPE_LIGHT,
                    buttons: [{
                        label: 'Speichern',
                        title: 'Auftrag speichen',
                        cssClass:'btn-success',
                        action: function(dialogItself){
                        
                            let postData = $('#new_order').serialize();
                        
                            postData._token = '{{csrf_token()}}';
                                                       
                            $.post("../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/b1454e7841ee1d49f594494b0eaa35748029280a", postData)
                            .done(function(data) {

                                dialogItself.close();
                                window.parent.load_frame(
                                    'open_tickets',
                                    "0ff1bb77a9de65eac6621c9c5a983da7a37ed3bf/afe4f16263308b092d15e04719f202efe1326813/" + data[0].ID,
                                    true
                                );

                            })
                            .fail(function(xhr) {
                            
                                if(422 == xhr.status) {
                                    $('#new_order').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON, function(index, item) {
                                        let array = index.split('.');
                                        $('#new_order').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                    });

                                    alertValidationError();
                                
                                } else alertException(xhr);
                            
                            });
                        
                        }
                    }, {
                        label: 'Abbrechen',
                        action: function(dialogItself){
                            dialogItself.close();
                        }
                    }]
                });
        
        });
        
        $('#new_shipping_order_button').on('click', function() {
        
            let ids = $.map($('.clients_table').bootstrapTable('getSelections'), function (row) {
                return row.ID
            })
        
            BootstrapDialog.show({
                    message: $('<div></div>').load('../create/afe4f16263308b092d15e04719f202efe1326813/b47ffbb6d10b344b0ad4e1f1bf5526e246b917ce?data[_client]=' + ids[0]),
                    title:'Neuer Lieferschein',
                    type:BootstrapDialog.TYPE_LIGHT,
                    buttons: [{
                        label: 'Speichern',
                        cssClass:'btn-success',
                        action: function(dialogItself) {
                        
                            let postData = $('#new_shipping_order').serialize();
                        
                            postData._token = '{{csrf_token()}}';
                            
                            
                            
                            $.post("../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/b47ffbb6d10b344b0ad4e1f1bf5526e246b917ce", postData)
                            .done(function(data) {

                                dialogItself.close();
                                window.parent.load_frame(
                                    'open_tickets',
                                    "0ff1bb77a9de65eac6621c9c5a983da7a37ed3bf/afe4f16263308b092d15e04719f202efe1326813/" + data[0].ID,
                                    true
                                );

                            })
                            .fail(function(xhr) {
                                
                                if(422 == xhr.status) {
                                    $('#new_shipping_order').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON, function(index, item) {
                                        let array = index.split('.');
                                        $('#new_shipping_order').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                    
                                    });

                                    alertValidationError();
                                
                                } else alertException(xhr);
                            
                            });
                        
                        }
                    }, {
                        label: 'Abbrechen',
                        action: function(dialogItself){
                            dialogItself.close();
                        }
                    }]
                });
        
        });
        
        $('#new_lot_button').on('click', function() {
        
            let ids = $.map($('.clients_table').bootstrapTable('getSelections'), function (row) {
                return row.ID
            })
        
            BootstrapDialog.show({
                    message: $('<div></div>').load('../create/afe4f16263308b092d15e04719f202efe1326813/e394996c8ffecef4efa6840e207181ee6bdf85d2?data[_client]=' + ids[0]),
                    title:'Neue Baustelle',
                    type:BootstrapDialog.TYPE_LIGHT,
                    buttons: [{
                        label: 'Speichern',
                        cssClass:'btn-success',
                        action: function(dialogItself){
                        
                            let postData = $('#new_lot').serialize();
                            
                            $.post("../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/e394996c8ffecef4efa6840e207181ee6bdf85d2", postData)
                            .done(function(data) {

                                dialogItself.close();
                                window.parent.load_frame(
                                    'open_tickets',
                                    "0ff1bb77a9de65eac6621c9c5a983da7a37ed3bf/afe4f16263308b092d15e04719f202efe1326813/" + data[0].ID,
                                    true
                                );


                            })
                            .fail(function(xhr) {
                                
                                if(422 == xhr.status) {
                                    $('#new_lot').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON, function(index, item) {
                                        let array = index.split('.');
                                        $('#new_lot').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                    
                                    });
                                
                                    alertValidationError();
                                
                                } else alertException(xhr);
                            
                            });
                        
                        }
                    }, {
                        label: 'Abbrechen',
                        action: function(dialogItself){
                            dialogItself.close();
                        }
                    }]
                });
        
        });

        $('#new_invoice_button').on('click', function() {

            let ids = $.map($('.clients_table').bootstrapTable('getSelections'), function (row) {
                return row.ID
            })

            BootstrapDialog.show({
                    message: $('<div></div>').load('../d28b4963e94b6c13de73de367eee276d73039493/86343e16c8551a46bdd6560814444580b3833a53/' + ids[0]),
                    title:'Neue Rechnung',
                    type:BootstrapDialog.TYPE_LIGHT,
                    buttons: [{
                        label: 'Speichern',
                        cssClass:'btn-success',
                        action: function(dialogItself) {

                            var option = $('#new_invoice [name="recipient"]:checked').val();

                                switch(option) {

                                    case "new":

                                        dialogItself.close();

                                        dialog = BootstrapDialog.show({
                                            message: $('<div></div>').load('../bee81541cb1e85aa6f48a7ec8f590b5e2a4b0c28/86343e16c8551a46bdd6560814444580b3833a53/' + ids[0]),
                                            title:'Neue Rechnung - Rechnungsadresse erfassen',
                                            type:BootstrapDialog.TYPE_LIGHT,
                                            buttons: [{
                                                label: 'Speichern',
                                                cssClass:'btn-success',
                                                action: function(dialogItself) {

                                                    $('#spinner').removeClass('d-none');

                                                    let postData = $('#new_recipient').serialize();
                                                        postData._token = '{{csrf_token()}}';

                                                    $.post("/api/hwplus/86343e16c8551a46bdd6560814444580b3833a53/bee81541cb1e85aa6f48a7ec8f590b5e2a4b0c28", postData)

                                                        .done(function(data) {

                                                            postData  += "&data%5Bdescriptor%5D=Rechnung";
                                                            postData  += "&data%5Bcustomer_id%5D=" + data[0].customer_id;
                                                            //postData  += "&data%5Bdate%5D=" + encodeURIComponent(date);
                                                            postData += "&data%5Bclient%5D=" + encodeURIComponent(data[0].descriptor);
                                                            postData += "&data%5B_client%5D=" + encodeURIComponent(data[0].ID);

                                                            $.post("/api/hwplus/27b96af59ee924f9ec98cf9c44b54e06219636c1/5dfe19c87715ed4ca89abb9f4eb4da4dc060c8bd", postData)

                                                                .done(function(data) {
                                                                    $('#spinner').addClass('d-none');

                                                                    window.parent.load_frame(
                                                                        'invoices',
                                                                        "2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/" + data[0].ID,
                                                                        true
                                                                    );

                                                                    dialog.close();
                                                                })

                                                                .fail(function(xhr){

                                                                    alertException(xhr);

                                                                });

                                                        })

                                                        .fail(function(xhr, status, error) {

                                                            $('#spinner').addClass('d-none');

                                                            if(422 == xhr.status) {

                                                                $('#new_recipient').find('.is-invalid').removeClass('is-invalid');
                                                                $.each(xhr.responseJSON, function(index, item) {
                                                                    let array = index.split('.');
                                                                    $('#new_recipient').find('[name="data['+array[1]+']"]').addClass('is-invalid');
                                                                });

                                                                alertValidationError();

                                                            }

                                                            else alertException(xhr);

                                                        });
                                                }
                                            }]
                                        });


                                        break;


                                    case "": alert('Fehler! Keine Auswahl getroffen');
                                        break;



                                    default:
                                        $.get("/api/hwplus/86343e16c8551a46bdd6560814444580b3833a53/" + option)

                                            .done(function(data) {

                                                let cdata = {};
                                                    cdata.data = {};
                                                $.each(data, function(index, value) { cdata["data"][index] = value; })


                                                postData = $.param(cdata);
                                                postData  += "&data%5Bdescriptor%5D=Rechnung";
                                                postData  += "&data%5Bcustomer_id%5D=" + data.customer_id;
                                                //postData  += "&data%5Bdate%5D=" + encodeURIComponent(date);
                                                postData += "&data%5Bclient%5D=" + encodeURIComponent(data.descriptor);
                                                postData += "&data%5B_client%5D=" + encodeURIComponent(data.ID);

                                                $.post("/api/hwplus/27b96af59ee924f9ec98cf9c44b54e06219636c1/5dfe19c87715ed4ca89abb9f4eb4da4dc060c8bd", postData)

                                                    .done(function(data) {

                                                        window.parent.load_frame(
                                                            'invoices',
                                                            "2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/" + data[0].ID,
                                                            true
                                                        );

                                                        $('#spinner').addClass('d-none');
                                                        dialog.close();
                                                    })

                                                .fail(function(xhr) {

                                                    alertException(xhr);

                                            });

                                            })
                                            .fail(function(xhr) {
                                                $('#spinner').addClass('d-none');
                                                alertException(xhr);

                                            });



                                            break;

                                }




                        }
                    }, {
                        label: 'Abbrechen',
                        action: function(dialogItself){
                            dialogItself.close();
                        }
                    }]
                });

        });

                 
    });


    function add_client() {
            BootstrapDialog.show({
                message: $('<div></div>').load('../c65ddeca3e4ae821f3e47737e9911280b27a2e9b'),
                title:'Neuer Kunde - Stammdaten erfassen',
                type: BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Speichern',
                    title: 'Neuer Kunde - Stammdaten speichern',
                    cssClass: 'btn-success',
                    action: function(dialogItself){

                        let postData = $('#new_client').serialize();

                        postData._token = '{{csrf_token()}}';

                        $.post("../../api/{{$repository->getConfig()->_service->url}}/86343e16c8551a46bdd6560814444580b3833a53/c65ddeca3e4ae821f3e47737e9911280b27a2e9b", postData)

                        .done(function(data) {

                            data[0].open_tickets = '<a href="#" class="btn btn-sm btn-warning" onclick="showOpenTickets(\''+data[0].ID+'\')">0</a>';
                            data[0].closed_tickets = '<a href="#" class="btn btn-sm btn-warning" onclick="showPrintedTickets(\''+data[0].ID+'\')">0</a>';
                            data[0].invoices = '<a href="#" class="btn btn-sm btn-warning" onclick="showInvoices(\''+data[0].ID+'\')">0</a>';
                            data[0].edit = '<button title="Kunde bearbeiten" onclick="show_details(\''+data[0].ID+'\')" class="btn btn-sm btn-warning"><i class="bi bi-pencil-square"></i></button>';
                            $('.clients_table').bootstrapTable('prepend', data);

                            dialogItself.close();
                        })

                        .fail(function(xhr, status, error) {


                            if(422 == xhr.status) {
                                $('#new_client').find('.is-invalid').removeClass('is-invalid');
                                $.each(xhr.responseJSON, function(index, item) {
                                    let array = index.split('.');
                                    $('#new_client').find('[name="data['+array[1]+']"]').addClass('is-invalid');
                                });

                                alertValidationError();

                            }

                            else alertException(xhr);

                        });

                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        }

    
    function show_details(id) {
    
        let row  =$('.clients_table').bootstrapTable('getRowByUniqueId', id);
        
       
        dialog = BootstrapDialog.show({
            message: $('<div></div>').load('../edit/86343e16c8551a46bdd6560814444580b3833a53/' + id),
            title: row.descriptor + ' - Kunde bearbeiten',
            type:BootstrapDialog.TYPE_LIGHT,
            buttons: [{
                label: 'Speichern',
                title: 'Kunde speichen',
                cssClass:'btn-success',
                action: function(dialogItself){
                
                    let postData = $('#edit_client').serialize();
                                                                            
                    $.post("../../api/{{$repository->getConfig()->_service->url}}/86343e16c8551a46bdd6560814444580b3833a53/" + id, postData)
                    .done(function(data) {
                        //$('.clients_table').bootstrapTable('updateByUniqueId', { id:id, row:data[0], replace:true });
                        dialogItself.close();
                    })
                    .fail(function(xhr) {
                    
                        if(422 == xhr.status) {
                            $('#edit_client').find('.is-invalid').removeClass('is-invalid');
                            $.each(xhr.responseJSON, function(index, item) {
                                let array = index.split('.');
                                $('#edit_client').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                            });

                            alertValidationError();
                        
                        
                        } else alertException(xhr);
                    
                    });
                
                }
            }, {
                label: 'Abbrechen',
                action: function(dialogItself){
                    dialogItself.close();
                }
            }]
        });
    
    }
    
    function showPrintedTickets(id) {
    
        let row  =$('.clients_table').bootstrapTable('getRowByUniqueId', id);
        
        BootstrapDialog.show({
            title: row.descriptor + ' - abgeschlossene Aufträge',
            size: BootstrapDialog.SIZE_WIDE,
            type:BootstrapDialog.TYPE_LIGHT,
            message: $('<div></div>').load('../7205611ef37b0d95b81adf670a7b397b5d6cabdb/afe4f16263308b092d15e04719f202efe1326813?filter[_client]='+ id + '&filter[printed]=1')
        });
    }
    
    function showOpenTickets(id) {
    
        let row  =$('.clients_table').bootstrapTable('getRowByUniqueId', id);
        
        BootstrapDialog.show({
            title: row.descriptor + ' - offene Aufträge',
            size: BootstrapDialog.SIZE_WIDE,
            type:BootstrapDialog.TYPE_LIGHT,
            message: $('<div></div>').load('../7205611ef37b0d95b81adf670a7b397b5d6cabdb/afe4f16263308b092d15e04719f202efe1326813?filter[_client]='+ id + '&filter[printed]=0')
        });
    }
    
    function showInvoices(id) {
    
        let row  = $('.clients_table').bootstrapTable('getRowByUniqueId', id);
        
        BootstrapDialog.show({
            title:row.descriptor + ' - Rechnungen',
            size: BootstrapDialog.SIZE_WIDE,
            type:BootstrapDialog.TYPE_LIGHT,
            message: $('<div></div>').load('../6670856ff71477f7645e5b011077e72825f10f18/27b96af59ee924f9ec98cf9c44b54e06219636c1?filter[_client]='+ id)
        });
    }
    
    function checkPaymentTerm(element, model, term, client) {
    
    
        $('#spinner').removeClass('d-none');
    
        let postData = {
            _token:'{{csrf_token()}}',
            data: {
                _row : model,
                _backlinked : term
            },
        }
                        
            
                                        
        $.post("../../api/{{$repository->getConfig()->_service->url}}/d364545c01e4f0cc5abbb1cda02be1411923fbfb/1b0643cf2e50e004c0fce117cf18d1609b41e6cd", postData)
            .done(function(data) { 
                
                dialog.getModalBody().load('../edit/86343e16c8551a46bdd6560814444580b3833a53/' + client, function() { $('#spinner').addClass('d-none'); });
             
            })
            .fail(function(xhr) {
            
                $(element).prop( "checked", false );
            });
    
    }
    
    function uncheckPaymentTerm(element, pivot, client) {
    
    
        $('#spinner').removeClass('d-none');
    
        let postData = {
            _token:'{{csrf_token()}}',
            _method: 'DELETE',
        }
        
       
                
        $.post("../../api/{{$repository->getConfig()->_service->url}}/d364545c01e4f0cc5abbb1cda02be1411923fbfb/" + pivot, postData)
        
            .done(function(data) {
                
                    dialog.getModalBody().load('../edit/86343e16c8551a46bdd6560814444580b3833a53/' + client, function() { $('#spinner').addClass('d-none'); });
            
            })
            
            .fail(function(xhr) {
            
                $(element).prop( "checked", true );
            });
    }
    
    
  
</script>
    
  </head>
  <body class="bg-transparent">

    <div id="spinner" class="spinner spinner-border d-none" role="status">
        <span class="sr-only">Loading...</span>
    </div>



    <div class="container pt-3 bg-white border-left border-right border-warning">


        <nav class="navbar navbar-expand-lg navbar-light bg-warning text-white">
            <a class="navbar-brand text-white" href="#"><i class="mdi mdi-account-group"></i> Kundenstamm</a>
        </nav>


        <table
            class="clients_table"
            data-url="../hwplus_clients_index"
            data-pagination="true"
            data-page-list="10,25,50,100,all"
            data-toggle="table" 
            __data-side-pagination="server"
            data-search="true"
            data-show-search-clear-button="true"
            data-buttons="buttons"
            data-cookie="true"
            data-cookie-id-table="frame_clients_index"
            data-cookie-storage="localStorage"
            data-sort-name="customer_id"
            data-click-to-select="true" 
            data-single-select="true"
            data-buttons-align="left"
            data-buttons-class="warning text-white"
            data-show-button-text="false"
            data-row-style="row_style"
            data-unique-id="ID">
            <thead >
                <tr>

                <th data-field="ID" data-visible="false"></th>
                <th data-field="streetadress" data-visible="false"></th>
                <th data-field="email" data-visible="false"></th>
                <th data-field="phone_business" data-visible="false"></th>
                <th data-field="phone_mobile" data-visible="false"></th>

                <th data-field="select" data-checkbox="true"></th>
                <th data-field="customer_id" class="font-weight-bold" data-sortable="true" data-editable="true" data-editable-mode="inline" data-editable-type="text" data-editable-emptytext ="...">Kd-Nr.</th>
                <th data-field="descriptor" data-sortable="true" data-editable="true" data-editable-mode="inline" data-editable-type="text" data-editable-emptytext ="..." data-editable-escape="false">Firma/Name</th>
                <th data-field="firstname" class="" data-sortable="true" data-editable="true" data-editable-mode="inline" data-editable-type="text" data-editable-emptytext ="...">Vorname</th>
                <th data-field="surname"  class="" data-sortable="true" data-editable="true" data-editable-mode="inline" data-editable-type="text" data-editable-emptytext ="...">Nachname</th>
                <th data-field="postcode"  class="" data-sortable="true" data-editable="true" data-editable-mode="inline" data-editable-type="text" data-editable-emptytext ="...">PLZ</th>
                <th data-field="location"  class="" data-sortable="true" data-editable="true" data-editable-mode="inline" data-editable-type="text" data-editable-emptytext ="...">Ort</th>
                <th data-field="open_tickets" class="smaller" data-align="center" data-formatter="open_tickets_formatter"><small>offene<br>Aufträge</small></th>
                <th data-field="closed_tickets"  class="smaller" data-align="center" data-formatter="closed_tickets_formatter"><small>fertige<br>Aufträge</small></th>
                <th data-field="num_invoices"  class="" data-align="center" data-formatter="num_invoices_formatter"><small>RG</small></th>
                <th data-field="edit"  class="smaller" data-align="center" data-formatter="row_edit_formatter"><small>Bearbeiten</small></th>
            </thead>
        </table>
    </div>
  </body>
  <script>

  window.open_tickets_formatter = (value, row) => {
    return  `<a href="#" class="btn btn-sm ` + (value ? "btn-danger" : "btn-warning") + ` text-white" title="Es liegen ` + value+ ` offene Aufträge vor" onclick="showOpenTickets('` + row.ID + `')">` + value + `</a>`;
  }

  window.closed_tickets_formatter = (value, row) => {
    return  `<a href="#" class="btn btn-sm btn-warning text-white" title="Es liegen ` + value+ ` abgeschlossene Aufträge vor" onclick="showPrintedTickets('` + row.ID + `')">` + value + `</a>`;
  }


  window.num_invoices_formatter = (value, row) => {
    return  `<a href="#" class="btn btn-sm btn-warning text-white" title="Es liegen ` + value+ ` Rechnungen vor" onclick="showInvoices('` + row.ID + `')">` + value + `</a>`;
  }

  window.row_edit_formatter = (value, row) => {
    return  `<button title="Kunde bearbeiten" onclick="show_details('` + row.ID + `')" class="btn btn-sm btn-warning text-white"><i class="bi bi-pencil-square"></i></button>`;
  }

  function row_style(row, index) {

        if (!(row._payment_term)) {
            return {
                css: {
                    'background-color': 'red',
                    'color':'white'
                }
            }
        } else return {};
  }
  
  </script>
</html>
