@extends ('layouts/template')
@section('content')
    <?php
    $multiProView = !!request()->input('multi-pro');
    $multiPros = [];
    if(request()->input('multi-pro-uids')) {
        $uids = explode(',', request()->input('multi-pro-uids'));
        foreach ($uids as $uid) {
            $multiPro = \App\Models\Pro::where('uid', $uid)->first();
            if($multiPro) {
                $multiPros[] = $multiPro;
            }
        }
    }
    ?>
    <link rel="stylesheet" href="/jstree/themes/default/style.min.css" />
    <script src="/jstree/jstree.min.js"></script>
    <div class="mcp-theme-1">
        <div class="card border-0 rounded-0 d-flex flex-column body-height">
            <div class="card-header px-2 py-3 bg-aliceblue">
                <div class="d-flex align-items-center">
                    <a href="{{route('practice-management.statTrees.list')}}" class="small text-decoration-none mr-3">
                        <i class="fa fa-chevron-left"></i>
                    </a>
                    <div class="mr-3">
                        <span>Name:</span>
                        <span class="font-weight-bold" title="Slug: {{ $statTree->slug }}">{{ $statTree->name }}</span>
                    </div>
                    <div class="mr-3 d-inline-flex">
                        <span class="mr-1">Model:</span>
                        <span class="font-weight-bold max-width-200px overflow-hidden text-ellipsis" title="{{ $statTree->model }}">{{ $statTree->model }}</span>
                    </div>
                    @if($statTree->pro_id)
                        <div class="mr-3">
                            <span>Pro:</span>
                            <span class="font-weight-bold" title="Clause: {{ $statTree->pro_scope_clause }}">{{ $statTree->pro->displayName() }}</span>
                        </div>
                    @endif
                    <div moe relative wide class="">
                        <a href="#" start show class=""><i class="fa fa-edit on-hover-opaque"></i></a>
                        <form url="{{ route("practice-management.api.statTree.updateBasic") }}">
                            @csrf
                            <input type="hidden" name="uid" value="{{$statTree->uid}}">
                            <div class="mb-2">
                                <label class="text-secondary text-sm mb-1">Name *</label>
                                <input type="text" class="form-control form-control-sm" name="name" value="{{$statTree->name}}" autofocus required>
                            </div>
                            <div class="mb-2">
                                <label class="text-secondary text-sm mb-1">Model *</label>
                                <input type="text" class="form-control form-control-sm" data-option-list="model-options" autocomplete="off" name="model" value="{{$statTree->model}}" required>
                                <div id="model-options" class="data-option-list">
                                    <?php $models = \Illuminate\Support\Facades\DB::select('SELECT distinct(model) as m FROM clause order by model'); ?>
                                    @foreach($models as $m)
                                        <div>{!! $m->m !!}</div>
                                    @endforeach
                                </div>
                            </div>
                            <div class="mb-2">
                                <label class="text-secondary text-sm mb-1">Slug *</label>
                                <input type="text" class="form-control form-control-sm" name="slug" value="{{$statTree->slug}}" required>
                            </div>
                            <label class="my-3 d-flex align-items-center">
                                <span class="mr-2">Is Template?</span>
                                <input type="checkbox" name="isTemplate" {{@$statTree->is_template ? 'checked' : ''}}>
                            </label>
                            <div class="mb-2">
                                <label class="text-secondary text-sm mb-1">Pro</label>
                                <select name="proUid" class="form-control input-sm" provider-search provider-type="hcp" data-pro-uid="{{ @$statTree->pro->uid }}">
                                    <option value="">--select--</option>
                                </select>
                            </div>
                            <div class="mb-2">
                                <label class="text-secondary text-sm mb-1">Pro Scope Clause</label>
                                <input type="text" class="form-control form-control-sm" name="proScopeClause" value="{{@$statTree->pro_scope_clause}}">
                            </div>
                            <div class="d-flex align-items-center">
                                <button class="btn btn-sm btn-primary mr-2" type="button" submit>Save</button>
                                <button class="btn btn-sm btn-default mr-2 border" type="button" cancel>Cancel</button>
                            </div>
                        </form>
                    </div>
                    @if(!$multiProView)
                        <a href="{{ route('practice-management.statTrees.view.edit', $statTree) }}?multi-pro=1" class="text-decoration-none font-weight-bold text-primary ml-auto">
                            <i class="fa fa-users mr-1"></i>
                            Multi-Pro View
                        </a>
                    @else
                        <a href="{{ route('practice-management.statTrees.view.edit', $statTree) }}" class="text-decoration-none font-weight-bold text-primary ml-auto">
                            <i class="fa fa-edit mr-1"></i>
                            Edit View
                        </a>
                    @endif
                </div>
            </div>
            <div class="card-body p-0 flex-grow-1">
                <div id="statTreeEdit-{{$statTree->id}}" class="row m-0 h-100 stat-tree {{$multiProView ? 'multi-pro-view' : ''}}">

                    <!-- clauses -->
                    <div class="col-3 p-0 h-100 clauses-column overflow-auto">

                        <div class="d-flex flex-column h-100">
                            <div class="d-flex align-items-center pl-2 height-35px border-bottom bg-light">
                                <h6 class="font-weight-bold m-0 text-secondary">Available Clauses</h6>
                                <div moe center wide class="ml-3">
                                    <a href="#" start show>+ Add</a>
                                    <form url="{{ route("practice-management.api.clause.create") }}" class="frm-clause-add-edit" hook="reloadClausesTree">
                                        @csrf
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Model</label>
                                            <input type="text" class="form-control form-control-sm" name="model" readonly value="{{$statTree->model}}">
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Question</label>
                                            <input type="text" class="form-control form-control-sm" name="question" autofocus>
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Answer</label>
                                            <input type="text" class="form-control form-control-sm" name="answer">
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Label</label>
                                            <input type="text" class="form-control form-control-sm" name="label" readonly>
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Clause Text</label>
                                            <textarea type="text" class="form-control form-control-sm" name="clauseText"></textarea>
                                        </div>
                                        <div class="d-flex align-items-center">
                                            <button class="btn btn-sm btn-primary mr-2" type="button" submit>Save</button>
                                            <button class="btn btn-sm btn-default mr-2 border" type="button" cancel>Cancel</button>
                                        </div>
                                    </form>
                                </div>
                                <a href="#" class="clause-expand-all ml-3" title="Expand All"><i class="fa fa-angle-double-down text-secondary"></i></a>
                                <a href="#" class="clause-collapse-all ml-2" title="Collapse All"><i class="fa fa-angle-double-up text-secondary"></i></a>
                            </div>
                            <div class="flex-grow-1 overflow-auto overflow-x-scroll pl-1">
                                <div class="clauses-view pb-5" id="clauses-view-{{$statTree->id}}"></div>
                            </div>
                        </div>

                        <!-- hidden moes invoked due to context actions -->
                        <div class="border mb-3 p-2 position-absolute" style="left: -10000px; top: -10000px;">
                            <div class="d-inline-flex align-items-baseline">

                                <!-- edit clause -->
                                <div moe center relative wide class="ml-3 mr-2" id="edit-clause-moe">
                                    <a href="#" start show><i class="text-sm fa fa-edit on-hover-opaque"></i></a>
                                    <form url="{{ route("practice-management.api.clause.update") }}" class="frm-clause-add-edit" center hook="reloadClausesTree">
                                        @csrf
                                        <input type="hidden" name="uid">
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Model</label>
                                            <input type="text" class="form-control form-control-sm" name="model" readonly>
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Question</label>
                                            <input type="text" class="form-control form-control-sm" name="question">
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Answer</label>
                                            <input type="text" class="form-control form-control-sm" name="answer">
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Label</label>
                                            <input type="text" class="form-control form-control-sm" name="label" readonly>
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Clause Text</label>
                                            <textarea type="text" class="form-control form-control-sm" name="clauseText"></textarea>
                                        </div>
                                        <div class="d-flex align-items-center">
                                            <button class="btn btn-sm btn-primary mr-2" type="button" submit>Save</button>
                                            <button class="btn btn-sm btn-default mr-2 border" type="button" cancel>Cancel</button>
                                        </div>
                                    </form>
                                </div>

                                <!-- remove clause -->
                                <div moe relative center id="remove-clause-moe">
                                    <a href="#" start show><i class="text-sm fa fa-trash-alt on-hover-opaque text-danger"></i></a>
                                    <form url="{{ route("practice-management.api.clause.remove") }}" center hook="reloadClausesTree">
                                        @csrf
                                        <input type="hidden" name="uid">
                                        <p>Are you sure?</p>
                                        <div class="d-flex align-items-center">
                                            <button class="btn btn-sm btn-danger mr-2" type="button" submit>Remove</button>
                                            <button class="btn btn-sm btn-default mr-2 border" type="button" cancel>Cancel</button>
                                        </div>
                                    </form>
                                </div>

                                <!-- add clause arg -->
                                <div moe relative center id="add-clause-arg-moe">
                                    <a href="#" start show><i class="text-sm fa fa-trash-alt on-hover-opaque text-danger"></i></a>
                                    <form url="{{ route("practice-management.api.clauseArg.create") }}" center hook="reloadClausesTree">
                                        @csrf
                                        <input type="hidden" name="clauseId">
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Arg Text</label>
                                            <input type="text" class="form-control form-control-sm" name="argText" required>
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Field Type</label>
                                            <select class="form-control form-control-sm" name="fieldType" required>
                                                <option value="">-- select --</option>
                                                <option value="numeric">Number</option>
                                                <option value="date">Date</option>
                                                <option value="text">String</option>
                                                <option value="bool">Boolean</option>
                                            </select>
                                        </div>
                                        <div class="d-flex align-items-center">
                                            <button class="btn btn-sm btn-primary mr-2" type="button" submit>Save</button>
                                            <button class="btn btn-sm btn-default mr-2 border" type="button" cancel>Cancel</button>
                                        </div>
                                    </form>
                                </div>

                                <!-- edit clause arg -->
                                <div moe relative center id="edit-clause-arg-moe">
                                    <a href="#" start show><i class="text-sm fa fa-trash-alt on-hover-opaque text-danger"></i></a>
                                    <form url="{{ route("practice-management.api.clauseArg.update") }}" center hook="reloadClausesTree">
                                        @csrf
                                        <input type="hidden" name="id">
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Arg Text</label>
                                            <input type="text" class="form-control form-control-sm" name="argText" required>
                                        </div>
                                        <div class="mb-2">
                                            <label class="text-secondary text-sm mb-1">Field Type</label>
                                            <select class="form-control form-control-sm" name="fieldType" required>
                                                <option value="">-- select --</option>
                                                <option value="numeric">Number</option>
                                                <option value="date">Date</option>
                                                <option value="text">String</option>
                                                <option value="bool">Boolean</option>
                                            </select>
                                        </div>
                                        <div class="d-flex align-items-center">
                                            <button class="btn btn-sm btn-primary mr-2" type="button" submit>Save</button>
                                            <button class="btn btn-sm btn-default mr-2 border" type="button" cancel>Cancel</button>
                                        </div>
                                    </form>
                                </div>

                                <!-- remove clause arg -->
                                <div moe relative center id="remove-clause-arg-moe">
                                    <a href="#" start show><i class="text-sm fa fa-trash-alt on-hover-opaque text-danger"></i></a>
                                    <form url="{{ route("practice-management.api.clauseArg.remove") }}" center hook="reloadClausesTree">
                                        @csrf
                                        <input type="hidden" name="id">
                                        <p>Are you sure?</p>
                                        <div class="d-flex align-items-center">
                                            <button class="btn btn-sm btn-danger mr-2" type="button" submit>Remove</button>
                                            <button class="btn btn-sm btn-default mr-2 border" type="button" cancel>Cancel</button>
                                        </div>
                                    </form>
                                </div>


                            </div>
                        </div>

                    </div>


                    <!-- tree -->
                    <div class="col-9 p-0 h-100 border-left tree-column overflow-auto">
                        <div class="row m-0 h-100">
                            <div class="{{$multiProView ? 'col-12' : 'col-6'}} tree-lhs-column border-right h-100 p-0">
                                <div class="d-flex flex-column h-100">
                                    <div class="d-flex align-items-center pl-2 height-35px border-bottom bg-light tree-column-header">
                                        <h6 class="font-weight-bold m-0 text-secondary">{{$statTree->name}}</h6>
                                        <span class="text-danger d-none if-changed ml-2 text-sm">(modified *)</span>
                                        @if($multiProView)
                                            <div moe class="ml-3">
                                                <a href="#" start show>Add Pro</a>
                                                <div url="/nop">
                                                    <div class="mb-2">
                                                        <select id="proUid" class="form-control input-sm" provider-search provider-type="hcp">
                                                            <option value="">--select--</option>
                                                        </select>
                                                    </div>
                                                    <div class="d-flex align-items-center">
                                                        <button class="btn btn-sm btn-primary mr-2 btn-add-pro" type="button">Add</button>
                                                        <button class="btn btn-sm btn-default mr-2 border" type="button" cancel>Cancel</button>
                                                    </div>
                                                </div>
                                            </div>
                                        @endif
                                        <a href="#" id="refresh-counts" class="ml-3">Refresh Counts</a>
                                        <a href="#" class="tree-expand-all ml-3" title="Expand All"><i class="fa fa-angle-double-down text-secondary"></i></a>
                                        <a href="#" class="tree-collapse-all ml-2" title="Collapse All"><i class="fa fa-angle-double-up text-secondary"></i></a>
                                        <a href="#" id="paste-as-root" class="ml-3">Paste as root</a>
                                        <input type="text" id="paste-container" style="position: fixed; top: 0; left: 0;">
                                        <div class="ml-auto mr-2 d-none if-changed">
                                            <a href="#" class="btn btn-sm btn-primary text-white" id="btn-save-tree">Save</a>
                                            <a href="#" class="ml-1 btn btn-sm btn-default border text-dark bg-white" onclick="return fastReload()">Reset</a>
                                        </div>
                                    </div>
                                    <div class="flex-grow-1 overflow-overlay-on-hover">
                                        @if(!$multiProView)
                                            <div class="stat-tree-view overflow-auto min-height-300px" id="stat-tree-edit-{{$statTree->id}}"></div>
                                        @else
                                            <div class="d-flex align-items-start h-100">
                                                <div class="mv-tree overflow-auto h-100 d-inline-flex flex-column">
                                                    <div class="multi-pro-view-stat-label">Stat</div>
                                                    <div class="stat-tree-view overflow-auto overflow-x-scroll flex-grow-1" id="stat-tree-edit-{{$statTree->id}}"></div>
                                                </div>
                                                <div class="overflow-auto overflow-x-scroll mv-table h-100">
                                                    <table class="table table-sm multi-pro-stats-table w-auto m-0">
                                                        <thead>
                                                        <tr>
                                                            <th {{$statTree->pro ? 'data-pro-uid="' . $statTree->pro->uid . '"' : ''}}>
                                                                <div class="pro-label" title="{{$statTree->pro ? $statTree->pro->name_display : 'Total'}}">{{$statTree->pro ? $statTree->pro->name_display : 'Total'}}</div>
                                                            </th>
                                                            @foreach($multiPros as $multiPro)
                                                                <th data-pro-uid="{{$multiPro->uid}}" count-required>
                                                                    <div class="pro-label position-relative" title="{{$multiPro->name_display ?: $multiPro->name_first}}">{{$multiPro->name_display ?: $multiPro->name_first}}
                                                                        <a href="#" class="mv-delete-pro-trigger rounded-circle bg-white c-pointer" data-pro-uid="{{$multiPro->uid}}"><i class="fa fa-times text-danger"></i></a>
                                                                    </div>
                                                                </th>
                                                            @endforeach
                                                        </tr>
                                                        </thead>
                                                        <tbody>
                                                        @foreach($linesFlat as $line)
                                                            <tr data-line-uid="{{$line->uid}}" {!! $line->parent ? 'data-parent-line-uid="' . $line->parent->uid . '"' : '' !!}>
                                                                <td class="p-0 on-hover-aliceblue c-pointer mv-view-data-trigger">
                                                                    <div class="count-label">
                                                                        <div class="count">{{$line->last_refresh_count}}</div>
                                                                        <div class="drop-percent"></div>
                                                                    </div>
                                                                </td>
                                                                @foreach($multiPros as $multiPro)
                                                                    <td class="p-0 on-hover-aliceblue c-pointer mv-view-data-trigger" data-pro-uid="{{$multiPro->uid}}">
                                                                        <div class="count-label">
                                                                            <div class="count"></div>
                                                                            <div class="drop-percent"></div>
                                                                        </div>
                                                                    </td>
                                                                @endforeach
                                                            </tr>
                                                        @endforeach
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        @endif
                                    </div>
                                </div>
                            </div>
                            @if(!$multiProView)
                                <!-- selected line properties -->
                                <div class="col-6 tree-rhs-column h-100 p-0">
                                    <div class="h-100 setup-column d-none" id="line-properties-column">
                                        <div class="d-flex flex-column h-100">
                                            <div class="d-flex align-items-center pl-2 height-35px border-bottom bg-light">
                                                <h6 class="font-weight-bold m-0 text-secondary">Selected Line Properties</h6>
                                            </div>
                                            <div class="flex-grow-1 overflow-overlay-on-hover">
                                                <div class="mb-3 d-flex align-items-baseline p-2 border-bottom font-weight-bold">
                                                    <span line-label></span>
                                                    <div class="ml-3 pl-3 border-left d-inline-flex align-items-baseline">
                                                        <span class="mr-1 font-weight-normal">Goal:</span>
                                                        <span line-goal class="mr-2"></span>
                                                        <a href="#" class="btn-edit-goal"><i class="fa fa-edit"></i></a>
                                                    </div>
                                                </div>
                                                <div class="d-flex align-items-baseline mb-2 px-2">
                                                    <h6 class="font-weight-bold m-0 text-secondary">Argument Values</h6>
                                                    <!--<a href="#" class="ml-3 text-sm" onclick="$('.parent-arg').toggle(); return false;">Toggle Parent Clause Args</a>-->
                                                </div>
                                                <div class="px-2">
                                                    <table class="table table-sm table-bordered table-striped">
                                                        <thead>
                                                        <tr>
                                                            <th class="border-bottom-0 w-35">Arg</th>
                                                            <th class="border-bottom-0 w-35">Value</th>
                                                            <th class="border-bottom-0">Access</th>
                                                        </tr>
                                                        </thead>
                                                        <tbody line-args>
                                                        </tbody>
                                                    </table>
                                                </div>
                                                <div class="d-flex align-items-baseline mb-2 border-top pt-3 px-2">
                                                    <h6 class="font-weight-bold m-0 text-secondary">Report Columns</h6>
                                                </div>
                                                <div class="px-2">
                                                    <form class="border p-2">
                                                        <div class="mb-1 d-flex align-items-baseline">
                                                            <span class="text-secondary mr-1 text-nowrap width-70px">Label:</span>
                                                            <div class="flex-grow-1 position-relative">
                                                                <input required type="text"
                                                                       name="label"
                                                                       class="form-control form-control-sm">
                                                            </div>
                                                        </div>
                                                        <div class="mb-1 d-flex align-items-baseline">
                                                            <span class="text-secondary mr-1 text-nowrap width-70px">Column:</span>
                                                            <div class="flex-grow-1 position-relative">
                                                                <input required type="text"
                                                                       name="display_key"
                                                                       class="form-control form-control-sm"
{{--                                                                       stag-suggest stag-suggest-left--}}
{{--                                                                       stag-suggest-ep="/column-suggest"--}}
{{--                                                                       stag-suggest-extra="table={{$statTree->model}}"--}}
                                                                       autocomplete="off">
                                                            </div>
                                                        </div>
                                                        <div class="mb-1 d-flex align-items-baseline">
                                                            <span class="text-secondary mr-1 text-nowrap width-70px">Type:</span>
                                                            <div class="flex-grow-1 position-relative">
                                                                <select required class="form-control form-control-sm min-width-unset" name="type" required>
                                                                    <option value="">-- select --</option>
                                                                    <option value="numeric">Number</option>
                                                                    <option value="date">Date</option>
                                                                    <option value="text">String</option>
                                                                    <option value="bool">Boolean</option>
                                                                </select>
                                                            </div>
                                                        </div>
                                                        <div class="mb-1 d-flex align-items-baseline">
                                                            <span class="text-secondary mr-1 text-nowrap width-70px"></span>
                                                            <div class="flex-grow-1 position-relative">
                                                                <button class="btn btn-sm btn-primary add-column">Add Column</button>
                                                            </div>
                                                        </div>
                                                    </form>
                                                    <table class="table table-sm table-bordered table-striped">
                                                        <thead>
                                                        <tr>
                                                            <th class="border-bottom-0 width-30px">#</th>
                                                            <th class="border-bottom-0 w-35">Label</th>
                                                            <th class="border-bottom-0">Column</th>
                                                            <th class="border-bottom-0">Type</th>
                                                            <th class="border-bottom-0 width-60px"></th>
                                                        </tr>
                                                        </thead>
                                                        <tbody line-columns>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            @endif
                        </div>
                    </div>

                </div>
                <script>
                    (function() {
                        function init() {

                            let linePropsColumn = $('#line-properties-column'),
                                multiViewPros = [];

                            @if(request()->input('multi-pro-uids'))
                                multiViewPros = '{{request()->input('multi-pro-uids')}}'.split(',');
                            @endif

                            function fillAndInvokeMoe(_id, _node) {
                                let moe = $(_id);
                                moe.find('input[name], select[name], textarea[name]').each(function() {
                                    let name = $(this).attr('name');
                                    if(!!_node.data[name]) {
                                        $(this).val(!!_node.data[name] ? _node.data[name] : '');
                                    }
                                });
                                moe.find('a[start]').trigger('click');
                            }

                            // clauses tree
                            let ClausesTree = {
                                el: $('#clauses-view-{{$statTree->id}}'),
                                load: function() {

                                    // destroy if existing
                                    try {
                                        this.el.jstree('destroy');
                                    }
                                    catch (e) {}

                                    // get data
                                    $.get('{{ route('practice-management.statTrees.view.clausesJSON', $statTree) }}', _data => {

                                        // init tree with data
                                        this.el
                                            .jstree({
                                                "core": {
                                                    "multiple": false,
                                                    "animation": 0,
                                                    'data': _data
                                                },
                                                "dnd": {
                                                    "is_draggable": function(_node, _e) {
                                                        return _node[0].data.type === 'clause';
                                                    }
                                                },
                                                "contextmenu": {
                                                    show_at_node: false,
                                                    items: function (node) {
                                                        if(node.data.type === 'clause') { // clause
                                                            return {
                                                                "edit": {
                                                                    "label": "<span class='text-sm'>Edit Clause</span>",
                                                                    "action": function (obj) {
                                                                        fillAndInvokeMoe('#edit-clause-moe', node);
                                                                    }
                                                                },
                                                                "remove": {
                                                                    "label": "<span class='text-sm'>Remove Clause</span>",
                                                                    "action": function (obj) {
                                                                        fillAndInvokeMoe('#remove-clause-moe', node);
                                                                    }
                                                                },
                                                                "add_arg": {
                                                                    "label": "<span class='text-sm'>Add Clause Arg</span>",
                                                                    "action": function (obj) {
                                                                        fillAndInvokeMoe('#add-clause-arg-moe', node);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else if(node.data.type === 'clause_arg') { // clause
                                                            return {
                                                                "edit": {
                                                                    "label": "<span class='text-sm'>Edit Arg</span>",
                                                                    "action": function (obj) {
                                                                        fillAndInvokeMoe('#edit-clause-arg-moe', node);
                                                                    }
                                                                },
                                                                "remove": {
                                                                    "label": "<span class='text-sm'>Remove Arg</span>",
                                                                    "action": function (obj) {
                                                                        fillAndInvokeMoe('#remove-clause-arg-moe', node);
                                                                    }
                                                                }
                                                            };
                                                        }
                                                    },
                                                },
                                                "plugins": [
                                                    "wholerow",
                                                    "dnd",
                                                    "contextmenu",
                                                    "state"
                                                ]
                                            });
                                    }, 'json');
                                }
                            };

                            @if($multiProView)
                            (function ($, undefined) {
                                "use strict";
                                $.jstree.plugins.noclose = function () {
                                    this.close_node = $.noop;
                                };
                            })(jQuery);
                            @endif

                            // stat tree
                            let StatTree = {
                                el: $('#stat-tree-edit-{{$statTree->id}}'),
                                changed: false,
                                copiedColumns: null,

                                setDirty: function(_changed = true) {
                                    this.changed = _changed;
                                    if(_changed) {
                                        $('.if-changed').removeClass('d-none');
                                        $('.tree-column-header').addClass('has-changes');
                                    }
                                    else {
                                        $('.if-changed').addClass('d-none');
                                        $('.tree-column-header').removeClass('has-changes');
                                    }
                                },

                                load: function() {

                                    // destroy if existing
                                    try {
                                        this.el.jstree('destroy');
                                    }
                                    catch (e) {}

                                    this.el = $('#stat-tree-edit-{{$statTree->id}}');

                                    // get data
                                    showMask();
                                    $.get('{{ route('practice-management.statTrees.view.linesJSON', $statTree) }}', _data => {

                                        // init tree with data
                                        this.el
                                            .on('move_node.jstree', (_e, _data) => { StatTree.dropped(_e, _data); })
                                            .on('copy_node.jstree', (_e, _data) => { StatTree.dropped(_e, _data); })
                                            .on('select_node.jstree', () => { StatTree.onSelected(); })
                                            .on('deselect_node.jstree', () => { StatTree.onDeselected(); })
                                            @if(!$multiProView)
                                            .on('redraw.jstree', () => { StatTree.dropVisualize(); })
                                            @endif
                                            .jstree({
                                                "core": {
                                                    @if(!$multiProView)
                                                    "check_callback": true,
                                                    @endif
                                                    "multiple": false,
                                                    "animation": 0,
                                                    'data': _data
                                                },
                                                @if(!$multiProView)
                                                "dnd": {
                                                    "is_draggable": function(_node, _e) {
                                                        return _node[0].data && _node[0].data.type === 'stat_tree_line';
                                                    },
                                                    "inside_pos": "last",
                                                },
                                                "contextmenu": {
                                                    show_at_node: false,
                                                    items: function (node) {
                                                        if(node.data.type === 'stat_tree_line') { // stat_tree_line
                                                            return {

                                                                @if(!$multiProView)
                                                                "data": {
                                                                    "label": "<span class='text-sm'>View Data</span>",
                                                                    "action": function (obj) {
                                                                        openDynamicStagPopup('/practice-management/stat-tree-lines/view-data/' + node.data.uid,
                                                                            null,
                                                                            'View Data',
                                                                            false,
                                                                            'medium');
                                                                    },
                                                                    separator_after: true,
                                                                },
                                                                @endif

                                                                "cut": {
                                                                    "label": "<span class='text-sm'>Cut</span>",
                                                                    "action": function (obj) {
                                                                        let selected = StatTree.selectedNode();
                                                                        if(selected) {
                                                                            StatTree.el.jstree(true).cut(selected.id);
                                                                            StatTree.setDirty();
                                                                        }
                                                                    },
                                                                },
                                                                "copy": {
                                                                    "label": "<span class='text-sm'>Copy</span>",
                                                                    "action": function (obj) {
                                                                        let selected = StatTree.selectedNode();
                                                                        if(selected) {
                                                                            StatTree.el.jstree(true).copy(selected.id);

                                                                            // put into localStorage for paste_ext
                                                                            let node = StatTree.el.jstree(true).get_json(selected.id),
                                                                                json = JSON.stringify(StatTree.getPasteBufferForNode(node));
                                                                            localStorage.stPasteBuffer = json;
                                                                            copyTextToClipboard(json);
                                                                        }
                                                                    },
                                                                },
                                                                "paste": {
                                                                    "label": "<span class='text-sm'>Paste</span>",
                                                                    "_disabled": !StatTree.el.jstree(true).can_paste(),
                                                                    "action": function (obj) {
                                                                        let selected = StatTree.selectedNode();
                                                                        if(selected && StatTree.el.jstree(true).can_paste()) {
                                                                            StatTree.el.jstree(true).paste(selected.id, 'last');
                                                                            StatTree.setDirty();
                                                                        }
                                                                    },
                                                                },
                                                                "paste_ext": {
                                                                    "label": "<span class='text-sm'>Paste (external)</span>",
                                                                    "_disabled": !localStorage.stPasteBuffer,
                                                                    "action": function (obj) {
                                                                        let selected = StatTree.selectedNode();
                                                                        if(selected && !!localStorage.stPasteBuffer) {
                                                                            try {
                                                                                let parsed = JSON.parse(localStorage.stPasteBuffer);
                                                                                StatTree.el.jstree(true).create_node(selected.id, parsed);
                                                                                StatTree.el.jstree(true).open_node(selected.id);
                                                                                StatTree.setDirty();
                                                                            }
                                                                            catch (e) {
                                                                                console.error(e);
                                                                                console.error('Unable to paste. Invalid buffer.')
                                                                            }
                                                                        }
                                                                    },
                                                                    separator_after: true,
                                                                },
                                                                "copy_columns": {
                                                                    "label": "<span class='text-sm'>Copy Columns</span>",
                                                                    "_disabled": !(node.data && node.data.columns && node.data.columns.length),
                                                                    "action": function (obj) {
                                                                        let selected = StatTree.selectedNode();
                                                                        if(selected) {
                                                                            let json = JSON.stringify(selected.data.columns);
                                                                            localStorage.stPasteBuffer_Columns = json;
                                                                            copyTextToClipboard(json);
                                                                        }
                                                                    },
                                                                },
                                                                "paste_columns": {
                                                                    "label": "<span class='text-sm'>Paste Columns</span>",
                                                                    // "_disabled": !localStorage.stPasteBuffer_Columns,
                                                                    "action": function (obj) {
                                                                        let selected = StatTree.selectedNode();
                                                                        if(selected) {
                                                                            navigator.clipboard.readText().then(clipText => {
                                                                                // check if valid json
                                                                                try {
                                                                                    let parsed = JSON.parse(clipText);
                                                                                    StatTree.setSelectedNodeColumns(parsed);
                                                                                    StatTree.onSelected();
                                                                                    StatTree.setDirty();
                                                                                }
                                                                                catch (e) {
                                                                                    toastr.error('Invalid paste buffer!');
                                                                                }
                                                                            })
                                                                        }
                                                                    },
                                                                },
                                                                "paste_columns_deep": {
                                                                    "label": "<span class='text-sm'>Paste Columns Recursively</span>",
                                                                    // "_disabled": !localStorage.stPasteBuffer_Columns,
                                                                    "action": function (obj) {
                                                                        let selected = StatTree.selectedNode();
                                                                        if(selected) {
                                                                            navigator.clipboard.readText().then(clipText => {
                                                                                // check if valid json
                                                                                try {
                                                                                    let parsed = JSON.parse(clipText);
                                                                                    StatTree.pasteColumnsDeep(selected, clipText);
                                                                                    StatTree.onSelected();
                                                                                    StatTree.setDirty();
                                                                                }
                                                                                catch (e) {
                                                                                    toastr.error('Invalid paste buffer!');
                                                                                }
                                                                            })
                                                                        }
                                                                    },
                                                                    separator_after: true,
                                                                },
                                                                "remove": {
                                                                    "label": "<span class='text-sm'>Remove</span>",
                                                                    "action": function (obj) {
                                                                        let selected = StatTree.selectedNode();
                                                                        if(selected) {
                                                                            StatTree.el.jstree(true).delete_node(selected.id);
                                                                            StatTree.setDirty();
                                                                        }
                                                                    },
                                                                    separator_after: true,
                                                                },
                                                                "permutate_child_tree": {
                                                                    "label": "<span class='text-sm'>Create Child Permutations</span>",
                                                                    "action": function (obj) {
                                                                        let selected = StatTree.selectedNode();
                                                                        if(selected) {
                                                                            StatTree.createChildTreePermutations(selected);
                                                                            StatTree.setDirty();
                                                                        }
                                                                    }
                                                                },
                                                                "generate_all_us_states": {
                                                                    "label": "<span class='text-sm'>Replicate for all US states</span>",
                                                                    "_disabled": !StatTree.hasStateArg(node),
                                                                    "action": function (obj) {
                                                                        let selected = StatTree.selectedNode();
                                                                        if(selected) {
                                                                            StatTree.replicateForAllUSStates(selected);
                                                                            StatTree.setDirty();
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    },
                                                },
                                                @endif
                                                "plugins": [
                                                    "wholerow",
                                                    @if(!$multiProView)
                                                    "dnd",
                                                    "contextmenu",
                                                    @else
                                                    "noclose",
                                                    @endif
                                                    "state"
                                                ]
                                            });
                                    }, 'json').then(hideMask);
                                },

                                hasStateArg: function(_node) {
                                    if(_node.data.clause && _node.data.clause.args && _node.data.clause.args.length) {
                                        let matched = _node.data.clause.args.filter(_x => _x.arg_text === 'state' && _x.field_type === 'text');
                                        return !!(matched.length);
                                    }
                                    return false;
                                },

                                replicateForAllUSStates: function(_node) {
                                    let node = this.el.jstree(true).get_json(_node), parent = this.el.jstree(true).get_node(_node.parent);
                                    let states = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'];

                                    node = this.getPasteBufferForNode(node);

                                    // delete node
                                    this.el.jstree(true).delete_node(_node);

                                    // create new for each state
                                    for (let i = 0; i < states.length; i++) {
                                        let stateNode = JSON.parse(JSON.stringify(node));
                                        for (let j = 0; j < stateNode.data.clause.args.length; j++) {
                                            if(stateNode.data.clause.args[j].arg_text === 'state' && stateNode.data.clause.args[j].field_type === 'text') {
                                                stateNode.data.clause.args[j].value = states[i];
                                            }
                                        }
                                        stateNode.text = stateNode.text.replace(/state:\s[A-Z]{2}/g, 'state: ' + states[i]);
                                        stateNode.text = stateNode.text.replace(/\([0-9]+\)/g, '(…)');
                                        this.el.jstree(true).create_node(parent, stateNode, 'last');
                                    }

                                    this.setDirty();

                                },

                                createChildTreePermutations: function(_node) {

                                    // permute: thanks: https://stackoverflow.com/a/37580979/921204
                                    function _permute(permutation) {
                                        var length = permutation.length,
                                            result = [permutation.slice()],
                                            c = new Array(length).fill(0),
                                            i = 1, k, p;

                                        while (i < length) {
                                            if (c[i] < i) {
                                                k = i % 2 && c[i];
                                                p = permutation[i];
                                                permutation[i] = permutation[k];
                                                permutation[k] = p;
                                                ++c[i];
                                                i = 1;
                                                result.push(permutation.slice());
                                            } else {
                                                c[i] = 0;
                                                ++i;
                                            }
                                        }
                                        return result;
                                    }

                                    // ensure 1 child for selected node
                                    if(_node.children.length !== 1) {
                                        toastr.error('Line must have exactly one child!');
                                        return;
                                    }

                                    // ensure all nodes down the node in the tree have only one child (if any)
                                    function _hasSingleChild(_id) {
                                        let node = StatTree.el.jstree(true).get_node(_id);
                                        if(node.children.length === 0) return true; // no children
                                        if(node.children.length > 1) return false; // more than 1 child, stop already!
                                        return _hasSingleChild(node.children[0]);
                                    }
                                    if(!_hasSingleChild(_node.id)) {
                                        toastr.error('Single linear child tree structure needed under selected node!');
                                        return;
                                    }

                                    // get an array of line "data" of the child tree
                                    function _getData(_id, _dataArray, _displayLabelArray) {
                                        let node = StatTree.el.jstree(true).get_node(_id);
                                        _dataArray.push(node.data);
                                        _displayLabelArray.push(node.data.displayLabel);
                                        if(node.children.length) {
                                            _getData(node.children[0], _dataArray, _displayLabelArray);
                                        }
                                    }
                                    let dataArray = [], displayLabelArray = [];
                                    _getData(_node.children[0], dataArray, displayLabelArray);
                                    let dataMap = {};
                                    for (let i = 0; i < dataArray.length; i++) {
                                        dataMap[dataArray[i].displayLabel] = JSON.parse(JSON.stringify(dataArray[i]));
                                        delete dataMap[dataArray[i].displayLabel].dropPercent;
                                        delete dataMap[dataArray[i].displayLabel].id;
                                        delete dataMap[dataArray[i].displayLabel].lastRefreshCount;
                                        delete dataMap[dataArray[i].displayLabel].treeOrderPositionIndex;
                                        delete dataMap[dataArray[i].displayLabel].uid;
                                    }

                                    // get all permutations
                                    let permutations = _permute(displayLabelArray);

                                    // create child tree for each permutation
                                    function _childTreeFromArray(_array, _index = 0) {
                                        let children = [];
                                        if(_index < _array.length - 1) {
                                            children.push(_childTreeFromArray(_array, _index + 1));
                                        }
                                        return {
                                            text: '<span class="stat-tree-anchor">' + _array[_index] + '</span><span class="ml-2 text-secondary line-count-label">(…)</span>',
                                            state: {
                                                opened: true,
                                                disabled: false,
                                                selected: false,
                                            },
                                            children: children,
                                            data: {
                                                    type: "stat_tree_line",
                                                    displayLabel: _array[_index],
                                                    columns: dataMap[_array[_index]].columns,
                                                    clause: dataMap[_array[_index]].clause
                                            },
                                            a_attr: {
                                                title: dataMap[_array[_index]].clause.clause_text
                                            }
                                        };
                                    }

                                    // clear current children
                                    this.el.jstree(true).delete_node(_node.children[0]);

                                    // create new child trees
                                    for (let i = 0; i < permutations.length; i++) {
                                        let subTree = _childTreeFromArray(permutations[i]);
                                        this.el.jstree(true).create_node(_node.id, JSON.parse(JSON.stringify(subTree)));
                                    }

                                    this.setDirty();

                                },

                                pasteColumnsDeep: function(_node, _strColumns) {
                                    _node.data.columns = JSON.parse(_strColumns);
                                    for (let i = 0; i < _node.children.length; i++) {
                                        this.pasteColumnsDeep(this.el.jstree(true).get_node(_node.children[i]), _strColumns);
                                    }
                                },

                                dropVisualize: function() {
                                    function calculateDropPercent(node, parent = null) {
                                        let realNode = StatTree.el.jstree(true).get_node(node.id);
                                        if(!realNode.data) return;
                                        if(parent && parent.data.lastRefreshCount !== null && parent.data.lastRefreshCount !== -1) {
                                            if(node.data.lastRefreshCount !== null && node.data.lastRefreshCount !== -1) {
                                                realNode.data.dropPercent = ((node.data.lastRefreshCount / parent.data.lastRefreshCount) * 100);
                                                if(realNode.data.dropPercent) {
                                                    let element = StatTree.el.jstree(true).get_node(node.id, true), cssClass = '';
                                                    /*if(realNode.data.dropPercent > 75) {
                                                        cssClass = 'drop-76-100';
                                                    }
                                                    else if(realNode.data.dropPercent > 50 && realNode.data.dropPercent <= 75) {
                                                        cssClass = 'drop-51-75';
                                                    }
                                                    else if(realNode.data.dropPercent > 25 && realNode.data.dropPercent <= 50) {
                                                        cssClass = 'drop-26-50';
                                                    }
                                                    else if(realNode.data.dropPercent > 0 && realNode.data.dropPercent <= 25) {
                                                        cssClass = 'drop-0-25';
                                                    }*/
                                                    cssClass = 'drop-0-25';
                                                    element.find('>a.jstree-anchor')
                                                        .addClass('has-drop-visualization')
                                                        .addClass(cssClass)
                                                        .attr('data-drop-percent', (realNode.data.dropPercent.toFixed(3)) + '% ⤵');

                                                    if(!!realNode.data.goalCondition && realNode.data.goalPercent !== -1) {
                                                        let goalLabel = '';
                                                        switch(realNode.data.goalCondition) {
                                                            case '=':
                                                                if(realNode.data.dropPercent !== realNode.data.goalPercent) {
                                                                    goalLabel = 'Should be = ' + realNode.data.goalPercent + '%';
                                                                }
                                                                break;
                                                            case '>':
                                                                if(realNode.data.dropPercent <= realNode.data.goalPercent) {
                                                                    goalLabel = 'Should be > ' + realNode.data.goalPercent + '%';
                                                                }
                                                                break;
                                                            case '<':
                                                                if(realNode.data.dropPercent >= realNode.data.goalPercent) {
                                                                    goalLabel = 'Should be < ' + realNode.data.goalPercent + '%';
                                                                }
                                                                break;
                                                            case '>=':
                                                                if(realNode.data.dropPercent < realNode.data.goalPercent) {
                                                                    goalLabel = 'Should be >= ' + realNode.data.goalPercent + '%';
                                                                }
                                                                break;
                                                            case '<=':
                                                                if(realNode.data.dropPercent > realNode.data.goalPercent) {
                                                                    goalLabel = 'Should be <= ' + realNode.data.goalPercent + '%';
                                                                }
                                                                break;
                                                        }
                                                        if(!!goalLabel) {
                                                            element.find('>a.jstree-anchor')
                                                                .addClass('has-goal-label')
                                                                .attr('data-goal-label', '⚠ ' + goalLabel);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        for (let i = 0; i < node.children.length; i++) {
                                            calculateDropPercent(node.children[i], node);
                                        }
                                    }
                                    let raw = this.el.jstree('get_json');
                                    for (let i = 0; i < raw.length; i++) {
                                        calculateDropPercent(raw[i]);
                                    }
                                },

                                dropped: function(_e, _data) {

                                    if(_data.original && _data.original.data &&
                                        _data.original.data.type === 'clause') {
                                        _data.node.data = {
                                            type:  "stat_tree_line",
                                            displayLabel: _data.original.data.label,
                                            columns:  [],
                                            clause:  {
                                                clause_id: _data.original.data.clauseId,
                                                clause_label: _data.original.data.label,
                                                args: _data.original.data.args
                                            }
                                        };

                                        // delete args and query children (from the clauses tree)
                                        this.el.jstree(true).delete_node(_data.node.children);

                                        // open new parent to reveal dropped node
                                        this.el.jstree(true).open_node(_data.parent);

                                        // select the new node
                                        this.el.jstree(true).deselect_all();
                                        this.el.jstree(true).select_node(_data.node.id);
                                    }
                                    else if(_e.type === 'copy_node' && _data.original && _data.original.data &&
                                        _data.original.data.type === 'stat_tree_line') {

                                        function recursiveCopyData(src, target) {
                                            src = StatTree.el.jstree(true).get_node(src);
                                            target = StatTree.el.jstree(true).get_node(target);
                                            target.data = JSON.parse(JSON.stringify(src.data));
                                            if(src.children.length === target.children.length) {
                                                for (let i = 0; i < target.children.length; i++) {
                                                    recursiveCopyData(src.children[i], target.children[i])
                                                }
                                            }
                                            else {
                                                console.log('Child count not the same!', src.text, target.text);
                                            }
                                        }

                                        recursiveCopyData(_data.original.id, _data.node.id);

                                        // open new parent to reveal dropped node
                                        this.el.jstree(true).open_node(_data.parent);

                                        // select the new node
                                        this.el.jstree(true).deselect_all();
                                        this.el.jstree(true).select_node(_data.node.id);
                                    }

                                    this.setDirty();
                                },

                                save: function() {
                                    setTimeout(() => {
                                        $.post('{{ route("practice-management.api.statTree.replaceAllLinesJSON") }}', {
                                            _token: '{{ csrf_token() }}',
                                            uid: "{{ $statTree->uid }}",
                                            data: StatTree.payload()
                                        }, function (response) {
                                            if(!hasResponseError(response)) {
                                                toastr.success('All changes saved!');
                                                /*StatTree.setDirty(false);
                                                StatTree.load();*/
                                                fastReload();
                                            }
                                        }, 'json');
                                    }, 0);
                                },

                                log: function() {
                                    let raw = this.el.jstree('get_json');
                                    for (let i = 0; i < raw.length; i++) {
                                        this.logNode(raw[i].id, "");
                                    }
                                },

                                logNode: function(_id, _indent) {
                                    let node = this.el.jstree('get_node', _id);
                                    let s = [], css = false;
                                    if(!node.data) css = true;
                                    s.push($('<div/>').html(node.text).text().substr(0, 10) + '...');
                                    s.push(node.data ? 'data:' + node.data.type: '%cdata:X');
                                    console.log("ALIX: " + _indent + s.join('  '), css ? 'color:red' : '');
                                    for (let i = 0; i < node.children.length; i++) {
                                        this.logNode(node.children[i], _indent + "\t");
                                    }
                                },

                                getPasteBufferForNode(_node) {
                                    let children = [];
                                    for (let i = 0; i < _node.children.length; i++) {
                                        children.push(this.getPasteBufferForNode(_node.children[i]));
                                    }
                                    return {
                                        "text": _node.text,
                                        "state": {
                                            "opened": true,
                                            "disabled": false,
                                            "selected": false,
                                        },
                                        "children": children,
                                        "data": _node.data
                                    };
                                },

                                payload: function() {
                                    let raw = this.el.jstree('get_json');
                                    let nodes = [];
                                    for (let i = 0; i < raw.length; i++) {
                                        nodes.push(this.nodePayload(raw[i].id));
                                    }
                                    return JSON.stringify(nodes);
                                },

                                nodePayload: function(_id) {
                                    let node = this.el.jstree('get_node', _id);
                                    let payload = {};
                                    if(node.data.type === 'stat_tree_line') {
                                        payload = {
                                            displayLabel: node.data.displayLabel,
                                            clause: node.data.clause,
                                            columns: node.data.columns,
                                            goalPercent: node.data.goalPercent,
                                            goalCondition: node.data.goalCondition,
                                        };
                                        let children = [];
                                        for (let i = 0; i < node.children.length; i++) {
                                            children.push(this.nodePayload(node.children[i]));
                                        }
                                        payload.children = children;
                                    }
                                    return payload;
                                },

                                selectedNode: function() {
                                    let selected = this.el.jstree('get_selected', true);
                                    if(selected && selected.length) {
                                        return selected[0];
                                    }
                                    return false;
                                },

                                getSelectedNodeClauseArgs: function() {
                                    let selected = this.selectedNode();
                                    if(selected) {
                                        return selected.data.clause.args;
                                    }
                                    return [];
                                },

                                getSelectedNodeColumns: function() {
                                    let selected = this.selectedNode();
                                    if(selected) {
                                        return selected.data.columns;
                                    }
                                    return [];
                                },

                                setSelectedNodeColumns: function(columns) {
                                    let selected = this.selectedNode();
                                    if(selected) {
                                        selected.data.columns = columns;
                                        this.setDirty();
                                    }
                                    return [];
                                },

                                onDeselected: function(_e, _data) {
                                    linePropsColumn.addClass('d-none');
                                },

                                onSelected: function(_e, _data) {

                                    let selected = this.selectedNode();

                                    @if($multiProView)
                                        $('.multi-pro-stats-table tr.bg-treeblue').removeClass('bg-treeblue');
                                        $('.multi-pro-stats-table tr[data-line-uid="' + selected.data.uid + '"]').addClass('bg-treeblue');
                                        return;
                                    @endif

                                    if(selected) console.log(selected.data)

                                    if(!(selected && selected.data && selected.data.type === 'stat_tree_line')) return;

                                    linePropsColumn.removeClass('d-none');
                                    linePropsColumn.find('[line-label]').text(selected.data.displayLabel);
                                    linePropsColumn.find('[line-goal]').text(
                                        selected.data.goalCondition + ' ' +
                                        (selected.data.goalPercent === -1 ? '-' : selected.data.goalPercent + '%')
                                    );

                                    // fill args
                                    let tbody = linePropsColumn.find('[line-args]');
                                    let clause = selected.data.clause;
                                    tbody.empty();
                                    if(clause) {
                                        let edit = true;
                                        let args = clause.args ? clause.args : [];
                                        // $('<tr/>').addClass(edit ? '' : 'opacity-60 parent-arg').append($('<td/>').attr('colspan', 3).addClass('font-weight-bold text-sm ' + (edit ? '' : 'text-secondary')).text(clause.clause_label)).appendTo(tbody);
                                        if(!args.length) {
                                            $('<tr/>').addClass(edit ? '' : 'opacity-60 parent-arg').append($('<td/>').attr('colspan', 3).addClass('pl-3 text-secondary text-sm').text('No args')).appendTo(tbody);
                                        }
                                        else {
                                            for (let i = 0; i < args.length; i++) {
                                                $('<tr/>')
                                                    .addClass(edit ? '' : 'opacity-60 parent-arg')
                                                    .append(
                                                        $('<td/>')
                                                            .addClass('pl-3')
                                                            .html(args[i].arg_text + ' <span class="text-secondary text-sm">(' + args[i].field_type + ')</span>')
                                                    )
                                                    .append(
                                                        $('<td/>')
                                                            .text(args[i].value)
                                                            .append(edit ? '<a href="#" class="edit-arg-value ml-2" data-index="' + i + '"><i class="fa fa-edit text-primary text-sm on-hover-opaque"></i></a>': '')
                                                    )
                                                    .append(
                                                        $('<td/>')
                                                            .text(args[i].access_level)
                                                            .append(edit ? '<a href="#" class="edit-arg-access-level ml-2" data-index="' + i + '"><i class="fa fa-edit text-primary text-sm on-hover-opaque"></i></a>': '')
                                                    )
                                                    .appendTo(tbody);
                                            }
                                        }
                                    }

                                    // fill columns
                                    tbody = linePropsColumn.find('[line-columns]');
                                    let columns = StatTree.getSelectedNodeColumns();
                                    tbody.empty();
                                    if(columns && columns.length) {
                                        for (let i = 0; i < columns.length; i++) {
                                            $('<tr/>')
                                                .append($('<td/>').text(i + 1))
                                                .append($('<td/>').text(columns[i].label).append('<a href="#" class="edit-column-label ml-2" data-index="' + i + '"><i class="fa fa-edit text-primary text-sm on-hover-opaque"></i></a>'))
                                                .append($('<td/>').text(columns[i].display_key).append('<a href="#" class="edit-column-column ml-2" data-index="' + i + '"><i class="fa fa-edit text-primary text-sm on-hover-opaque"></i></a>'))
                                                .append($('<td/>').text(columns[i].type))
                                                .append(
                                                    $('<td/>')
                                                        .addClass('text-right text-nowrap')
                                                        .append(i > 0 ? '<a href="#" class="move-column-up mr-2" data-index="' + i + '"><i class="fa fa-arrow-up text-primary on-hover-opaque"></i></a>': '')
                                                        .append(i < columns.length - 1 ? '<a href="#" class="move-column-down mr-2" data-index="' + i + '"><i class="fa fa-arrow-down text-primary on-hover-opaque"></i></a>': '')
                                                        .append('<a href="#" class="remove-column" data-index="' + i + '"><i class="fa fa-trash-alt text-danger on-hover-opaque"></i></a>')
                                                )
                                                .appendTo(tbody);
                                        }
                                    }

                                    initMoes();

                                },
                            };

                            $(document)
                                .off('click', '.add-column')
                                .on('click', '.add-column', function() {
                                    let form = $(this).closest('form');
                                    if(!form[0].checkValidity()) {
                                        form[0].reportValidity();
                                        return false;
                                    }
                                    let columns = StatTree.getSelectedNodeColumns();
                                    columns.push({
                                        label: form.find('[name="label"]').val(),
                                        display_key: form.find('[name="display_key"]').val(),
                                        type: form.find('[name="type"]').val(),
                                    });
                                    StatTree.setSelectedNodeColumns(columns);
                                    StatTree.onSelected();
                                    StatTree.setDirty();
                                    form[0].reset();
                                    form.find('[name="label"]').focus();
                                    return false;
                                });

                            /*linePropsColumn.find('input[stag-suggest][name="displayKey"]')
                                .off('stag-suggest-selected')
                                .on('stag-suggest-selected', (_e, _input, _data) => {
                                    let columns = StatTree.getSelectedNodeColumns();
                                    columns.push({
                                        label: _data.label,
                                        display_key: _data.text,
                                        type: _data.type
                                    });
                                    $(_input).val('').focus();
                                    StatTree.setSelectedNodeColumns(columns);
                                    StatTree.onSelected();
                                    StatTree.setDirty();
                                    return false;
                                });*/

                            $(document)
                                .off('click', '.move-column-up')
                                .on('click', '.move-column-up', function() {
                                    let columns = StatTree.getSelectedNodeColumns();
                                    let index = +($(this).attr('data-index'));
                                    if(index > 0) {
                                        let x = columns[index - 1];
                                        columns[index - 1] = columns[index];
                                        columns[index] = x;
                                    }
                                    StatTree.setSelectedNodeColumns(columns);
                                    StatTree.onSelected();
                                    StatTree.setDirty();
                                    return false;
                                });

                            $(document)
                                .off('click', '.move-column-down')
                                .on('click', '.move-column-down', function() {
                                    let columns = StatTree.getSelectedNodeColumns();
                                    let index = +($(this).attr('data-index'));
                                    if(index < columns.length - 1) {
                                        let x = columns[index + 1];
                                        columns[index + 1] = columns[index];
                                        columns[index] = x;
                                    }
                                    StatTree.setSelectedNodeColumns(columns);
                                    StatTree.onSelected();
                                    StatTree.setDirty();
                                    return false;
                                });

                            $(document)
                                .off('click', '.remove-column')
                                .on('click', '.remove-column', function() {
                                    let columns = StatTree.getSelectedNodeColumns();
                                    columns.splice(+($(this).attr('data-index')), 1);
                                    StatTree.setSelectedNodeColumns(columns);
                                    StatTree.onSelected();
                                    StatTree.setDirty();
                                    return false;
                                });

                            $(document)
                                .off('click', '.edit-arg-value')
                                .on('click', '.edit-arg-value', function() {
                                    let args = StatTree.getSelectedNodeClauseArgs();
                                    let value = window.prompt('New value:', args[+($(this).attr('data-index'))].value || '');
                                    if(value !== null) {
                                        args[+($(this).attr('data-index'))].value = value;
                                        StatTree.onSelected();
                                        StatTree.setDirty();
                                    }
                                    return false;
                                });

                            $(document)
                                .off('click', '.edit-arg-access-level')
                                .on('click', '.edit-arg-access-level', function() {
                                    let args = StatTree.getSelectedNodeClauseArgs();
                                    let accessLevel = window.prompt('New access level (USER, PRO or ADMIN):', args[+($(this).attr('data-index'))].access_level || '');
                                    if(accessLevel !== null) {
                                        args[+($(this).attr('data-index'))].access_level = accessLevel;
                                        StatTree.onSelected();
                                        StatTree.setDirty();
                                    }
                                    return false;
                                });

                            $(document)
                                .off('click', '.edit-column-label')
                                .on('click', '.edit-column-label', function() {
                                    let columns = StatTree.getSelectedNodeColumns();
                                    let index = +($(this).attr('data-index'));
                                    let value = window.prompt('New label:', columns[+($(this).attr('data-index'))].label || '');
                                    if(value !== null) {
                                        columns[index].label = value;
                                        StatTree.setSelectedNodeColumns(columns);
                                        StatTree.onSelected();
                                        StatTree.setDirty();
                                    }
                                    return false;
                                });

                            $(document)
                                .off('click', '.edit-column-column')
                                .on('click', '.edit-column-column', function() {
                                    let columns = StatTree.getSelectedNodeColumns();
                                    let index = +($(this).attr('data-index'));
                                    let value = window.prompt('New column:', columns[+($(this).attr('data-index'))].display_key || '');
                                    if(value !== null) {
                                        columns[index].display_key = value;
                                        StatTree.setSelectedNodeColumns(columns);
                                        StatTree.onSelected();
                                        StatTree.setDirty();
                                    }
                                    return false;
                                });

                            $(document)
                                .off('click', '.btn-edit-goal')
                                .on('click', '.btn-edit-goal', function() {
                                    let selected = StatTree.selectedNode();
                                    let condition = window.prompt('Condition (=, <, >, <=, ):', selected.data.goalCondition);
                                    if(condition !== null) {
                                        let value = window.prompt('New goal (%):', (selected.data.goalPercent !== -1 ? selected.data.goalPercent : ''));
                                        if(value !== null) {
                                            if($.trim(value) === '') {
                                                value = -1;
                                            }
                                            else {
                                                value = +value;
                                            }
                                            selected.data.goalCondition = condition;
                                            selected.data.goalPercent = value;
                                            StatTree.onSelected();
                                            StatTree.setDirty();
                                        }
                                    }
                                    return false;
                                });

                            $(document)
                                .off('click', '.clause-expand-all')
                                .on('click', '.clause-expand-all', function() {
                                    $('#clauses-view-{{$statTree->id}}').jstree('open_all');
                                    return false;
                                });
                            $(document)
                                .off('click', '.clause-collapse-all')
                                .on('click', '.clause-collapse-all', function() {
                                    $('#clauses-view-{{$statTree->id}}').jstree('close_all');
                                    return false;
                                });

                            $(document)
                                .off('click', '.tree-expand-all')
                                .on('click', '.tree-expand-all', function() {
                                    $('#stat-tree-edit-{{$statTree->id}}').jstree('open_all');
                                    return false;
                                });
                            $(document)
                                .off('click', '.tree-collapse-all')
                                .on('click', '.tree-collapse-all', function() {
                                    $('#stat-tree-edit-{{$statTree->id}}').jstree('close_all');
                                    return false;
                                });

                            $(document)
                                .off('click', '#btn-save-tree')
                                .on('click', '#btn-save-tree', function() {
                                    StatTree.save();
                                    return false;
                                });

                            $(document)
                                .off('click', '.log-tree')
                                .on('click', '.log-tree', function() {
                                    StatTree.log();
                                    return false;
                                });

                            $(document)
                                .off('click', '.btn-add-pro')
                                .on('click', '.btn-add-pro', function() {
                                    multiViewPros.push($(this).closest('[moe]').find('#proUid').val());
                                    fastLoad('{{ route('practice-management.statTrees.view.edit', $statTree) }}?multi-pro=1&multi-pro-uids=' + multiViewPros.join(','));
                                    return false;
                                });

                            $(document)
                                .off('input change paste', '.frm-clause-add-edit input[name="question"], .frm-clause-add-edit input[name="answer"]')
                                .on('input change paste', '.frm-clause-add-edit input[name="question"], .frm-clause-add-edit input[name="answer"]', function() {
                                    let form = $(this).closest('.frm-clause-add-edit');
                                    let label = $.trim(form.find('input[name="question"]').val()) + ' ' +
                                        $.trim(form.find('input[name="answer"]').val());
                                    form.find('input[name="label"]').val(label);
                                });

                            $('#refresh-counts')
                                .off('click')
                                .on('click', function() {
                                    if(StatTree.changed) {
                                        window.alert('Cannot refresh counts while the tree has unsaved changes.');
                                        return;
                                    }
                                    fastReload();
                                    return false;
                                });

                            $('#paste-as-root')
                                .off('click')
                                .on('click', function() {
                                    let pasteInput = $('#paste-container');
                                    pasteInput.empty().focus();
                                    navigator.clipboard.readText().then(clipText => {
                                        // check if valid json
                                        try {
                                            let parsed = JSON.parse(clipText);
                                            // empty the tree
                                            StatTree.el.jstree(true).delete_node(StatTree.el.jstree(true).get_node("#").children);

                                            // paste it!
                                            StatTree.el.jstree(true).create_node('#', parsed, 'first');

                                            StatTree.setDirty();
                                        }
                                        catch (e) {
                                            toastr.error('Invalid paste buffer!');
                                        }
                                    })
                                });

                            $(document)
                                .off('click', '.mv-view-data-trigger')
                                .on('click', '.mv-view-data-trigger', function() {
                                    let title = 'View Data';
                                    if($(this).attr('data-pro-uid')) {
                                        let tdIndex = $(this).index();
                                        title = 'View Data for ' + $(this).closest('table').find('thead tr th:eq(' + tdIndex + ')').text();
                                    }
                                    openDynamicStagPopup('/practice-management/stat-tree-lines/view-data/' + $(this).closest('tr').attr('data-line-uid') + '?proUid=' + $(this).attr('data-pro-uid'),
                                        null,
                                        title,
                                        false,
                                        'medium');
                                    return false;
                                });

                            $(document)
                                .off('click', '.mv-delete-pro-trigger')
                                .on('click', '.mv-delete-pro-trigger', function() {
                                    let proUids = '{{request()->input('multi-pro-uids')}}'.split(',').filter(_x => _x !== $(this).attr('data-pro-uid'));
                                    fastLoad('/practice-management/stat-trees/view/{{$statTree->uid}}/edit?multi-pro=1&multi-pro-uids=' + proUids.join(','));
                                    return false;
                                });

                            @if($multiProView)
                            /*$('[count-required]').each(function() {
                                $.post('{{route('practice-management.api.statTree.getCountsForPro')}}', {
                                    uid: '{{$statTree->uid}}',
                                    proUid: $(this).attr('data-pro-uid')
                                }, _data => {
                                    for(let x in _data) {
                                        $('.multi-pro-stats-table tr[data-line-uid="' + x + '"] td[data-pro-uid="' + $(this).attr('data-pro-uid') + '"] .count').text(_data[x]);
                                    }

                                    // calculate drop %
                                    $('.multi-pro-stats-table tr[data-line-uid][data-parent-line-uid]').each(function() {
                                        for (let i = 0; i < $(this).find('>td').length; i++) {
                                            let parentCount = $('.multi-pro-stats-table tr[data-line-uid="' + $(this).attr('data-parent-line-uid') + '"]>td:eq(' + i + ') .count').first().text(),
                                                myCount = $(this).find('>td:eq(' + i + ') .count').first().text();
                                            if(parentCount && myCount && !Number.isNaN(+parentCount) && !Number.isNaN(+myCount) && +parentCount > 0) {
                                                parentCount = +parentCount;
                                                myCount = +myCount;
                                                let element = $(this).find('>td:eq(' + i + ') .drop-percent').first(), cssClass = '';
                                                let dropPercent = ((parentCount - myCount) / parentCount) * 100;
                                                if(dropPercent > 75) {
                                                    cssClass = 'mv-drop-76-100';
                                                }
                                                else if(dropPercent > 50 && dropPercent <= 75) {
                                                    cssClass = 'mv-drop-51-75';
                                                }
                                                else if(dropPercent > 25 && dropPercent <= 50) {
                                                    cssClass = 'mv-drop-26-50';
                                                }
                                                else if(dropPercent > 0 && dropPercent <= 25) {
                                                    cssClass = 'mv-drop-0-25';
                                                }
                                                element.removeClass().addClass('drop-percent').addClass(cssClass).text(dropPercent.toFixed(1) + '% ⤵');
                                            }
                                        }
                                    });

                                }, 'json');
                            });*/
                            $.get('{{route('practice-management.api.statTree.getCountsForPros')}}', {
                                uid: '{{$statTree->uid}}',
                                proUids: '{{request()->input('multi-pro-uids')}}'
                            }, _data => {
                                for(let x in _data) {
                                    let lineTR = $('.multi-pro-stats-table tr[data-line-uid="' + x + '"]');
                                    for (let i = 0; i < _data[x].length; i++) {
                                        lineTR.find('>td[data-pro-uid="' + _data[x][i]._v_pro_uid + '"] .count').text(_data[x][i].count);
                                    }
                                }
                                // calculate drop %
                                $('.multi-pro-stats-table tr[data-line-uid][data-parent-line-uid]').each(function() {
                                    for (let i = 0; i < $(this).find('>td').length; i++) {
                                        let parentCount = $('.multi-pro-stats-table tr[data-line-uid="' + $(this).attr('data-parent-line-uid') + '"]>td:eq(' + i + ') .count').first().text(),
                                            myCount = $(this).find('>td:eq(' + i + ') .count').first().text();
                                        if(parentCount && myCount && !Number.isNaN(+parentCount) && !Number.isNaN(+myCount) && +parentCount > 0) {
                                            parentCount = +parentCount;
                                            myCount = +myCount;
                                            let element = $(this).find('>td:eq(' + i + ') .drop-percent').first(), cssClass = '';
                                            let dropPercent = ((parentCount - myCount) / parentCount) * 100;
                                            if(dropPercent > 75) {
                                                cssClass = 'mv-drop-76-100';
                                            }
                                            else if(dropPercent > 50 && dropPercent <= 75) {
                                                cssClass = 'mv-drop-51-75';
                                            }
                                            else if(dropPercent > 25 && dropPercent <= 50) {
                                                cssClass = 'mv-drop-26-50';
                                            }
                                            else if(dropPercent > 0 && dropPercent <= 25) {
                                                cssClass = 'mv-drop-0-25';
                                            }
                                            element.removeClass().addClass('drop-percent').addClass(cssClass).text(dropPercent.toFixed(1) + '% ⤵');
                                        }
                                    }
                                });
                            }, 'json');
                            @endif

                            @if($multiProView)
                            $('.mv-tree .stat-tree-view')
                                .off('scroll')
                                .on('scroll', function() {
                                     $('.mv-table').scrollTop($(this).scrollTop());
                                });
                            @endif

                            ClausesTree.load();
                            StatTree.load();
                            initMoes();

                            addMCHook('reloadClausesTree', function() {
                                ClausesTree.load();
                            });

                            initVSplitter('stat-tree-edit-1', $('.clauses-column'), $('.tree-column'));
                            @if(!$multiProView)
                                initVSplitter('stat-tree-edit-2', $('.tree-lhs-column'), $('.tree-rhs-column'));
                            @else
                                initVSplitter('stat-tree-edit-3', $('.mv-tree'), $('.mv-table'));
                            @endif

                        }
                        addMCInitializer('stat-tree-edit-page', init, '#statTreeEdit-{{$statTree->id}}');
                    }).call(window);
                </script>
            </div>
        </div>
    </div>
@endsection