@extends('app.practice-management.visit-templates.single')
@section('visitTemplateTab')

<div id="visitTemplateSegmentTemplates" class="row">
    <div class="col-md-12">
        <div class="card mb-2">
            <div class="card-header border-bottom-0 px-1 py-2 d-flex align-items-center">
                <strong class="mr-4">
                    <i class="fas fa-notes-medical"></i>
                    Visit Template Segment Templates
                </strong>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header border-bottom-0 px-1 py-2 d-flex align-items-center">
                        <div class="d-flex align-items-center justify-content-between w-100">
                            <strong>Left Position</strong>
                            @include('app.practice-management.visit-templates.visit-template-segment-templates.create', ['position' => 'LEFT'])
                        </div>

                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive" data-position="LEFT" droppable-section>
                            @include('app.practice-management.visit-templates.visit-template-segment-templates.segment-templates-list', ['position' => 'LEFT'])
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header border-bottom-0 px-1 py-2 d-flex align-items-center">
                        <div class="d-flex align-items-center justify-content-between w-100">
                            <strong>Right Position</strong>
                            @include('app.practice-management.visit-templates.visit-template-segment-templates.create', ['position' => 'RIGHT'])
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive" data-position="RIGHT" droppable-section>
                            @include('app.practice-management.visit-templates.visit-template-segment-templates.segment-templates-list', ['position' => 'RIGHT'])
                        </div>                        
                    </div>
                </div>
                @if($visitTemplate->is_slim)
                    <div class="alert alert-warning mt-1">
                        <span><b><i class="fas fa-exclamation-triangle"></i> Warning:</b> Two column layout wont work well on slim.</span>
                    </div>
                @endif
            </div>
        </div>

        <div class="mt-3">
            {{ $visitTemplateSegmentTemplates->appends(request()->input())->links() }}
        </div>
    </div>

    <div class="col-md-12 mt-4">
        <div class="card mb-2">
            <div class="card-header border-bottom-0 px-1 py-2 d-flex align-items-center">
                <strong class="mr-4">
                    <i class="fas fa-trash text-danger"></i>
                    Deactivated Segment Templates
                </strong>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            @include('app.practice-management.visit-templates.visit-template-segment-templates.segment-templates-list-deactivated')
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<script>
var draggableVisitTemplateSegmentTemplates = null;
(function($){
    draggableVisitTemplateSegmentTemplates = {
        recordsPerPage: '<?= $visitTemplateSegmentTemplates->perPage() ?>',
        currentPage: '<?= $visitTemplateSegmentTemplates->currentPage() ?>',
        preservePositionIndexNumber: false,
        draggedDeactivatedRecordUid: null,

        recalculateRowsPositionIndexes: function(table, leftRightPosition){
            var self = this;
            self.forceShowMask();
            var currentRowsData = [];
            var rows = $(table).find('tbody tr');
            $.each(rows, function(i, row){
                var uid = $(row).data('uid');
                var currentPositionIndex = parseInt($(row).data('positionindex'));
                var heading = $(row).data('heading');
                var subheading = $(row).data('subheading');
                var displayTitle = $(row).data('displaytitle');
                var leftOrRight = $(row).data('leftorright');
                currentRowsData.push({uid:uid, position: currentPositionIndex,heading:heading, subheading:subheading, displayTitle:displayTitle, leftOrRight:leftOrRight});                
            });
            var _currentRowsData = JSON.stringify(currentRowsData);
            
            var sortedByPositionIndexAscending = currentRowsData.sort(function(a, b){
                var aPositionIndex = a.position;
                var bPositionIndex = b.position; 
                return ((aPositionIndex < bPositionIndex) ? -1 : ((aPositionIndex > bPositionIndex) ? 1 : 0));
            });

            var originalCurrentRowsData = JSON.parse(_currentRowsData);

            var updatedData = [];
            $.each(originalCurrentRowsData, function(i, r){
                if(self.preservePositionIndexNumber){
                  r.position = sortedByPositionIndexAscending[i].position;  
                }else{
                    r.position = i;
                    var currentPage = parseInt(self.currentPage);
                    currentPage = isNaN(currentPage) ? 1:currentPage;
                    if(currentPage > 1){
                        r.position = i + parseInt(self.recordsPerPage);
                    }                    
                }
                
                updatedData.push(r);
            });
            self.updatePositionIndexes(updatedData);
        },
        updatePositionIndexes: async function(data){
            var self = this;
            var error = null;
            for (var row of data) {
                row.positionIndex = row.position;
                var response = await $.post('/api/visitTemplateSegmentTemplate/updateBasic', row, function(res){return res});
                if(!response.success){
                    error = true;
                    toastr.error(response.message);
                }
            }
            
            fastReload();
            setTimeout(function(){
                self.forceHideMask();
            },1000);
        },
        initDraggableTable: function(){
            var self = this;
            $(".table-dnd").tableDnD({
                onDragClass: 'table-dnd-on-drag',
                onDrop: function(table, row){
                    var tableLeftRightPosition = $(table).data('position');
                    self.recalculateRowsPositionIndexes(table, tableLeftRightPosition);
                },
                onDragStart: function(table, row) {
                    $(table).find('tbody tr').addClass('table-dnd-no-change');
                    $(row).removeClass('table-dnd-no-change');
                },
                onDragStop: function(table, row) {
                    $(table).find('tbody tr').removeClass('table-dnd-no-change');
                },
            });
        },
        initOnDroppableSection: function(){
            var self = this;
            $('[droppable-section]').on('dragover', function(e){
                $(e.currentTarget).addClass('droppable-section-active');
                return false;
            }).on('drop', function (e) {
                $(e.currentTarget).removeClass('droppable-section-active');
                var position = $(e.currentTarget).data('position');
                self.updateDraggedDeactivatedRecord(position);
                return false;
            });
            $('[draggable-item]').on('dragstart', function(e){
                self.draggedDeactivatedRecordUid = $(e.currentTarget).data('uid');
            });
        },
        updateDraggedDeactivatedRecord: function(position){
            var self = this;
            if(!self.draggedDeactivatedRecordUid) return;
            self.forceShowMask();
            var positionUrl = position == 'LEFT' ? 'moveToLeft':'moveToRight';
            $.post('/api/visitTemplateSegmentTemplate/reactivate', {uid: self.draggedDeactivatedRecordUid, memo:''}, function(response){
                if(response.success){
                  $.post('/api/visitTemplateSegmentTemplate/'+positionUrl, {uid:self.draggedDeactivatedRecordUid}, function(res){
                      if(res.success){
                          self.draggedDeactivatedRecordUid = null;
                          fastReload();
                          self.forceHideMask();
                      }
                  },'json');  
                }
            },'json');            
        },
        forceShowMask: function(){
            $('body').addClass('forced-masking');
        },
        forceHideMask: function(){
            $('body').removeClass('forced-masking');
        },
        init: function(){
            this.initDraggableTable();
            this.initOnDroppableSection();
        }
    };
    
})(jQuery);
</script>

<script>
        (function() {
            function init() {
                draggableVisitTemplateSegmentTemplates.init();
                addMCHook('reArrangePositionIndexes', function() {
                    draggableVisitTemplateSegmentTemplates.forceShowMask();
                    fastReload();
                    setTimeout(function(){
                        var tables = $('.table-dnd');
                        $.each(tables, function(i, table){
                            var tableLeftRightPosition = $(table).data('position');
                            draggableVisitTemplateSegmentTemplates.recalculateRowsPositionIndexes(table, tableLeftRightPosition);
                        });
                    },500);
                });
            }
            addMCInitializer('visitTemplateSegmentTemplates', init, '#visitTemplateSegmentTemplates')

        }).call(window);
    </script>

@endSection