<!doctype html>
<?php 

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

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

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.2/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@7.4.47/css/materialdesignicons.min.css">

    <!-- JQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    
    <!-- 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>
    <!-- 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>

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

    <!-- 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">
    <!--link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery.fancytree@2.38.2/dist/skin-win8-xxl/ui.fancytree.min.css" -->
    <script src="https://cdn.jsdelivr.net/npm/jquery.fancytree@2.38.3/dist/modules/jquery.fancytree.dnd.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_semanticui.min.css">
    
    <script src=" https://cdn.jsdelivr.net/npm/numeral@2.0.6/numeral.min.js "></script>

    <script src="{{url('js/hwplus.js')}}"></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: 1px solid rgba(34,36,38,.15);
            border-radius:10px;
            background-color:#f9fafb;
        }

        
    
    </style>
    
    
    <script>

   
  $(function() {

  
        $("#tree").fancytree({
            icons:true,
            autoCollapse: true,
            autoScroll: true,
            minExpandLevel: 2,
            connectors:true,
            extensions: ["dnd5"],
            click: function(event, data) {
            
                let key = data.node.key;

                $('.folder_detail').prop('disabled', false);
                masterTable.setData("../../api/{{$repository->getConfig()->_service->url}}/d31b93cf956350ee05030203dbaeb11022ac7320/" + key + "/_material");
            
            },
            dnd5: {
                autoExpandMS: 1500,
                preventRecursion: true, // Prevent dropping nodes on own descendants
                preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.

                // --- Drag Support --------------------------------------------------------

                dragStart: function(node, data) {
                // Called on source node when user starts dragging `node`.
                // This method MUST be defined to enable dragging for tree nodes!
                // We can
                //   - Add or modify the drag data using `data.dataTransfer.setData()`.
                //   - Call `data.dataTransfer.setDragImage()` and set `data.useDefaultImage` to false.
                //   - Return false to cancel dragging of `node`.

                // Set the allowed effects (i.e. override the 'effectAllowed' option)
                data.effectAllowed = "all";  // or 'copyMove', 'link'', ...

                // Set a drop effect (i.e. override the 'dropEffectDefault' option)
                // One of 'copy', 'move', 'link'.
                // In order to use a common modifier key mapping, we can use the suggested value:
                data.dropEffect = data.dropEffectSuggested;

                // We could also define a custom image here (not on IE though):
                //data.dataTransfer.setDragImage($("<div>TEST</div>").appendTo("body")[0], -10, -10);
                //data.useDefaultImage = false;

                // Return true to allow the drag operation
                if( node.isFolder() ) { return false; }
                return true;
                },
                dragDrag: function(node, data) {
                // Called on source node every few milliseconds while `node` is dragged.
                // Implementation of this callback is optional and rarely required.
                },
                dragEnd: function(node, data) {
                // Called on source node when the drag operation has terminated.
                // Check `data.isCancelled` to see if a drop occurred.
                // Implementation of this callback is optional and rarely required.
                // Note caveat: 
                // If the drop handler removed or moved the dragged source element,  
                // `node` and `data` may not contain expected values, or this event
                // is not triggered at all.
                },

                // --- Drop Support --------------------------------------------------------

                dragEnter: function(node, data) {
                // Called on target node when s.th. is dragged over `node`.
                // `data.otherNode` may be a Fancytree source node or null for 
                // non-Fancytree droppables.
                // This method MUST be defined to enable dropping over tree nodes!
                //
                // We may
                //   - Set `data.dropEffect` (defaults to '')
                //   - Call `data.setDragImage()`
                //
                // Return
                //   - true to allow dropping (calc the hitMode from the cursor position)
                //   - false to prevent dropping (dragOver and dragLeave are not called)
                //   - a list (e.g. ["before", "after"]) to restrict available hitModes
                //   - a string "over", "before, or "after" to force a hitMode
                //   - Any other return value will calc the hitMode from the cursor position.

                // Example:
                // Prevent dropping a parent below another parent (only sort nodes under
                // the same parent):
                //if(node.parent !== data.otherNode.parent){
                //  return false;
                //}
                // Example:
                // Don't allow dropping *over* a node (which would create a child). Just
                // allow changing the order:
                //return ["before", "after"];

                // Accept everything:
                return 'over';
                },
                dragOver: function(node, data) {
                // Called on target node every few milliseconds while some source is 
                // dragged over it.
                // `data.hitMode` contains the calculated insertion point, based on cursor
                // position and the response of `dragEnter`.
                //
                // We may
                //   - Override `data.hitMode`
                //   - Set `data.dropEffect` (defaults to the value that of dragEnter)
                //     (Note: IE will ignore this and use the value from dragenter instead!)
                //   - Call `data.dataTransfer.setDragImage()`

                // Set a drop effect (i.e. override the 'dropEffectDefault' option)
                // One of 'copy', 'move', 'link'.
                // In order to use a common modifier key mapping, we can use the suggested value:
                data.dropEffect = data.dropEffectSuggested;
                },
                dragExpand: function(node, data) {
                // Called when a dragging cursor lingers over a parent node.
                // (Optional) Return false to prevent auto-expanding `node`.
                },
                dragLeave: function(node, data) {
                // Called when s.th. is no longer dragged over `node`.
                // Implementation of this callback is optional and rarely required.
                },
                dragDrop: function(node, data) {
                // This function MUST be defined to enable dropping of items on the tree.
                //
                // The source data is provided in several formats:
                //   `data.otherNode` (null if it's not a FancytreeNode from the same page)
                //   `data.otherNodeData` (Json object; null if it's not a FancytreeNode)
                //   `data.dataTransfer.getData()`
                //
                // We may access some meta data to decide what to do:
                //   `data.hitMode` ("before", "after", or "over").
                //   `data.dataTransfer.dropEffect`,`.effectAllowed`
                //   `data.originalEvent.shiftKey`, ...
                //
                // Example:

                var transfer = data.dataTransfer;

                node.debug("drop", data);

                if( data.otherNode ) {
                    // Drop another Fancytree node from same frame
                    // (maybe from another tree however)
                    
                    var sameTree = (data.otherNode.tree === data.tree);
                    
                   
                    let postData = {};
                        postData._method = "PUT";
                        postData.data = {};
                        postData.data._parent = node.key;
                    
                    $.post("../../api/{{$repository->getConfig()->_service->url}}/d31b93cf956350ee05030203dbaeb11022ac7320/" + data.otherNode.key, postData)
                    
                        .done(function() {
                        
                            data.otherNode.moveTo(node, data.hitMode);
                        
                        })
                        
                        .fail(function(xhr) {
                        
                            alertException(xhr);
                        });
                    
                    
                    

                    
                } else if( data.otherNodeData ) {
                    // Drop Fancytree node from different frame or window, so we only have
                    // JSON representation available
                    node.addChild(data.otherNodeData, data.hitMode);
                } else {
                    // Drop a non-node
                    node.addNode({
                    title: transfer.getData("text")
                    }, data.hitMode);
                }
                // Expand target node when a child was created:
                node.setExpanded();
                }
            }
        
        });
        
        
        $('#add_folder').on('click', function() {
        
            let tree = $('#tree').fancytree('getTree');
            let node = tree.getActiveNode();
            let id = node.key;
            
            BootstrapDialog.show({
                message: $('<div></div>').load('../e1256850759665749fe0afb29f705c2cea70f7d2'),
                title:'Neues Verzeichnis erstellen',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Speichern',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                    
                        let tree = $('#tree').fancytree('getTree');
                        let node = tree.getActiveNode();
                        $('#new_folder').find('input[name="data[_parent]"]').val(node.key);
                          
                        let postData = $('#new_folder').serialize();
                    
                        $.post("../../api/{{$repository->getConfig()->_service->url}}/d31b93cf956350ee05030203dbaeb11022ac7320/e1256850759665749fe0afb29f705c2cea70f7d2", postData)
                        
                        .done(function(data) {  
                        
                            let tree = $('#tree').fancytree('getTree');
                            let node = tree.getActiveNode();
                            node.addNode({key:data[0].ID, title:data[0].descriptor});
                        
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            
                            if(422 == xhr.status) {
                                $('#new_folder').find('.is-invalid').removeClass('is-invalid');
                                $.each(xhr.responseJSON, function(index, item) {
                                    let array = index.split('.');
                                    $('#new_folder').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                });
                            
                            
                            }

                            else alertException(xhr);
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
            
        });
        
        
        $('#edit_folder').on('click', function() {
        
            let tree = $('#tree').fancytree('getTree');
            let node = tree.getActiveNode();
            let id = node.key;
            
            BootstrapDialog.show({
                message: $('<div></div>').load('../edit/d31b93cf956350ee05030203dbaeb11022ac7320/' + id),
                title:'Verzeichnis bearbeiten',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Speichern',
                    cssClass:'btn-success',
                    action: function(dialogItself) {
                          
                        let postData = $('#form_edit_folder').serialize();
                    
                        $.post("../../api/{{$repository->getConfig()->_service->url}}/d31b93cf956350ee05030203dbaeb11022ac7320/" + id, postData)
                        
                        .done(function(data) {  
                        
                            let tree = $('#tree').fancytree('getTree');
                            let node = tree.getActiveNode();
                            node.setTitle(data[0].descriptor);
                            
                            dialogItself.close();
                        
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            
                            if(422 == xhr.status) {
                                $('#form_edit_folder').find('.is-invalid').removeClass('is-invalid');
                                $.each(xhr.responseJSON, function(index, item) {
                                    let array = index.split('.');
                                    $('#form_edit_folder').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                });
                            
                            
                            }

                            else alertException(xhr);
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
            
        });
  
 
        $(document).on('click', '#drop_material_button', function() { 
        
            BootstrapDialog.confirm('Möchten Sie den gewählten Eintrag wirklich löschen?', function(result){
                if(result) {
                    
                    let postData = {
                        _token:'{{csrf_token()}}',
                        _method: 'DELETE',
                    }
                    
                    
                    let ids = masterTable.getSelectedData();
                    
                          
                    $.post("../../api/{{$repository->getConfig()->_service->url}}/5a7dfc613be971ac442fff63b73ecd1b2ebd9594/" + ids[0].ID, postData)
                    
                        .done(function() {
                        
                            $('#menu_button').prop('disabled' ,true);
                            
                            let tree = $('#tree').fancytree('getTree');
                            let node = tree.getActiveNode();
                                                                         
                            masterTable.setData("../../api/{{$repository->getConfig()->_service->url}}/d31b93cf956350ee05030203dbaeb11022ac7320/" + node.key + "/_material");
                        
                        })
                        
                        .fail(function(xhr) {
                        
                            alertException(xhr);
                        });
                    
                }
            });
        
        });
  
                 
    });
    
  
</script>
    
  </head>
  <body class="bg-transparent">
  

  
    <div class="container pt-3 bg-white border-left border-right" style="border-color:var(--skyblue)">

        <nav class="navbar navbar-expand-lg navbar-light text-white" style="background-color:var(--skyblue)">
            <a class="navbar-brand text-white" href="#"><i class="mdi mdi-palette-swatch-variant"></i> Materialstamm</a>
        </nav>

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

            <button type="button" class="btn" style="color:white !important; background-color:var(--skyblue); opacity:1" disabled=""><i class="mdi mdi-menu"></i></button>

            <div class="btn-group" role="group">
                <div class="btn-group" role="group">
                    <button class="btn dropdown-toggle" type="button" style="background-color:var(--skyblue); color:white !important;" data-toggle="dropdown">
                       Verzeichnis
                    </button>
                    <div class="dropdown-menu">
                        <button class="dropdown-item" id="add_folder">Neues Verzeichnis</button>
                        <button class="dropdown-item folder_detail" id="edit_folder" disabled>Verzeichnis bearbeiten</button>
                        <button class="dropdown-item folder_detail" id="drop_folder" disabled>Verzeichnis löschen</button>
                    </div>
                    <button type="button" class="btn" style="background-color:var(--skyblue); color:white !important;" id="add_material">Neues Material anlegen</button>
                </div>

            </div>
        </div>

        <div class="row">
            <div class="col col-3 mt-3">
            



                <div id="tree" class="mt-3">
                        <ul>
                            
                        <?php
                        
                        $tree = \App\Models\PHPXPress\HwplusMaterialMasterFolders::where('materialized_depth', 0)->first()->getDescendantsAndSelf()->toHierarchy();
                        
                        function test($row) {
                        
                            if(0 == $row->materialized_depth) echo '<li class="active focus expanded" id="'.$row->getKey().'">'.$row->descriptor;
                            else echo '<li class="" id="'.$row->getKey().'">'.$row->descriptor;
                            
                        
                            if($row->children->count()) {
                                echo "<ul>"; 
                                foreach($row->children->sortBy('descriptor') AS $child) test($child); 
                                echo "</ul>";
                            }
                        
                            echo "</li>";
                        }
                        
                        test($tree->first());
                        
                        ?>
                        </ul>     
                </div>
            </div>
            <div class="col col-9 mt-3">

                <table id="mastertable" class="mt-3"></table>
            </div>
        </div>
    </div>
  </body>
  
  <script>
  
    function replace(value) {
        return value.replace(/[^\d,]+/g, '')
    }
  
    var netpriceEditor = function(cell, onRendered, success, cancel, editorParams){
        //cell - the cell component for the editable cell
        //onRendered - function to call when the editor has been rendered
        //success - function to call to pass thesuccessfully updated value to Tabulator
        //cancel - function to call to abort the edit and return to a normal cell
        //editorParams - params object passed into the editorParams column definition property

        //create and style editor
        var editor = document.createElement("input");
        


        editor.setAttribute("type", "input");
        editor.setAttribute("onkeyup", "this.value = replace(this.value)");

        //create and style input
        editor.style.padding = "3px";
        editor.style.width = "100%";
        editor.style.boxSizing = "border-box";

        //Set value of editor to the current value of the cell
        //editor.value = luxon.DateTime.fromFormat(cell.getValue(), "dd/MM/yyyy").toFormat("yyyy-MM-dd")
        editor.value = cell.getValue();

        //set focus on the select box when the editor is selected (timeout allows for editor to be added to DOM)
        onRendered(function(){
            editor.focus();
            editor.style.css = "100%";
        });

        //when the value has been set, trigger the cell to update
        function successFunc(){
            //success(luxon.DateTime.fromFormat(cell.getValue(), "yyyy-MM-dd").toFormat("dd/MM/yyyy"));
            success(editor.value);
        }

        editor.addEventListener("change", successFunc);
        editor.addEventListener("blur", successFunc);

        //return the editor element
        return editor;
    };

    var masterTable = new Tabulator("#mastertable", {
        movableRows:true,
        layout:"fitColumns",
        selectable: 1,
        rowHeight:80,
        initialSort:[{column:'_material_at_material_master_folders_order', dir:'asc'}],
        columns:[ //set column definitions for imported table data
            {title:"ID", field:'ID', visible:false, sorter:"number"},
            {formatter:"rowSelection", align:"center", headerSort:false, width:10, visible:false},
            {title:"Pos.", field:'_material_at_material_master_folders_order', visible:true, sorter:'number', width:10},
            {title:"Bezeichnung", field:'descriptor', visible:true, sorter:'string', editor:"textarea", formatter:"textarea"},
            {title:'VPE', field:'_unit', visible:true, editor:'list', width:100, hozAlign:"right", headerHozAlign:"right",
                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:'MwSt', field:'_vat', visible:true, editor:'list', width:50, hozAlign:"right", headerHozAlign:"right",
                editorParams: {
                    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:'netprice', visible:true, editor:netpriceEditor, width:100, hozAlign:"right", headerHozAlign:"right", formatter:function(cell, formatterParams, onRendered) {
                    return formatPrice(cell.getValue());

            }},
            {title:'', field:'', visible:true, hozAlign:"right", headerHozAlign:"right", width:80, formatter:function() { return '<button type="button" class="btn btn-danger btn-sm" id="drop_material_button"><i class="bi bi-x-circle"></button>'; }}
        ],
    });
    
    masterTable.on("tableBuilt", function(){
    
        masterTable.setData("../../api/{{$repository->getConfig()->_service->url}}/d31b93cf956350ee05030203dbaeb11022ac7320/7f605b6656421d0ea289395c126c23219796d8ac/_material");
    
    });
    
    masterTable.on("rowSelected", function(row){
        //row - row component for the selected row
        $('#menu_button').prop("disabled",false);
    });
    
    masterTable.on("rowDeselected", function(row){
        //row - row component for the selected row
        $('#menu_button').prop("disabled",true);
    });
    
    masterTable.on("rowMoved", function(row) {
    
            $('#spinner').removeClass('d-none');
    
            let postData = {
                _token:'{{csrf_token()}}',
                _method: 'PUT',
                data: {}
            }
            
            let tree = $('#tree').fancytree('getTree');
            let node = tree.getActiveNode();
            
            postData.data['_material_at_material_master_folders_order'] = row.getPosition();
            
            $.post("../../../api/{{$repository->getConfig()->_service->url}}/5a7dfc613be971ac442fff63b73ecd1b2ebd9594/" + row.getData().ID, postData)
                
                .done(function(data) {
                
                    $('#spinner').addClass('d-none');
                    masterTable.setData("../../api/{{$repository->getConfig()->_service->url}}/d31b93cf956350ee05030203dbaeb11022ac7320/" + node.key + "/_material");
                
                })
                
                .fail(function(xhr) {
                
                    $('#spinner').addClass('d-none');
                
                    alertException(xhr);  
                });
        
    
    });
    
    masterTable.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}}/5a7dfc613be971ac442fff63b73ecd1b2ebd9594/" + 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('../96f9fdfcc3a5c85884c6fb1e16b99f9952fdd499'),
                title:'Neues Material',
                type:BootstrapDialog.TYPE_LIGHT,
                buttons: [{
                    label: 'Speichern',
                    cssClass:'btn-success',
                    action: function(dialogItself){
                    
                        $('#spinner').removeClass('d-none');
                    
                        let tree = $('#tree').fancytree('getTree');
                        let node = tree.getActiveNode();
                        let id = node.key;
                        
                        $('input[name="data[_material_at_material_master_folders]"]').val(id);
                        
                        let postData = $('#new_material').serialize();
                    
                        postData._token = '{{csrf_token()}}';
                        
                        $.post("../../api/{{$repository->getConfig()->_service->url}}/5a7dfc613be971ac442fff63b73ecd1b2ebd9594/96f9fdfcc3a5c85884c6fb1e16b99f9952fdd499", postData)
                        
                        .done(function(data) {
                            $('#spinner').addClass('d-none');
                            masterTable.addData(data);
                            dialogItself.close();
                        })
                        
                        .fail(function(xhr, status, error) {
                        
                            $('#spinner').addClass('d-none');
                            
                            if(422 == xhr.status) {
                                $('#new_material').find('.is-invalid').removeClass('is-invalid');
                                $.each(xhr.responseJSON, function(index, item) {
                                    let array = index.split('.');
                                    $('#new_material').find('[name="data['+array[1]+']"]').addClass('is-invalid'); 
                                });
                            
                            
                            }

                            else { 
                            
                                alertException(xhr);
                            }
                        
                        });
                    
                    }
                }, {
                    label: 'Abbrechen',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }]
            });
    
    })
    
  
  </script>
</html>
