<!doctype html>
<?php 

use Jackiedo\DotenvEditor\Facades\DotenvEditor;


$MAIL_HOST = DotenvEditor::load(base_path('.env'))->getValue('MAIL_HOST');
$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">
    <title>Rechnungswesen - {{$editor->getKey('APP_TITLE')['value']}}</title>
    <link rel="icon" type="image/vnd.microsoft.icon" href="/images/bürozeit.ico">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <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>
    
    <!-- Latest compiled and minified CSS -->
    <!--link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.21.1/dist/bootstrap-table.min.css"-->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/bootstrap-table.min.css">

    <!-- Latest compiled and minified JavaScript -->
    <!--script src="https://unpkg.com/bootstrap-table@1.21.1/dist/bootstrap-table.min.js"></script-->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/bootstrap-table.min.js"></script>
    <!--script src="{{url('/js/bootstrap-table.js')}}"></script -->
    <!-- Latest compiled and minified Locales -->
    <!--script src="https://unpkg.com/bootstrap-table@1.21.1/dist/locale/bootstrap-table-de-DE.min.js"></script-->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/locale/bootstrap-table-de-DE.js"></script>
    
    
    <!--link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.21.1/dist/extensions/reorder-rows/bootstrap-table-reorder-rows.css"-->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/extensions/reorder-rows/bootstrap-table-reorder-rows.css">
    <!--script src="https://cdnjs.cloudflare.com/ajax/libs/TableDnD/1.0.5/jquery.tablednd.js"></script -->
    <script src="https://cdn.jsdelivr.net/gh/isocra/TableDnD@1.0.5/dist/jquery.tablednd.1.0.5.js"></script>
    <!--script src="https://unpkg.com/bootstrap-table@1.21.1/dist/extensions/reorder-rows/bootstrap-table-reorder-rows.js"></script-->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-table@1.21.1/dist/extensions/reorder-rows/bootstrap-table-reorder-rows.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>
    
    <!-- Bootstrap editable -->
    <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>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.0.0/moment.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
    <link rel="stylesheet" href="{{url('/css/bootstrap/bootstrap.dialogs.css')}}">
    <script src="{{url('/js/bootstrap.dialogs.js')}}"></script>
    
    <!-- Tabulator -->

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tabulator-tables@5.4.3/dist/css/tabulator.min.css">
    <script src="https://cdn.jsdelivr.net/npm/tabulator-tables@5.4.3/dist/js/tabulator.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tabulator-tables@5.4.3/dist/css/tabulator_bootstrap5.min.css">

    <!-- Fancytree -->
    <script src="https://cdn.jsdelivr.net/npm/jquery.fancytree@2.38.2/dist/jquery.fancytree-all-deps.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/jquery.fancytree@2.38.2/dist/skin-win8/ui.fancytree.min.css" rel="stylesheet">
    
    <script src="https://cdn.jsdelivr.net/npm/luxon@3.2.1/build/global/luxon.min.js"></script>

    <script src=" https://cdn.jsdelivr.net/npm/numeral@2.0.6/numeral.min.js "></script>
    

    <script src="{{url('js/hwplus.js?1')}}"></script>
    <link rel="stylesheet" href="{{url('css/hwplus.css')}}">
    
    <style type="text/css">


        ul.fancytree-container, span.fancytree-title {
            font-size: inherit;
            font-family:inherit;
        }

        ul.fancytree-container {
            border: none;
        }



    </style>
   
    <script>


    let listVat = @json(\Runtime::make('hwplus_vat_rates')->get()->keyBy('ID'));

   
   var netCalc = function(values, data, calcParams) {
        //values - array of column values
        //data - all table data
        //calcParams - params passed from the column definition object

        var calc = 0;

        values.forEach(function(value){
            value = parseFloat(value.replace(',','.'));
            calc = calc + value;
        });

        return calc.toFixed(2) + '€';
    }
    
    var sumCalc = function(values, data, calcParams) {
        //values - array of column values
        //data - all table data
        //calcParams - params passed from the column definition object

        var calc = 0;

        values.forEach(function(value){
            value = parseFloat(value);
            calc = calc + value;
        });

        return calc.toFixed(2) + '€';
    }
    
    var editAble = function(cell){
        return {{$model->flag_finished ? "false" : "true"}}
    }

    function preview_header() {

            BootstrapDialog.show({
                message: $('<div></div>').load('../../2304208b02b9ccdacb87eb0f26f2369180dbb869/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}'),
                title:'Vorschau Kopfzeile',
                buttons: [{
                    label: 'Schließen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });

        }
    
  
    $(function() {
    

    
        setInterval(function() {
            
            // Zwischensumme 1

            let sum1 = 0;

            let fares = 0;
            let aes = 0;
            let services = 0;

            let b_fares = 0;
            let b_aes = 0;
            let b_services = 0;

            if($('#fareTable div.tabulator-footer [tabulator-field="sum"]').length ) {
                fares = $('#fareTable div.tabulator-footer [tabulator-field="sum"]').html();
                fares = parseFloat(fares.slice(0, -1));
                b_fares = $('#fareTable div.tabulator-footer [tabulator-field="brutto"]').html();
                b_fares = parseFloat(b_fares.slice(0, -1));
            }
            if($('#aeTable div.tabulator-footer [tabulator-field="sum"]').length ) {
                aes = $('#aeTable div.tabulator-footer [tabulator-field="sum"]').html();
                aes = parseFloat(aes.slice(0, -1));
                b_aes = $('#aeTable div.tabulator-footer [tabulator-field="brutto"]').html();
                b_aes = parseFloat(b_aes.slice(0, -1));
            }
            if($('#serviceTable div.tabulator-footer [tabulator-field="sum"]').length ) {
                serivces = $('#serviceTable div.tabulator-footer [tabulator-field="sum"]').html();
                services = parseFloat(serivces.slice(0, -1));
                b_services = $('#serviceTable div.tabulator-footer [tabulator-field="brutto"]').html();
                b_services = parseFloat(b_services.slice(0, -1));
            }

            sum1 = fares + aes + services;
            b_sum1 = b_fares + b_aes + b_services;

            $('.sum1').html('Zwischensumme netto: ' + sum1.toFixed(2) + '€');
            $('.sum1').data('sum1', sum1);
            $('.sum1').data('b_sum1', b_sum1);

            //alert('sum1: ' + b_sum1);

            // Zwischensumme 2

            let sum2 = sum1;
            let b_sum2 = b_sum1;
            let selection = {};
            let row = {};

            if(typeof premiumChargeTable !== 'undefined' && premiumChargeTable.getSelectedData().length) {

                selection = premiumChargeTable.getSelectedData()[0];
                row = premiumChargeTable.getSelectedRows()[0];

                if(selection.unit == "%") {

                    let im = sum2 / 100 * parseFloat(selection.value);
                    row.update({sum:sum2})
                    sum2 = sum2 + im;
                    b_sum2 = b_sum2 + parseFloat(selection.brutto);
                }
                else {
                    row.update({sum:parseFloat(selection.value)});
                    sum2 = sum2 + parseFloat(selection.value);
                    b_sum2 = b_sum2 + parseFloat(selection.brutto);
                }

            }

            $('.sum2').html('Zwischensumme netto: ' + sum2.toFixed(2) + '€');
            $('.sum2').data('sum2', sum2);
            $('.sum2').data('b_sum2', sum2);

            // Gesamtsumme inkl. Material

            let material = $('#invoiceTable div.tabulator-footer [tabulator-field="sum"]').html();
            let b_material = $('#invoiceTable div.tabulator-footer [tabulator-field="brutto"]').html();

            let misc = $('#miscTable div.tabulator-footer [tabulator-field="sum"]').html();
            let b_misc = $('#miscTable div.tabulator-footer [tabulator-field="brutto"]').html();

            material = parseFloat(material.slice(0, -1));
            b_material = parseFloat(b_material.slice(0, -1));

            misc = parseFloat(misc.slice(0, -1));
            b_misc = parseFloat(b_misc.slice(0, -1));

            let netto = sum2 + material + misc;
            let brutto = b_sum2 + b_material + b_misc;

            //alert('brutto: ' + brutto);

            $('.netto').html('Gesamt netto: ' + netto.toFixed(2) + '€');
            $('.brutto').html('Gesamt brutto: ' + (brutto.toFixed(2)) + '€');

            }, 500);
    
        @php
        $data = \App\Models\PHPXPress\HwplusInvoiceItems::with('_meta._doctype')->whereHas('_meta._doctype', function($query) { 
            $query->where('ID', '050b070c151f8f0b9d76589922f58a908e67535f');
        })->where('_items_at_hwplus_invoices', $model->getKey())->get();
        @endphp
    
        let fareTableData = @json($data); 

        fareTable = new Tabulator("#fareTable", {
            movableRows:editAble(),
            layout:"fitColumns",
            selectable: editAble(),
            rowHeight:100,
            data:fareTableData,
            index: "ID",
            initialSort:[{column:'sort_order', dir:'asc'}],
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:10},
                {rowHandle:true, formatter:"handle", headerSort:false, width:10, vertAlign:'top'},
                {title:"", field:'sort_order', visible:true, sorter:'number', width:10},
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"textarea", editable:editAble, formatter:"textarea", editorParams:             {
                    selectContents:true,
                }},
                {title:'Einheit', field:'unit', visible:true, editor:'list', editable:editAble, width:100,
                    editorParams: {
                        values:[@foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) {value:'{{$row->descriptor}}', label:"{{$row->descriptor}}"},@endforeach],
                        clearable:true,
                    },
                    formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) '{{$row->descriptor}}':'{{$row->descriptor}}',@endforeach
                    }

                },
                {title:'Menge', field:'amount', visible:true, width:100, editor:'input', mutateLink:"brutto", editable:editAble, mutateLink:"sum", editorParams: {
                    selectContents:true
                }, formatter:function(cell, formatterParams, onRendered) {
                    return formatAmount(cell.getValue());
                }, editorParams:{
                    elementAttributes:{
                        oninput:"validateAmount(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'Einzelpreis', field:'netprice', visible:true, width:100, editor:'input', editable:editAble, __bottomCalc:netCalc, formatter: function(cell) {
                    return formatPrice(cell.getValue());
                }, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }, editorParams:{
                    elementAttributes:{
                        oninput:"validatePrice(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'MwSt.', field:'vat', visible:true, width:90, editor:'list', editable:editAble, formatter: function(cell) { return cell.getValue() + '%'}, editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->rate}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->rate}}':'{{$row->descriptor}}',@endforeach
                    }


                },
                {title:'Netto', field:'sum', visible:true, width:120, bottomCalc:sumCalc, mutateLink:'brutto',
                    mutator: function(value, row) {
                        let sum = parseFloat(row.netprice.replace(',','.')) * parseFloat(row.amount.replace(',','.'));
                        return sum.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}},
                {title:'Brutto', field:'brutto', visible:false, width:120, bottomCalc:sumCalc,
                    mutator: function(value, row) {
                        let brutto =  parseFloat(row.sum) + parseFloat(row.vat.replace(',','.')) * parseFloat(row.sum) / 100;
                        return brutto.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}},
            ],
        });
    
        fareTable.on("rowSelected", function(row){
            $('.fare_menu_button').prop("disabled",false);
        });
        
        fareTable.on("rowDeselected", function(row){
            $('.fare_menu_button').prop("disabled",true);
        });
        

        fareTable.on("cellEdited", function(cell){

                let field = cell.getField();
                if(jQuery.inArray(field, ['brutto', 'sum']) !== -1) return;

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

                let postData = {
                    _token:'{{csrf_token()}}',
                    _method: 'PUT',
                    data: {}
                }

                let row = cell.getRow().getData();

                postData.data[cell.getField()] = cell.getValue();

                $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/" + row.ID, postData)

                    .done(function() {

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

                    })

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

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

                        alertException(xhr);



                    });
        });
        
        $('.add_fare').on('click', function() {
        
  
            BootstrapDialog.show({
                message: $('<div></div>').load('../../create/8d9c8b3182023463c3470b19e7b4dad2511868cc/050b070c151f8f0b9d76589922f58a908e67535f?data[_items_at_hwplus_invoices]={{$model->getKey()}}'),
                title:'Rechnungsposition erfassen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Speichern',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        let postData = $('#new_invoice_item').serialize();
                                        
                        $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/050b070c151f8f0b9d76589922f58a908e67535f", postData)
                        
                        .done(function(data) { 
                        
                            $('#spinner').addClass('d-none');
                            fareTable.addData(data);
                            dialogItself.close(); 
                        
                        })
                            
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            if(422 == xhr.status) {
                                
                                    $('#new_invoice_item').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON, function(index, item) {
                                        let array = index.split('.');
                                        $('#new_invoice_item').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                    });
                                
                                    return;
                                
                            }
                        
                            alertException(xhr);
                        
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
    
        })
        
        $('.add_fare_charge').on('click', function() {

            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../851aa2a23b963f46836ee9dc67571ad111b6848d/baab2d50701592cb784913b0e3d4deb7e9d57ab7?data[invoice]={{$model->getKey()}}'),
                title:'Fahrtkosten hinzufügen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });

        })
        
        
        $('.drop_fare_button').click(function() {
            
            BootstrapDialog.confirm('Rechnungsposition löschen bestätigen?', function(result){
                if(result) {
                
                    $('#spinner').removeClass('d-none');
                    
                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }
                    
                    let selectedRowID = fareTable.getSelectedData()[0].ID;
                                            
                    $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/" + selectedRowID, postData)
                    
                        .done(function() {
                                        
                            $('#spinner').addClass('d-none');            
                            
                            fareTable.deleteRow(selectedRowID);
                        
                        })
                        
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            alertException(xhr);
                        });
                    $('.fare_menu_button').prop('disabled', true);
                }
            });
        
        
        })
        
        
        
        invoiceTextTable = new Tabulator("#invoiceTextTable", {
            movableRows:true,
            layout:"fitColumns",
            selectable: 1,
            rowHeight:100,
            data:@json(\App\Models\PHPXPress\HwplusInvoiceNotes::where('_notes_at_hwplus_invoices', $model->getKey())->get()),
            initialSort:[{column:'sort', dir:'asc'}],
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:10},
                {rowHandle:true, formatter:"handle", headerSort:false, width:10, vertAlign:'top'},
                {title:"", field:'sort', visible:true, sorter:'number', width:10},
                {title:'Text', field:'text', visible:true, editor:'textarea', formatter:"textarea" },
            ],
        });
        
        
        
        
        invoiceTextTable.on("rowSelected", function(row){
            $('#invoice_text_menu_button').prop("disabled",false);
        });
        
        invoiceTextTable.on("rowDeselected", function(row){
            $('#invoice_text_menu_button').prop("disabled",true);
        });
        
        invoiceTextTable.on("rowMoved", function(row) {
        
                $('#spinner').removeClass('d-none');
        
                let postData = {
                    _token:'{{csrf_token()}}',
                    _method: 'PUT',
                    data: {}
                }
                
                postData.data['_notes_at_hwplus_invoices_order'] = row.getPosition();        
                
                $.post("../../../api/{{$repository->getConfig()->_service->url}}/89157a15b3ce224a6dbcffe3e2d3461e319319a6/" + row.getData().ID, postData)
                    
                    .done(function(data) {
                                
                        invoiceTextTable.setData("../../../api/{{$repository->getConfig()->_service->url}}/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}/_notes");

                        $('#spinner').addClass('d-none');
                        
                    })
                    
                    .fail(function(xhr) {
                    
                        $('#spinner').addClass('d-none');
                    
                        alertException(xhr);    
                    });
            
        
        });
    
    
        invoiceTextTable.on("cellEdited", function(cell){
                        
                $('#spinner').removeClass('d-none');
                
                let postData = {
                    _token:'{{csrf_token()}}',
                    _method: 'PUT',
                    data: {}
                }
                
                let row = cell.getRow().getData();
            
                postData.data[cell.getField()] = cell.getValue();
                
                $.post("../../../api/{{$repository->getConfig()->_service->url}}/89157a15b3ce224a6dbcffe3e2d3461e319319a6/" + row.ID, postData)
                    
                    .done(function() {
                    
                        $('#spinner').addClass('d-none');
                    
                    })
                    
                    .fail(function(xhr, status, error) {
                            
                        $('#spinner').addClass('d-none');
                        cell.restoreOldValue();
                                    
                        alertException(xhr);
                        
                        
            
                    });
        });
        
        $('#drop_invoice_text_button').click(function() {
        
                      
            dialog = BootstrapDialog.confirm('Rechnungstext löschen bestätigen?', function(result){
                if(result) {
                
                    $('#spinner').removeClass('d-none');
                    
                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }
                    
                    let selectedRowID = invoiceTextTable.getSelectedData()[0].ID;
                                            
                    $.post("../../../api/{{$repository->getConfig()->_service->url}}/89157a15b3ce224a6dbcffe3e2d3461e319319a6/" + selectedRowID, postData)
                    
                        .done(function() {
                                                
                            $('#spinner').addClass('d-none');
                            
                            invoiceTextTable.getSelectedRows()[0].delete();
                        
                        })
                        
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            alertException(xhr);
                        });
                    
                    $('#manhour_menu_button').prop('disabled', true);
                }
            });
        
        
        })
        
        $('#add_invoice_text').on('click', function() {
        
  
            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../9ae4379e916a6a802c876f27dd76d988d43df31b/84b692d8b9ce096bca28327be5fe9ac581bba7a2?data[_notes_at_hwplus_invoices]={{$model->getKey()}}'),
                title:'Rechnungstext hinzufügen',
            });
    
        })
        
        
        
        
        
        
        
        
        
        @php
        $data = \App\Models\PHPXPress\HwplusInvoiceItems::with('_meta._doctype')->whereHas('_meta._doctype', function($query) { 
            $query->where('ID', 'cba3def15e0e6c1151fe202c8b00c2a0c1951909');
        })->where('_items_at_hwplus_invoices', $model->getKey())->get();
        @endphp
    
        let aeTableData = @json($data); 

        aeTable = new Tabulator("#aeTable", {
            movableRows:editAble(),
            layout:"fitColumns",
            selectable: editAble(),
            data:aeTableData,
            index: "ID",
            initialSort:[{column:'sort_order', dir:'asc'}],
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:10},
                {rowHandle:true, formatter:"handle", headerSort:false, width:10, vertAlign:"top"},
                {title:"", field:'sort_order', visible:true, sorter:'number', width:10},
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"textarea", editable:editAble, formatter:"textarea", editorParams:{
                    selectContents:true,
                }},
                {title:'Einheit', field:'unit', visible:true, editor:'list', editable:editAble, width:100,
                    editorParams: {
                        values:[@foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) {value:'{{$row->descriptor}}', label:"{{$row->descriptor}}"},@endforeach],
                        clearable:true,
                    },
                    formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) '{{$row->descriptor}}':'{{$row->descriptor}}',@endforeach
                    }

                },
                {title:'Menge', field:'amount', visible:true, width:100,  editor:'input', editable:editAble, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }, formatter:function(cell, formatterParams, onRendered) {
                    return formatAmount(cell.getValue());
                }, editorParams:{
                    elementAttributes:{
                        oninput:"validateAmount(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'Einzelpreis', field:'netprice', visible:true, width:100,  editor:'input', editable:editAble, formatter: function(cell) {
                    return formatPrice(cell.getValue());
                }, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }, editorParams:{
                    elementAttributes:{
                        oninput:"validatePrice(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'MwSt.', field:'vat', visible:true, width:90, editor:'list', editable:editAble, mutateLink:'sum', formatter: function(cell) { return cell.getValue() + '%'}, editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->rate}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->rate}}':'{{$row->descriptor}}',@endforeach
                    }


                },,
                {title:'Netto', field:'sum', visible:true, width:120, bottomCalc:sumCalc, mutateLink:'brutto',
                    mutator: function(value, row) {
                        let sum = parseFloat(row.netprice.replace(',','.')) * parseFloat(row.amount.replace(',','.'));
                        return sum.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}

                },
                {title:'Brutto', field:'brutto', visible:false, width:120, bottomCalc:sumCalc,
                    mutator: function(value, row) {
                        let brutto = parseFloat(row.sum) + parseFloat(row.vat.replace(',','.')) * parseFloat(row.sum) / 100;
                        return brutto.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}},
                
            ],
        });
    
    
        aeTable.on("rowSelected", function(row){
            $('.ae_menu_button').prop("disabled",false);
        });
        
        aeTable.on("rowDeselected", function(row){
            $('.ae_menu_button').prop("disabled",true);
        });
        
    
        aeTable.on("cellEdited", function(cell){
        
                let field = cell.getField();
                if(jQuery.inArray(field, ['brutto', 'sum']) !== -1) return;
                       
                $('#spinner').removeClass('d-none');
                
                let postData = {
                    _token:'{{csrf_token()}}',
                    _method: 'PUT',
                    data: {}
                }
                
                let row = cell.getRow().getData();
            
                postData.data[cell.getField()] = cell.getValue();
                
                $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/" + row.ID, postData)
                    
                    .done(function() {
                    
                        $('#spinner').addClass('d-none');
                    
                    })
                    
                    .fail(function(xhr, status, error) {
                            
                        $('#spinner').addClass('d-none');
                        cell.restoreOldValue();
                                    
                        alertException(xhr);
                        
                        
            
                    });
        });
        
        $('.add_ae').on('click', function() {
   
            BootstrapDialog.show({
                message: $('<div></div>').load('../../create/8d9c8b3182023463c3470b19e7b4dad2511868cc/cba3def15e0e6c1151fe202c8b00c2a0c1951909?data[_items_at_hwplus_invoices]={{$model->getKey()}}'),
                title:'Rechnungsposition erfassen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Speichern',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        let postData = $('#new_invoice_item').serialize();
                                        
                        $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/cba3def15e0e6c1151fe202c8b00c2a0c1951909", postData)
                        
                        .done(function(data) { 
                        
                            $('#spinner').addClass('d-none');
                            aeTable.addData(data);
                            dialogItself.close(); 
                        
                        })
                            
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            if(422 == xhr.status) {
                                
                                    $('#new_invoice_item').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON, function(index, item) {
                                        let array = index.split('.');
                                        $('#new_invoice_item').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                    });
                                
                                    return;
                                
                            }
                        
                            alertException(xhr);
                        
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
    
        })
        
        
        
        
        $('.drop_ae_button').click(function() {
            
            BootstrapDialog.confirm('Rechnungsposition löschen bestätigen?', function(result){
                if(result) {
                
                    $('#spinner').removeClass('d-none');
                    
                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }
                    
                    let selectedRowID = aeTable.getSelectedData()[0].ID;
                                            
                    $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/" + selectedRowID, postData)
                    
                        .done(function() {
                                        
                            $('#spinner').addClass('d-none');
                            
                            aeTable.deleteRow(selectedRowID);
                            
                            
                        
                        })
                        
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            alertException(xhr);
                        });
                    $('.ae_menu_button').prop('disabled', true);
                }
            });
        
        
        })
        








        // Services






        @if(\Runtime::make('hwplus_services_master')->count())


        @php
        $data = \App\Models\PHPXPress\HwplusInvoiceItems::with('_meta._doctype')->whereHas('_meta._doctype', function($query) {
            $query->where('ID', 'b76663c559923d5b46f232451fea273f6887bb28');
        })->where('_items_at_hwplus_invoices', $model->getKey())->get();
        @endphp

        let serviceTableData = @json($data);

        serviceTable = new Tabulator("#serviceTable", {
            movableRows:editAble(),
            layout:"fitColumns",
            selectable: editAble(),
            data:serviceTableData,
            index: "ID",
            initialSort:[{column:'sort_order', dir:'asc'}],
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:10},
                {rowHandle:true, formatter:"handle", headerSort:false, width:10, vertAlign:"top"},
                {title:"", field:'sort_order', visible:true, sorter:'number', width:10},
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"textarea", editable:editAble, formatter:"textarea", editorParams:{
                    selectContents:true,
                }},
                {title:'Einheit', field:'unit', visible:true, editor:'list', editable:editAble, width:100,
                    editorParams: {
                        values:[@foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) {value:'{{$row->descriptor}}', label:"{{$row->descriptor}}"},@endforeach],
                        clearable:true,
                    },
                    formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) '{{$row->descriptor}}':'{{$row->descriptor}}',@endforeach
                    }

                },
                {title:'Menge', field:'amount', visible:true, width:100,  editor:'input', editable:editAble, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }},
                {title:'Einzelpreis', field:'netprice', visible:true, width:100,  editor:'input', editable:editAble, formatter: function(cell) { return cell.getValue() + '€'}, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }},
                {title:'MwSt.', field:'vat', visible:true, width:90, editor:'list', editable:editAble, formatter: function(cell) { return cell.getValue() + '%'}, editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->rate}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->rate}}':'{{$row->descriptor}}',@endforeach
                    }


                },,
                {title:'Netto', field:'sum', visible:true, width:120, bottomCalc:sumCalc, mutateLink:'brutto',
                    mutator: function(value, row) {
                        let sum = parseFloat(row.netprice.replace(',','.')) * parseFloat(row.amount.replace(',','.'));
                        return sum.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}

                },
                {title:'Brutto', field:'brutto', visible:false, width:120, bottomCalc:sumCalc,
                    mutator: function(value, row) {
                        let brutto = parseFloat(row.sum) + parseFloat(row.vat.replace(',','.')) * parseFloat(row.sum) / 100;
                        return brutto.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}},

            ],
        });


        serviceTable.on("rowSelected", function(row){
            $('.service_menu_button').prop("disabled",false);
        });

        serviceTable.on("rowDeselected", function(row){
            $('.service_menu_button').prop("disabled",true);
        });


        serviceTable.on("cellEdited", function(cell){

                let field = cell.getField();
                if(jQuery.inArray(field, ['brutto', 'sum']) !== -1) return;

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

                let postData = {
                    _token:'{{csrf_token()}}',
                    _method: 'PUT',
                    data: {}
                }

                let row = cell.getRow().getData();

                postData.data[cell.getField()] = cell.getValue();

                $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/" + row.ID, postData)

                    .done(function() {

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

                    })

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

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

                        alertException(xhr);



                    });
        });

        $('.add_service').on('click', function() {


            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../361b9c0533b8686807d724eb39ec49ee1c7abc8e/d88b5f160ec4cb110473cda17917466cd2b9d352?data[invoice]={{$model->getKey()}}'),
                title:'Dienstleistung hinzufügen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });


        });



        $('.drop_service_button').click(function() {

            BootstrapDialog.confirm('Dienstleitung löschen bestätigen?', function(result){
                if(result) {

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

                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }

                    let selectedRowID = serviceTable.getSelectedData()[0].ID;

                    $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/" + selectedRowID, postData)

                        .done(function() {

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

                            serviceTable.deleteRow(selectedRowID);



                        })

                        .fail(function(xhr) {

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

                            alertException(xhr);
                        });
                    $('.ae_menu_button').prop('disabled', true);
                }
            });


        })

        
        @endif
        
        
        







        // Material















        
        
    
        @php
        $data = \App\Models\PHPXPress\HwplusInvoiceItems::with('_meta._doctype')->whereHas('_meta._doctype', function($query) { 
            $query->where('ID', '854cbb63e8c1319f02330c2e61e7b93bf4682cc2');
        })->where('_items_at_hwplus_invoices', $model->getKey())->get();
        @endphp
        let invoiceTableData = @json($data)

        invoiceTable = new Tabulator("#invoiceTable", {
            movableRows:editAble(),
            layout:"fitColumns",
            selectable: editAble(),
            rowHeight:100,
            data:invoiceTableData,
            index: "ID",
            initialSort:[{column:'_items_at_hwplus_invoices_order', dir:'asc'}],
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:60},
                {rowHandle:true, formatter:"handle", headerSort:false, width:10, vertAlign:'top'},
                {title:"", field:'_items_at_hwplus_invoices_order', visible:true, sorter:'number', width:10},
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"textarea", editable:editAble, formatter:"textarea", editorParams:             {
                    selectContents:true,
                }},
                {title:'VPE', field:'unit', visible:true, editor:'list', editable:editAble, width:100,
                    editorParams: {
                        values:[@foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) {value:'{{$row->getKey()}}', label:"{{$row->descriptor}}"},@endforeach],
                        clearable:true,
                    },
                    formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) '{{$row->getKey()}}':'{{$row->descriptor}}',@endforeach
                    }

                },
                {title:'Menge', field:'amount', visible:true, editor:'input', width:100, editable:editAble, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }, formatter:function(cell, formatterParams, onRendered) {
                    return formatAmount(cell.getValue());
                }, editorParams:{
                    elementAttributes:{
                        oninput:"validateAmount(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'Einzelpreis', field:'netprice', visible:true, editor:'input', width:100, editable:editAble, __bottomCalc:netCalc, formatter: function(cell) {
                    return formatPrice(cell.getValue());
                }, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }, editorParams:{
                    elementAttributes:{
                        oninput:"validatePrice(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'MwSt.', field:'vat', visible:true, width:90, editor:'list', editable:editAble, mutateLink:'sum', formatter: function(cell) { return cell.getValue() + '%'}, editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->rate}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->rate}}':'{{$row->descriptor}}',@endforeach
                    }


                },
                {title:'Netto', field:'sum', visible:true, bottomCalc:sumCalc, width:120, mutateLink:'brutto',
                    mutator: function(value, row) {
                        let sum = parseFloat(row.netprice.replace(',','.')) * parseFloat(row.amount.replace(',','.'));
                        return sum.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}

                },
                {title:'Brutto', field:'brutto', visible:false, width:120, bottomCalc:sumCalc,
                    mutator: function(value, row) {
                        let brutto = parseFloat(row.sum) + parseFloat(row.vat.replace(',','.')) * parseFloat(row.sum) / 100;
                        return brutto.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}},
            ],
        });
    
    
        invoiceTable.on("rowSelected", function(row){
            $('.material_menu_button').prop("disabled",false);
        });
        
        invoiceTable.on("rowDeselected", function(row){
            $('.material_menu_button').prop("disabled",true);
        });
        
        invoiceTable.on("rowMoved", function(row) {
        

        
                $('#spinner').removeClass('d-none');
        
                let postData = {
                    _token:'{{csrf_token()}}',
                    _method: 'PUT',
                    data: {}
                }
                
                postData.data['_items_at_hwplus_invoices_order'] = row.getPosition();
                
                $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/" + row.getData().ID, postData)
                    
                    .done(function(data) {
                                
                        //invoiceTable.setData("../../../api/{{$repository->getConfig()->_service->url}}/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}/_items");


                        $('#spinner').addClass('d-none');
                        
                    })
                    
                    .fail(function(xhr) {
                    
                        $('#spinner').addClass('d-none');
                        alert("Ein fehler ist aufgetreten beim Verschieben. Die Rechnung wird neu geladen");
                        window.location.reload();

                        alertException(xhr);
                    });
            
        
        });
    
    
        invoiceTable.on("cellEdited", function(cell){
        
                let field = cell.getField();
                if(jQuery.inArray(field, ['brutto', 'sum']) !== -1) return;

                $('#spinner').removeClass('d-none');
                
                let postData = {
                    _token:'{{csrf_token()}}',
                    _method: 'PUT',
                    data: {}
                }
                
                let row = cell.getRow().getData();
            
                postData.data[cell.getField()] = cell.getValue();
                
                $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/" + row.ID, postData)
                    
                    .done(function() {
                    
                        $('#spinner').addClass('d-none');
                    
                    })
                    
                    .fail(function(xhr, status, error) {
                            
                        $('#spinner').addClass('d-none');
                        cell.restoreOldValue();
                                    
                        alertException(xhr);
                        
                        
            
                    });
        });
        
        $('.add_material').on('click', function() {
   
            BootstrapDialog.show({
                message: $('<div></div>').load('../../create/8d9c8b3182023463c3470b19e7b4dad2511868cc/854cbb63e8c1319f02330c2e61e7b93bf4682cc2?data[_items_at_hwplus_invoices]={{$model->getKey()}}'),
                title:'Rechnungsposition erfassen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Speichern',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        let postData = $('#new_invoice_item').serialize();
                                        
                        $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/854cbb63e8c1319f02330c2e61e7b93bf4682cc2", postData)
                        
                        .done(function(data) { 
                        
                            $('#spinner').addClass('d-none');
                            invoiceTable.addData(data);
                            dialogItself.close(); 
                        
                        })
                            
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            if(422 == xhr.status) {
                                
                                    $('#new_invoice_item').find('.is-invalid').removeClass('is-invalid');
                                    $.each(xhr.responseJSON, function(index, item) {
                                        let array = index.split('.');
                                        $('#new_invoice_item').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                    });
                                
                                    return;
                                
                            }
                        
                            alertException(xhr);
                        
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
    
        })
        
        window.add_material_from_master = function(postData) {

            postData.data._items_at_hwplus_invoices = postData.data.object;

            $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/854cbb63e8c1319f02330c2e61e7b93bf4682cc2", postData)
                .done(function(data) {

                $('#spinner').addClass('d-none');
                    invoiceTable.addData(data);
                    $('#liveToast').toast('show');

                })

                .fail(function(xhr) {

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

                    alertException(xhr);


                });

        }
        
        
        $('.drop_material_button').click(function() {
            
            BootstrapDialog.confirm('Rechnungsposition löschen bestätigen?', function(result){
                if(result) {
                
                    $('#spinner').removeClass('d-none');
                    
                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }
                    
                    let selectedRowID = invoiceTable.getSelectedData()[0].ID;
                                            
                    $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/" + selectedRowID, postData)
                    
                        .done(function() {
                                        
                            $('#spinner').addClass('d-none');            
                            
                            invoiceTable.deleteRow(selectedRowID);
                        
                        })
                        
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            alertException(xhr);
                        });
                    $('.material_menu_button').prop('disabled', true);
                }
            });
        
        
        })

        @if(\Runtime::make('hwplus_premium_charges')->count())

        let premiumChargeTableData = @json(\App\Models\PHPXPress\HwplusPremiumCharges::get());

        premiumChargeTable = new Tabulator("#premiumChargeTable", {
            movableRows:editAble(),
            layout:"fitColumns",
            selectable: editAble() ? 1 : 0 ,
            selectableRows:1,
            rowHeight:100,
            data:premiumChargeTableData,
            index: "ID",
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:60 },
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"textarea", editable:editAble, formatter:"textarea", editorParams:             {
                    selectContents:true,
                }},
                {title:'Wert', field:'value', visible:true, editor:'input', width:100, editable:false, editorParams:             {
                    selectContents:true,
                }},
                {title:'Einheit', field:'unit', visible:true, width:100, editable:false, editorParams:             {
                    selectContents:true,
                }},
                 {title:'MwSt.', field:'_vat', visible:true, width:90, editor:'list', editable:false, formatter: function(cell) { return cell.getValue() + '%'}, mutateLink:"brutto", editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->getKey()}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->getKey()}}':'{{$row->descriptor}}',@endforeach
                    }


                },
                {title:'Netto', field:'sum', visible:false, width:100, mutateLink:"brutto",
                    formatter: function(cell) { return cell.getValue() > 0 ? cell.getValue().toFixed(2) + '€' : ''; }
                },
                {title:'Brutto', field:'brutto', visible:true, width:120,
                    mutator: function(cell, row) {

                        let brutto = row.sum + row.sum / 100 * listVat[row._vat].rate;
                        return brutto.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() > 0 ? cell.getValue() + '€' : ''; }},
            ],
        });


        @if($model->_premium_charge)
        premiumChargeTable.on("tableBuilt", function() {
            premiumChargeTable.selectRow('{{$model->_premium_charge->getKey()}}');
        });
        @endif

        premiumChargeTable.on("rowSelected", function(row){

            let selectedRow = premiumChargeTable.getSelectedRows()[0];
            let rowData = selectedRow.getData();

            let postData = {};
                postData._token = '{{csrf_token()}}';
                postData._method = "PUT";
                postData.data = {};
                postData.data._premium_charge = rowData.ID;

            $.post("../../../api/{{$repository->getConfig()->_service->url}}/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}", postData)

                        .done(function() {

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


                        })

                        .fail(function(xhr) {

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

                            alertException(xhr);
                        });



        });

        premiumChargeTable.on("rowDeselected", function(row) {

            window.setTimeout(function() {

                let selectedRow = premiumChargeTable.getSelectedRows()[0];

                if(selectedRow) return;

                let rowData = row.getData();

                let postData = {};
                    postData._token = '{{csrf_token()}}';
                    postData._method = "PUT";
                    postData.data = {};
                    postData.data._premium_charge = "";

                $.post("../../../api/{{$repository->getConfig()->_service->url}}/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}", postData)

                            .done(function() {

                                $('#spinner').addClass('d-none');
                                row.update({sum:0, brutto:0});

                            })

                            .fail(function(xhr) {

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

                                alertException(xhr);
                            });

            }, 200);

        });

        @endif

        // Sonstiges

        @php
        $data = \App\Models\PHPXPress\HwplusInvoiceItems::with('_meta._doctype')->whereHas('_meta._doctype', function($query) {
            $query->where('ID', 'e63730ed5536eb59ae0dfd1eb96f5a862be2e5c7');
        })->where('_items_at_hwplus_invoices', $model->getKey())->get();
        @endphp

        let miscTableData = @json($data);

        miscTable = new Tabulator("#miscTable", {
            movableRows:editAble(),
            layout:"fitColumns",
            selectable: editAble(),
            data:miscTableData,
            index: "ID",
            initialSort:[{column:'sort_order', dir:'asc'}],
            columns:[ //set column definitions for imported table data
                {title:"ID", field:'ID', visible:false, sorter:"number"},
                {formatter:"rowSelection", headerSort:false, width:10},
                {rowHandle:true, formatter:"handle", headerSort:false, width:10, vertAlign:"top"},
                {title:"", field:'sort_order', visible:true, sorter:'number', width:10},
                {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"textarea", editable:editAble, formatter:"textarea", editorParams:{
                    selectContents:true,
                }},
                {title:'Einheit', field:'unit', visible:true, editor:'list', editable:editAble, width:100,
                    editorParams: {
                        values:[@foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) {value:'{{$row->descriptor}}', label:"{{$row->descriptor}}"},@endforeach],
                        clearable:true,
                    },
                    formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusUnits::get() AS $row) '{{$row->descriptor}}':'{{$row->descriptor}}',@endforeach
                    }

                },
                {title:'Menge', field:'amount', visible:true, width:100,  editor:'input', editable:editAble, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }, formatter:function(cell, formatterParams, onRendered) {
                    return formatAmount(cell.getValue());
                }, editorParams:{
                    elementAttributes:{
                        oninput:"validateAmount(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'Einzelpreis', field:'netprice', visible:true, width:100,  editor:'input', editable:editAble, formatter: function(cell) {
                    return formatPrice(cell.getValue());
                }, mutateLink:"sum", editorParams:             {
                    selectContents:true,
                }, editorParams:{
                    elementAttributes:{
                        oninput:"validatePrice(event, this)", //set the maximum character length of the input element to 10 characters
                    }
                }},
                {title:'MwSt.', field:'vat', visible:true, width:90, editor:'list', editable:editAble, mutateLink:'sum', formatter: function(cell) { return cell.getValue() + '%'}, editorParams:             {
                    selectContents:true,
                    values:[@foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) {value:'{{$row->rate}}', label:"{{$row->descriptor}}"},@endforeach],
                    clearable:true,
                }, formatter:'lookup',
                    formatterParams:{
                        @foreach(\App\Models\PHPXPress\HwplusVatRates::get() AS $row) '{{$row->rate}}':'{{$row->descriptor}}',@endforeach
                    }


                },,
                {title:'Netto', field:'sum', visible:true, width:120, bottomCalc:sumCalc, mutateLink:'brutto',
                    mutator: function(value, row) {
                        let sum = parseFloat(row.netprice.replace(',','.')) * parseFloat(row.amount.replace(',','.'));
                        return sum.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}

                },
                {title:'Brutto', field:'brutto', visible:false, width:120, bottomCalc:sumCalc,
                    mutator: function(value, row) {
                        let brutto = parseFloat(row.sum) + parseFloat(row.vat.replace(',','.')) * parseFloat(row.sum) / 100;
                        return brutto.toFixed(2);
                    },
                    formatter: function(cell) { return cell.getValue() + '€'}},

            ],
        });


        miscTable.on("rowSelected", function(row){
            $('.misc_menu_button').prop("disabled",false);
        });

        miscTable.on("rowDeselected", function(row){
            $('.misc_menu_button').prop("disabled",true);
        });


        miscTable.on("cellEdited", function(cell){

                let field = cell.getField();
                if(jQuery.inArray(field, ['brutto', 'sum']) !== -1) return;

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

                let postData = {
                    _token:'{{csrf_token()}}',
                    _method: 'PUT',
                    data: {}
                }

                let row = cell.getRow().getData();

                postData.data[cell.getField()] = cell.getValue();

                $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/" + row.ID, postData)

                    .done(function() {

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

                    })

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

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

                        alertException(xhr);



                    });
        });

        $('.add_misc').on('click', function() {

            BootstrapDialog.show({
                message: $('<div></div>').load('../../create/8d9c8b3182023463c3470b19e7b4dad2511868cc/e63730ed5536eb59ae0dfd1eb96f5a862be2e5c7?data[_items_at_hwplus_invoices]={{$model->getKey()}}'),
                title:'Sonstige Position erfassen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Speichern',
                    cssClass:'btn-success',
                    action: function(dialogItself) {

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

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

                        $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/e63730ed5536eb59ae0dfd1eb96f5a862be2e5c7", postData)

                        .done(function(data) {

                            $('#spinner').addClass('d-none');
                            miscTable.addData(data);
                            dialogItself.close();

                        })

                        .fail(function(xhr) {

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

                            if(422 == xhr.status) {

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

                                    return;

                            }

                            alertException(xhr);


                        });

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

        })




        $('.drop_misc_button').click(function() {

            BootstrapDialog.confirm('Sonstige Position löschen bestätigen?', function(result){
                if(result) {

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

                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }

                    let selectedRowID = aeTable.getSelectedData()[0].ID;

                    $.post("../../../api/{{$repository->getConfig()->_service->url}}/8d9c8b3182023463c3470b19e7b4dad2511868cc/" + selectedRowID, postData)

                        .done(function() {

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

                            miscTable.deleteRow(selectedRowID);



                        })

                        .fail(function(xhr) {

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

                            alertException(xhr);
                        });
                    $('.misc_menu_button').prop('disabled', true);
                }
            });


        })

        // Verschiedenes

        $(document).on('click', '#open_materialmaster_button', function() {

            $.each(BootstrapDialog.dialogs, function(id, dialog){
                dialog.close();
            });

            dialog = BootstrapDialog.show({
                message: $('<div></div>').load('../../bdd9815c6685a7ea6a567b141e2919969717c80b/5a7dfc613be971ac442fff63b73ecd1b2ebd9594'),
                size:BootstrapDialog.SIZE_EXTRAWIDE,
                title:"Materialstamm",
                //cssClass:'modal-fullscreen',
                data:{
                    ticket: '{{$model->getKey()}}'
                }

            });

        })
        
        $(document).on('click', '#open_unitselection_button', function() {
        
       
            dialog = BootstrapDialog.show({
                title: 'Einheit auswählen',
                message: $('<div></div>').load('../../ba0cfd2e18e37e3b20f8d121a5a01d05951dd232/5ddb8c9ee285433c6034c2e62b3590242eb2f82c'),
                type:BootstrapDialog.TYPE_LIGHT
            });
        
        });
        
        
        $(document).on('click', '.preview_invoice', function() {
           
            if(!download('../../preview_invoice/1/{{$model->getKey()}}')) {
                getPDFTicket('../../preview_invoice/1/{{$model->getKey()}}');
            }

            //window.location = "../../preview_invoice/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}";
        
        })
        
        $('.finish_invoice').click(function() {
           
            //window.location = "";
            dialog = BootstrapDialog.confirm({
                title: 'Hinweis',
                type: BootstrapDialog.TYPE_WARNING, // <-- Default value is BootstrapDialog.TYPE_PRIMARY
                message: 'Wenn Sie die Rechnung schließen können keine weitere Änderungen an der Rechnung vorgenommen werden. Nach dem Schließen dieser Rechnung können Sie diese noch drucken oder per Email versenden. Rechnung jetzt schließen?',
                closable: true, // <-- Default value is false
                draggable: true, // <-- Default value is false
                btnCancelLabel: 'Abbrechen', // <-- Default value is 'Cancel',
                btnOKLabel: 'Rechnung schließen', // <-- Default value is 'OK',
                btnOKClass: 'btn-warning', // <-- If you didn't specify it, dialog type will be used,
                callback: function(result) {
                    // result will be true if button was click, while it will be false if users close the dialog directly.
                    if(result) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        $.get("../../finish_invoice/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}")
                        
                        .done(function(data) { 
                        
                            $('#spinner').addClass('d-none');
                            window.location.reload();
                            dialogItself.close(); 
                            
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            alertException(xhr);
                        
                        });
                    }
                }
            });
        
        })
        
        $('.pdf_print').click(function() {
       
            
            window.location = "../../print_invoice/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}";
            
            
        
        })
        
        $('.send_email').click(function() {
      
            BootstrapDialog.show({
                message: $('<div></div>').load('../../f0d1d47eb92f01077335f4854cafd4f9b8c65197/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}'),
                title:'Email-Versand',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Senden',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        let postData = $('#new_email').serialize();
                    
                            postData._token = '{{csrf_token()}}';
                        
                        $.post("../../mail_invoice/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}", postData)
                        
                        .done(function(data) { 
                        
                            $('#spinner').addClass('d-none');
                            dialogItself.close(); 
                            
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                        
                            
                             if(422 == xhr.status) {
                                $('#new_email').find('.is-invalid').removeClass('is-invalid');
                                $.each(xhr.responseJSON.errors, function(index, item) {
                                    let array = index.split('.');
                                    $('#new_email').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                });
                            
                            
                            }

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


        $('.drop_invoice').click(function() {


            dialog = BootstrapDialog.confirm('Rechnung löschen bestätigen?', function(result){
                if(result) {

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

                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }


                    $.post("../../drop_invoice/{{$model->getKey()}}", postData)

                        .done(function() {

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

                            window.location = "../../759549c6ca5f53b6c47699785cbd2ca0aa8438e4/afe4f16263308b092d15e04719f202efe1326813";

                        })

                        .fail(function(xhr) {

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

                            alertException(xhr);
                        });

                }
            });


        })



        $('.copy_invoice').click(function() {

            dialog = BootstrapDialog.confirm({
                title: 'Hinweis',
                type: BootstrapDialog.TYPE_WARNING,
                message: 'Möchten Sie die aktuelle Rechnung duplizieren? Wenn Sie auf JA klicken, wird automatisch eine Kopie erstellt.',
                closable: true, // <-- Default value is false
                draggable: true, // <-- Default value is false
                btnCancelLabel: 'Abbrechen', // <-- Default value is 'Cancel',
                btnOKLabel: 'Kopie erstellen', // <-- Default value is 'OK',
                btnOKClass: 'btn-warning', // <-- If you didn't specify it, dialog type will be used,
                callback: function(result) {
                    // result will be true if button was click, while it will be false if users close the dialog directly.
                    if(result) {

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

                        $.post("../../copy_invoice/{{$model->getKey()}}")

                        .done(function(data) {

                            $('#spinner').addClass('d-none');
                            window.location.reload();
                            dialogItself.close();

                        })

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

                            alertException(xhr);

                        });
                    }
                }
            });

        })

        
        $('.create_reverse_invoice').click(function() {
           
            dialog = BootstrapDialog.confirm({
                title: 'Hinweis',
                type: BootstrapDialog.TYPE_WARNING,
                message: 'Möchten Sie die aktuelle Rechnung stornieren? Wenn Sie auf JA klicken, wird automatisch eine Storno-Rechnung erstellt.',
                closable: true, // <-- Default value is false
                draggable: true, // <-- Default value is false
                btnCancelLabel: 'Abbrechen', // <-- Default value is 'Cancel',
                btnOKLabel: 'Stornorechnung erstellen', // <-- Default value is 'OK',
                btnOKClass: 'btn-warning', // <-- If you didn't specify it, dialog type will be used,
                callback: function(result) {
                    // result will be true if button was click, while it will be false if users close the dialog directly.
                    if(result) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        $.post("../../create_reverse_invoice/{{$model->getKey()}}")
                        
                        .done(function(data) { 
                        
                            $('#spinner').addClass('d-none');
                            window.location.reload();
                            dialogItself.close(); 
                            
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            alertException(xhr);
                        
                        });
                    }
                }
            });
        
        })
        
        
        $('.create_adjusted_invoice').click(function() {
           
            dialog = BootstrapDialog.confirm({
                title: 'Hinweis',
                type: BootstrapDialog.TYPE_WARNING,
                message: 'Möchten Sie die aktuelle Rechnung berichtigen? Wenn Sie auf JA klicken, wird automatisch eine Berichtigungs-Rechnung erstellt.',
                closable: true, // <-- Default value is false
                draggable: true, // <-- Default value is false
                btnCancelLabel: 'Abbrechen', // <-- Default value is 'Cancel',
                btnOKLabel: 'Berichtigungsrechnung erstellen', // <-- Default value is 'OK',
                btnOKClass: 'btn-warning', // <-- If you didn't specify it, dialog type will be used,
                callback: function(result) {
                    // result will be true if button was click, while it will be false if users close the dialog directly.
                    if(result) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        $.post("../../create_adjusted_invoice/{{$model->getKey()}}")
                        
                        .done(function(data) { 
                        
                            $('#spinner').addClass('d-none');
                            window.location.reload();
                            dialogItself.close(); 
                            
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            alertException(xhr);
                        
                        });
                    }
                }
            });
        
        })
        

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


            BootstrapDialog.show({
                message: $('<div></div>').load('../../915533142c45502d38b74e61e0749fa621c1b158/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}'),
                title:'Rechnungsempfänger ändern',
                type:BootstrapDialog.TYPE_LIGHT,
                size:BootstrapDialog.SIZE_WIDE,
                buttons: [{
                    label: 'Weiter',
                    cssClass:'btn-success',
                    action: function(dialogItself) {

                        let client = $.map($('#client_select_table').bootstrapTable('getSelections'), function (row) {
                            return row;
                        })

                        clientID = client[0].ID;

                        dialogItself.close();

                        BootstrapDialog.show({
                            message: $('<div></div>').load('../../a1bffc658eb57d949d141162fc714d1a8d0f542e/86343e16c8551a46bdd6560814444580b3833a53/' + clientID),
                            title:'Rechnungsadresse ändern',
                            size:BootstrapDialog.SIZE_WIDE,
                            type:BootstrapDialog.TYPE_LIGHT,
                            buttons: [{
                                label: 'Auswahl übernehmen',
                                cssClass:'btn-success',
                                action: function(dialogItself) {

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

                                    switch(option) {

                                        case "new":

                                            dialogItself.close();

                                            BootstrapDialog.show({
                                                message: $('<div></div>').load('../../bee81541cb1e85aa6f48a7ec8f590b5e2a4b0c28/86343e16c8551a46bdd6560814444580b3833a53/' + clientID),
                                                title:'Neue 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/{{$repository->getConfig()->_service->url}}/86343e16c8551a46bdd6560814444580b3833a53/bee81541cb1e85aa6f48a7ec8f590b5e2a4b0c28", postData)

                                                            .done(function(data) {
                                                                $('#spinner').addClass('d-none');
                                                                dialogItself.close();
                                                                $.post("../../change_invoice_receipient/{{$model->getKey()}}/" + data[0].ID)
                                                                    .done(function(data) {
                                                                        window.location.reload();
                                                                    })
                                                                    .fail(function(xhr, status, error) {
                                                                        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');
                                                                        });

                                                                        return;

                                                                }


                                                                else alertException(xhr);

                                                            });
                                                    }
                                                }]
                                            });


                                            break;


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



                                        default:

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


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

                                            $.post("../../change_invoice_receipient/{{$model->getKey()}}/" + $('#new_invoice [name="recipient"]:checked').val())
                                                .done(function(data) {
                                                    window.location.reload();
                                                })
                                                .fail(function(xhr, status, error) {
                                                    alertException(xhr);

                                                });

                                            break;

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



                        return;



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


        })

    
        $('#fare,#location,#commission_number,#note,#order_number,#date,#service_date,#header,#assignment').editable({ showbuttons: "bottom", onblur:"ignore", emptytext:'Klicken zum ändern', disabled:{{$model->flag_finished ? "true" : "false"}}});
        
        $('__#header').editable({
            tpl: "<textarea type='text' style='width:800px'></textarea>"
        });
        
        $('#service_date').on('save', function(e, params) { 
        
            $('#spinner').removeClass('d-none');
            
            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['service_date'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}", postData)
                
                .done(function(data) {
                
                    $('#spinner').addClass('d-none');
                    $('#service_date').html(moment(data[0].service_date).format('DD.MM.YYYY'));
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);      
                });
        
        });
        
        $('#date').on('save', function(e, params) { 
        
            $('#spinner').removeClass('d-none');
            
            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['date'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}", postData)
                
                .done(function(data) {
                
                    $('#spinner').addClass('d-none');
                    $('#date').html(moment(data[0].date).format('DD.MM.YYYY'));
                    
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);     
                });
        
        });


        $('#assignment').on('save', function(e, params) {

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

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }

            postData.data['assignment'] = params.newValue;

            $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->_ticket->getKey()}}", postData)

                .done(function() {

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

                })

                .fail(function(xhr) {

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

                    alertException(xhr);
                });

        });

        
        $('#header').on('save', function(e, params) { 
        
            $('#spinner').removeClass('d-none');
            
            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['header'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}", postData)
                
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);   
                });
        
        });
        
       
        $('#note').on('save', function(e, params) {

            $('#spinner').removeClass('d-none');
            
            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['note'] = params.newValue;
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}", postData)
                
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);         
                });
        });
        
        $('#print_note').change(function() {
        
            $('#spinner').removeClass('d-none');
            
            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            postData.data['print_note'] = $('#print_note').prop('checked') ? 1 : 0;
                        
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}", postData)
                
                .done(function() {
                
                    $('#spinner').addClass('d-none');
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);  
                });
            
        });

        $('#order_number').on('save', function(e, params) {

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

            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }

            postData.data['order_number'] = params.newValue;

            $.post("../../../api/{{$repository->getConfig()->_service->url}}/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->getKey()}}", postData)

                .done(function() {

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

                })

                .fail(function(xhr) {

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

                    alertException(xhr);
                });
        });
        
        
        $('.create_standing_order').on('click', function() {
        
            BootstrapDialog.confirm('Möchten Sie die aktuelle Rechnung als Dauerauftrag anlegen?', function(result){
                if(result) {
                
                    $('#spinner').removeClass('d-none');
                    
                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'POST',
                    }
                                            
                    $.post("../../create_standing_order/{{$model->getKey()}}", postData)
                    
                        .done(function(data) {
                                        
                            $('#spinner').addClass('d-none');            
                            window.location = "../../137a983681de4ff7f08ec43c875cb00161efc24a/27b96af59ee924f9ec98cf9c44b54e06219636c1/" + data[0].ID;
                            
                        
                        })
                        
                        .fail(function(xhr) {
                        
                            $('#spinner').addClass('d-none');
                        
                            alertException(xhr);
                        });
                    
                }
            });
            
        
        });
        
        
        
        $('#change_adress').on('click', function() {
        
        return;
            BootstrapDialog.show({
                message: $('<div></div>').load('../../1c09c602ecc905155d989319c7f8f116600af860/86343e16c8551a46bdd6560814444580b3833a53'),
                title:'Rechnungsadresse ändern',
                buttons: [{
                    label: 'Speichern',
                    action: function(dialogItself) {
                    
                        $('#spinner').removeClass('d-none');
                    
                        let ids = $.map($('#client_select_table').bootstrapTable('getSelections'), function (row) {
                            return row.ID
                        })
                        
                        let postData = {};
                            postData._method = "PUT";
                            postData.data = {};
                            postData.data['_client'] = ids[0];
                                            
                        $.post("../../../api/{{$repository->getConfig()->_service->url}}/afe4f16263308b092d15e04719f202efe1326813/{{$model->getKey()}}", postData)
                        
                        .done(function(data) { 
                            $('#spinner').addClass('d-none');
                            dialogItself.close(); 
                            window.location.reload(); 
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                            
                            alertException(xhr);
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
        
        });



        
    
    });
    
    

    
    </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-danger">
          
        <nav class="navbar navbar-expand-lg navbar-light bg-danger text-white">
            <a class="navbar-brand text-white" href="#"><i class="mdi mdi-book-open-page-variant-outline"></i> Rechnungswesen</a>
        </nav>

        <div class="btn-group mt-2 mb-2" role="group">

            <button type="button" class="btn btn-danger" onclick="window.location='../../759549c6ca5f53b6c47699785cbd2ca0aa8438e4/afe4f16263308b092d15e04719f202efe1326813'"><i class="mdi mdi-home-circle"></i> zurück zur Übersicht</button>
            <button class="btn btn-danger dropdown-toggle" type="button" data-toggle="dropdown">
                {{$model->descriptor}}
            </button>
            <div class="dropdown-menu">
                <a class="dropdown-item preview_invoice @if($model->flag_finished) disabled @endif" href="#">Vorschau</a>
                @if($model->invoice_number AND $model->descriptor == "Korrekturrechnung")
                <div class="dropdown-divider"></div>
                <a class="dropdown-item finish_invoice" href="#">Korrekturrechnung abschließen</a>
                @elseif(!$model->invoice_number)
                <div class="dropdown-divider"></div>
                <a class="dropdown-item finish_invoice" href="#">Rechnung abschließen</a>
                @if("standing_order" != $model->_meta->_doctype->identifier)
                <a class="dropdown-item create_standing_order" href="#">Dauerauftrag anlegen</a>
                @endif
                @else
                <a class="dropdown-item pdf_print" href="#">@if($model->printed) erneut @endif Drucken</a>
                @if($MAIL_HOST)
                <a class="dropdown-item send_email" href="#">@if($model->mailed) erneut @endif per Email senden</a>
                @endif
                @if($model->printed OR $model->mailed)
                <a class="dropdown-item create_reverse_invoice" href="#">Rechnung stornieren</a>
                <a class="dropdown-item create_adjusted_invoice" href="#">Rechnung berichtigen</a>
                @endif
                @endif
                <div class="dropdown-divider"></div>
                <a class="dropdown-item copy_invoice" @if($model->descriptor != "Rechnung") disabled @endif href="#">Kopie erstellen</a>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item drop_invoice @if($model->flag_finished) disabled @endif" href="#">Löschen</a>
            </div>
        </div>
          
          
          
            <div class="row">
            
                <div class="col col-xs-12 col-md-4">
                
                    <div class="card">
                            <ul class="list-group list-group-flush">
                            <li class="list-group-item"><b>{{$model->descriptor}}</b> @if(!$model->flag_finished) <button class="btn btn-sm btn-secondary float-right" id="change_client" >Adresse ändern</button> @endif</li>
                            <li class="list-group-item">
                                <b>{{$model->client}}</b>  
                                @if($model->firstname) <br> {{$model->firstname}} {{$model->surname}} @endif
                                <br>{{$model->streetadress}} {{$model->housenumber}}
                                <br>{{$model->postcode}} {{$model->location}}
                            </li>
                        </ul>
                    </div>
                </div>
            
            
                <div class="col col-xs-12 col-md-4">
                    <div class="card">
                            <ul class="list-group list-group-flush">
                            <li class="list-group-item"><b>Notizen:</b></b> <small>(auf PDF drucken <input type="checkbox" name="data[print_note]" id="print_note" {{$model->print_note ? 'checked="checked"' : ''}}>)</small></li>
                            @if(!$model->invoice_number)
                            <li class="list-group-item"><a href="#" id="note" data-type="textarea" data-mode="inline">{{$model->note}}</a></li>
                            @else
                            <li class="list-group-item">{!! nl2br($model->note)!!}</li>
                            @endif
                        </ul>
                    </div>
                
                </div>
                <div class="col col-xs-12 col-md-4">
                    <div class="card">
                            <ul class="list-group list-group-flush">

                            @if(!$model->invoice_number OR (!$model->flag_finished AND $model->invoice_number))
                            <li class="list-group-item" style="font-size:x-large"><b>RG-Nummer:</b> <b class="text-danger">[{{$model->createInvoiceNumber()}}]</b></li>
                            @else
                            <li class="list-group-item" style="font-size:x-large"><b>RG-Nummer:</b> <b class="text-danger">{{$model->invoice_number}}</b></li>
                            @endif

                            @if($model->_ticket->getKey() AND "Angebot" == $model->_ticket->descriptor)
                            <li class="list-group-item"><b>{{$model->_ticket->descriptor}}:</b> <a href="#" onclick="window.parent.load_frame('offers', 'd774d83528528c1bb8aa3f8a18d6bd66a9c76e66/afe4f16263308b092d15e04719f202efe1326813/{{$model->_ticket->getKey()}}', true)"  style="color:var(--cyan)">{{$model->_ticket->job_number}}</a></li>
                            @elseif($model->_ticket->getKey())
                            <li class="list-group-item"><b>{{$model->_ticket->descriptor}}:</b> <a href="#" onclick="window.parent.load_frame('closed_tickets', '0ff1bb77a9de65eac6621c9c5a983da7a37ed3bf/afe4f16263308b092d15e04719f202efe1326813/{{$model->_ticket->getKey()}}', true)"  style="color:var(--cyan)">{{$model->_ticket->job_number}}</a></li>
                            @endif

                            @if($ri = \App\Models\PHPXPress\HwplusInvoices::where('_reverse_invoice', $model->getKey())->first())
                            <li class="list-group-item"><b>Originalrechnung:</b> <a href="#" onclick="window.parent.load_frame('invoices', '2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$ri->getKey()}}', true)"  style="color:var(--cyan)">{{$ri->invoice_number}}</a></li>
                            @endif

                            <li class="list-group-item"><b>Gesendet:</b> @if($model->mailed) {{(new \Carbon\Carbon($model->mailed))->format('d.m.Y')}} @endif</li>
                            <li class="list-group-item"><b>Gedruckt:</b> @if($model->printed) {{(new \Carbon\Carbon($model->printed))->format('d.m.Y')}} @endif</li>

                            @if($model->_ticket->getKey())
                            <li class="list-group-item"><b>Bestellnummer:</b> {{$model->_ticket->order_number}}</li>
                            @else
                            <li class="list-group-item"><b>Bestellnummer:</b> <a href="#" id="order_number" data-type="text" data-mode="inline">{{$model->order_number}}</a></li>
                            @endif

                            <li class="list-group-item"><b>Leistungsdatum:</b> <a href="#" id="service_date" data-tpl="<input type='date'>" data-mode="inline" data-value="{{$model->service_date}}" data-emptytext ="Heute">@if($model->service_date) {{(new \Carbon\Carbon($model->service_date))->format('d.m.Y')}} @endif</a></li>
                            
                            <li class="list-group-item"><b>Rechnungsdatum:</b> <a href="#" id="date" data-tpl="<input type='date'>" data-mode="inline" data-value="{{$model->date}}" data-emptytext ="Heute">@if($model->date) {{(new \Carbon\Carbon($model->date))->format('d.m.Y')}} @endif</a></li>
                            @if($model->_reverse_invoice)
                            <li class="list-group-item"><b>Stornodatum:</b> {{(new \Carbon\Carbon($model->_reverse_invoice->date))->format('d.m.Y')}}</li>
                            @endif
                            
                        </ul>
                    </div>
                </div>
            </div>

            @if($model->descriptor == "Stornorechnung")
            <div class="card mt-2">
                <div class="card-header bg-danger text-white">Hinweis</div>
                <div class="card-body bg-danger text-white">

                    Bei dieser Rechnung handelt es sich um eine Stornorechnung! Die Originalrechnung finden Sie <a class="text-dark" href="../../2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{\App\Models\PHPXPress\HwplusInvoices::where('_reverse_invoice', $model->getKey())->first()->getKey()}}">&gt; hier &lt;</a>.

                </div>
            </div>
            @endif

            @if($model->descriptor == "Korrekturrechnung")
            <div class="card mt-2">
                <div class="card-header bg-danger text-white">Hinweis</div>
                <div class="card-body bg-danger text-white">

                    Bei dieser Rechnung handelt es sich um eine Korrekturrechnung! Die Originalrechnung finden Sie <a class="text-dark" href="../../2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{\App\Models\PHPXPress\HwplusInvoices::where('_adjusted_invoice', $model->getKey())->first()->getKey()}}">&gt; hier &lt;</a>.

                </div>
            </div>
            @endif
            
            @if($model->_reverse_invoice)
            <div class="card mt-2">
                <div class="card-header bg-danger text-white">Hinweis</div>
                <div class="card-body bg-danger text-white">
                    
                    Diese Rechnung wurde storniert. Die Stornorechnung finden Sie <a class="text-dark" href="../../2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->_reverse_invoice->getKey()}}">&gt; hier &lt;</a>.
                    
                </div>
            </div>
            @endif


            @if($model->_adjusted_invoice)
            <div class="card mt-2">
                <div class="card-header bg-danger text-white">Hinweis</div>
                <div class="card-body bg-danger text-white">

                    Diese Rechnung wurde korrigiert. Die Korrekturrechnung finden Sie <a class="text-dark" href="../../2fc25ddce687403194c3995a6f3bcdcebb62968d/27b96af59ee924f9ec98cf9c44b54e06219636c1/{{$model->_adjusted_invoice->getKey()}}">&gt; hier &lt;</a>.

                </div>
            </div>
            @endif

            @if($model->_ticket)
            <hr>

            <div class="card mt-2">
                <div class="card-header">Durchgeführte Arbeiten</div>
                <div class="card-body">

                    @if(!$model->flag_finished)

                    <a href="#" id="assignment" data-type="textarea" data-mode="inline">{!!$model->_ticket->assignment!!}</a>

                    @else

                    @foreach(explode("\n", $model->_ticket->assignment) as $line) {{ $line }} <br> @endforeach

                    @endif
                </div>
            </div>
            @endif

            <hr>
            
            <div class="card mt-2">
                <div class="card-header">Anschreiben
                    <div class="btn-group float-right" role="group">
                        <button class="btn btn-primary float-right" data-toggle="collapse" data-target="#collapseExample">
                            Platzhalter
                        </button>
                        <button class="btn btn-primary float-right" onclick="preview_header()">
                            Vorschau
                        </button>
                    </div>
                </div>
                <x-placeholder_invoices :model="$model"/>
                <div class="card-body">
                    
                    @if(!$model->flag_finished)
                    
                    <a href="#" id="header" data-type="textarea" data-mode="inline">{!!$model->header!!}</a>
                    
                    @else
                    
                    @foreach(explode("\n", $model->header) as $line) {{ $line }} <br> @endforeach
                    
                    @endif
                </div>
            </div>

            
            
            <div class="card mt-2">
                <div class="card-header">Arbeitsstunden</div>
                <div class="card-body">
                    
                    @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-secondary add_ae" ><i class="bi bi-file-plus"></i> Zeit</button>
                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle ae_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_ae_button" >Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif

                    <div id="aeTable" class="mt-3"></div>

                    @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-secondary add_ae" ><i class="bi bi-file-plus"></i> Zeit</button>
                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle ae_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_ae_button" >Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif

                </div>

            </div>
            
            <div class="card mt-2">
                <div class="card-header">Nebenleistungen (Fahrtkosten etc.)</div>
                <div class="card-body">
                    
                    @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-secondary add_fare"  ><i class="bi bi-file-plus"></i> Nebenleistung</button>
                        <button type="button" class="btn btn-secondary add_fare_charge" ><i class="bi bi-file-plus"></i> aus Katalog</button>
                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle fare_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_fare_button" >Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif

                    <div id="fareTable" class="mt-3"></div>

                    @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-secondary add_fare"  ><i class="bi bi-file-plus"></i> Nebenleistung</button>
                        <button type="button" class="btn btn-secondary add_fare_charge" ><i class="bi bi-file-plus"></i> aus Katalog</button>
                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle fare_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_fare_button" >Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif

                </div>

            </div>

            @if(\Runtime::make('hwplus_services_master')->count())

            <div class="card mt-2">
                <div class="card-header">Dienstleistungen</div>
                <div class="card-body">

                    @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-secondary add_service" ><i class="bi bi-file-plus"></i> Leistung</button>
                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle service_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_service_button" >Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif

                    <div id="serviceTable" class="mt-3"></div>

                    @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-secondary add_service" ><i class="bi bi-file-plus"></i> Leistung</button>
                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle service_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_service_button" >Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif


                </div>

            </div>

            @endif


            <!--div class="card mt-2">
                <div class="card-header  font-weight-bold text-right pr-5">
                    <div class="sum1 mr-5">0.00€</div>
                </div>
            </div -->

                
            @if(\App\Models\PHPXPress\HwplusPremiumCharges::count())

            <div class="card mt-2">
                <div class="card-header  bg-secondary text-white">Sonderzuschlag</div>
                <div class="card-body">
                    <div id="premiumChargeTable" class="mt-3"></div>
                </div>
            </div>

            <div class="card mt-2">
                <div class="card-header font-weight-bold text-right pr-5">
                    <div class="sum2 mr-5">0.00€</div>
                </div>
            </div>

            @else

            <div class="sum2 d-none"></div>

            @endif
            
            <div class="card mt-2">
                <div class="card-header">Material</div>
                <div class="card-body">
                    
                    @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-secondary add_material" ><i class="bi bi-file-plus"></i> Material</button>
                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle material_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_material_button" >Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif

                    <div id="invoiceTable" class="mt-3"></div>

                    @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-secondary add_material" ><i class="bi bi-file-plus"></i> Material</button>
                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle material_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_material_button" >Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif


                </div>


            </div>

            <div class="card mt-2">
                <div class="card-header">Sonstiges</div>
                <div class="card-body">

                    @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-secondary add_misc" ><i class="bi bi-file-plus"></i> Sonstiges</button>
                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle misc_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_misc_button" >Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif

                    <div id="miscTable" class="mt-3"></div>

                    @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">
                        <button type="button" class="btn btn-secondary add_misc" ><i class="bi bi-file-plus"></i> Sonstiges</button>
                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle misc_menu_button" type="button"  data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item drop_misc_button" >Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif

                </div>


            </div>



        <div class="card mt-2">
            <div class="card-header gesamt font-weight-bold text-right pr-5">
                <div class="netto">0.00€</div>
                @if(!$editor->getValue('COMPANY_SBLAW'))<div class="brutto">0.00€</div>@endif
            </div>
        </div>


        
         <div class="card mt-2">
                <div class="card-header">Rechnungstext</div>
                <div class="card-body">
                    
                    @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">

                        <button type="button" class="btn btn-secondary" id="add_invoice_text"><i class="bi bi-file-plus"></i></button>
                        
                       
                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle" type="button" id="invoice_text_menu_button" data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item" id="drop_invoice_text_button">Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif
                </div>
                <div id="invoiceTextTable" class="mt-3"></div>

                @if(!$model->flag_finished)
                    <div class="btn-group mt-2" role="group">

                        <button type="button" class="btn btn-secondary" id="add_invoice_text"><i class="bi bi-file-plus"></i></button>


                        <div class="btn-group ml-0">
                            <button class="btn btn-secondary dropdown-toggle" type="button" id="invoice_text_menu_button" data-toggle="dropdown" aria-expanded="false" disabled>
                            gewählte Position
                            </button>
                            <div class="dropdown-menu">
                                <button class="dropdown-item" id="drop_invoice_text_button">Löschen</button>
                            </div>
                        </div>
                    </div>
                    @endif

            </div>
            
        
         <div class="card mt-2">
                <div class="card-header">Dokument</div>
                <div class="card-body text-right">
                    @if(!$model->flag_finished)
                    <button class="btn btn-danger finish_invoice">Rechnung abschließen</a>
                    @else
                    <button class="btn btn-danger pdf_print">@if($model->printed) erneut @endif Drucken</button>
                        @if($MAIL_HOST)
                        <button class="btn btn-danger send_email">@if($model->mailed) erneut @endif per Email senden</button>
                        @endif
                    @endif
                </div>
            </div>           
            
        </div>

        
    </div>                  
    </body>
</html>
