<div class="card">
    <div class="card-heading d-flex justify-content-between">
        <div class="card-heading-title">
            <h3 class="card-title"><?php echo app('translator')->get('Lista kategorija vesti'); ?></h3>
            <p class="card-sub-title text-muted"><?php echo app('translator')->get('Mozete da menjate <code>redosled</code> kategorija po prioritetu'); ?></p>
        </div>
        <div class="card-heading-actions">
            <form 
                action=""
                method="post"
                id="priority-change-form" 
                class="d-inline"
            >
                <?php echo csrf_field(); ?>
                <input type="hidden" name="ids_by_priority" value="">

                <button id="priority-change-btn" type="button" class="btn btn-outline-warning">
                    <i class="fa fa-sort"></i>
                    <?php echo app('translator')->get('Promeni Redosled'); ?>
                </button>
                <button id="priority-save-btn" type="button" class="btn btn-success" style="display: none;">
                    <i class="fa fa-save"></i>
                    <?php echo app('translator')->get('Sačuvaj Redosled'); ?>
                </button>
                <button id="priority-cancel-btn" type="button" class="btn btn-outline-danger" style="display: none;">
                    <i class="fa fa-remove"></i>
                    <?php echo app('translator')->get('Otkaži'); ?>
                </button>
            </form>
        </div>
    </div>
    <div class="card-body">
        

        <table id="entities-table" class="table table-striped">
            <thead>
                <tr>
                    <th>&nbsp;</th>
                    <th class="text-center"><span class="text-success" style="padding-left: 18px;"><i class="fa fa-check"></i></span></th>
                    <th><?php echo app('translator')->get('Naziv Kategorije'); ?></th>
                    <th></th>
                    <th class="disabled-sorting text-right"><?php echo app('translator')->get('Opcije'); ?></th>
                </tr>
            </thead>
            <tbody>
                
            </tbody>
        </table>
    </div>
</div>

<?php $__env->startPush('head_links'); ?>
<style>
    .sortable-move-highlight {
        background-color: rgba(0,0,0,0.1) !important;
        line-height: 2.8em;
    }
    .ui-sortable-helper > td {
        border: none !important; 
    }
    .table-sortable tbody tr:nth-of-type(odd) {
        background-color: rgba(255,255,255,0.1);
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('footer_scripts'); ?>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
    var blade = {
        prioritySaveAjaxUrl: "<?php echo e(route('categories.change_priority', ['activeWebsite' => $activeWebsite])); ?>",
        datatablesAjaxUrl: "<?php echo e(route('categories.datatable', ['activeWebsite' => $activeWebsite])); ?>",
        entityId: "<?php echo e($entity ? $entity->id : -1); ?>"
    };

    // 'enter' kao 'tab'
    // @link https://stackoverflow.com/questions/1009808/enter-key-press-behaves-like-a-tab-in-javascript
    $('body').on('keydown', 'input, select', function(e) {
        if (e.key === "Enter") {
            var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
            focusable = form.find('input,a,select,button,textarea').filter(':visible');
            next = focusable.eq(focusable.index(this)+1);
            if (next.length) {
                next.focus();
            } else {
                form.submit();
            }
            return false;
        }
    });
    
    // DATATABLES
    var datatable = $('#entities-table').DataTable({
        "processing": false,
        "serverSide": true,
        "paging": false,
        "searching": false,
        "language": {
            "emptyTable": "<?php echo app('translator')->get('Nema kategorija'); ?>",
            "sInfoFiltered": ""
        },
        "ajax": {
            url: blade.datatablesAjaxUrl,
            type: "post",
        },
        "columns": [
            {data: "sort_handle", orderable: false, searchable: false, className: "text-center", visible: false},
            {data: "status", orderable: false, searchable: false, className: "text-center"},
            {data: "name", orderable: false, searchable: false}, 
            {data: "color", orderable: false, searchable: false, className: "text-center"}, 
            {data: "actions", orderable: false, searchable: false, className: "text-right"}
        ],
        "initComplete": function() { // trenutno "initComplete" nema efekta zato sto je 
            fixDatatableBug();       // prva kolona nad kojom se ispravlja bag 'hidden'. 
        }
    });

    /**
     * Ispravi 'datatables' bag gde se pojavljuje fantomska klasa 'sorting_asc' 
     * iako je kolona setovana kao 'orderable: false'.
     */
    function fixDatatableBug()
    {
        $('th.sorting_asc').first().removeClass('sorting_asc');
    }


    // KOD ZA IZMENU REDOSLEDA ('PRIORITY') KATEGORIJA
    // ------------------------------------------------

    /**
     * Sakrij dugmice za 'save' i 'cancel' a prikazi za 'priority change'.
     * Uradi 'unbind' 'sortable' elementa.
     */
    function buttonsResetAndUnbindSortable() {
        $('#priority-change-btn').show();
        $('#priority-save-btn').hide();
        $('#priority-cancel-btn').hide();

        $(".sortable-entities").sortable("destroy");
        $('#entities-table_wrapper').removeClass('sortable-entities');
        $('#entities-table').switchClass("table-sortable", "table-striped");
    }

    $('#priority-change-btn').on('click', function () {
        $('#priority-change-btn').hide();
        $('#priority-save-btn').show();
        $('#priority-cancel-btn').show();

        $('#entities-table').switchClass("table-striped", "table-sortable", {children: true, duration: 600});
        $('#entities-table_wrapper').addClass('sortable-entities');

        //inicijalizuj 'jquery-ui sortable'
        $(".sortable-entities").sortable({ 
            items: "tr",
            containment: $('#entities-table > tbody'),
            handle: '.entity-sort-handle',
            tolerance: "pointer",
            placeholder: "sortable-move-highlight",
            cursor: "move",
            revert: 250, 
            // 'helper' resenje preuzeto sa -> https://stackoverflow.com/questions/1307705/jquery-ui-sortable-with-table-and-tr-width
            helper: function(e, tr) { 
                var $originals = tr.children();
                var $helper = tr.clone(true);
                $helper.children().each(function(index) {
                    // Set helper cell sizes to match the original sizes
                    $(this).width($originals.eq(index).width());
                });
                return $helper;
            }
        });

        // prikazi kolonu sa 'sorting hadle' elementima
        datatable.column(0).visible(true);
        fixDatatableBug();
    });

    $('#priority-cancel-btn').on('click', function () {
        buttonsResetAndUnbindSortable();

        datatable.ajax.reload(function() {
            fixDatatableBug();
            // sakrij kolonu sa 'sorting hadle' elementima
            datatable.column(0).visible(false);
        });
    });

    // Posalji preko ajaksa novi raspored 'priority'-ja kategorija.
    $('#priority-save-btn').on('click', function () {
        let priorityMap = $(".sortable-entities").sortable("toArray");

        // Nepoznato poreklo prvog "" elementa !!! TODO: naci kako/gde se on generise
        // Nastao je tek nakon integracije 'sortable' sa 'datatables'-om.
        console.log(priorityMap);
        if(priorityMap.length && priorityMap[0] === "") {
            priorityMap.shift();
        }

        let ajaxData = {
            "priority_map": priorityMap,
            "map_collection_range": "full"
        };

        $.ajax({
            'url': blade.prioritySaveAjaxUrl,
            'type': 'POST',
            'data': ajaxData, 
            // ne poziva se .done() zato sto ajax.blade.php $.ajaxSetup ima 'success' i 'error' 'callback' funkcije.
            'success': function(response) { 
                buttonsResetAndUnbindSortable();
            }
        })            

    });

    // DELETE MODAL
    let deleteOptions = {
        "liveSelector": '[data-action="delete"]'
    };
    $('#entities-table').questionPop(deleteOptions).on('success.qp', '[data-action="delete"]', function(e) {
        let rowId = $(e.target).data('id');
        $('#' + rowId).remove();

        // ukoliko je ID trenutne kategorije koja se edituje jednak ID-ju kategorije koja je obrisana
        // idi na pocetnu stranicu kategorija.
        if(blade.entityId && rowId == blade.entityId) {
            window.location.href = "<?php echo e(route('categories.index', ['activeWebsite' => $activeWebsite])); ?>";
        }
    });

    // Prikazujemo/uklanjamo kategoriju iz navigacije
    $('#entities-table').questionPop({
        "liveSelector": '[data-action="show-in-nav"]'
    }).on('success.qp', function() {
        $('#entities-table').DataTable().draw('page');

    });

    /**
     * 'Javascript' akcije koje se izvrsavaju kada je uspesno izvrseno
     * 'backend enable/disable' kategorije.
     */
    function onEnabledDisabled(button) {
        let action = button.find('i').hasClass('fa-plus-circle') ? 1 : 0;

        let buttonElActiveClass = action ? 'fa-minus-circle' : 'fa-plus-circle';
        let buttonElChangeClass = action ? 'fa-plus-circle' : 'fa-minus-circle';
        let statusElActiveClass = action ? 'fa-remove' : 'fa-check';
        let statusElChangeClass = action ? 'fa-check' : 'fa-remove';
        let statusWrapperElActiveClass = action ? 'text-danger' : 'text-success';
        let statusWrapperElChangeClass = action ? 'text-success' : 'text-danger';
        let btnTitle = action ? "<?php echo app('translator')->get('Zabrani'); ?>" : "<?php echo app('translator')->get('Odobri'); ?>";
        let btnDataText = action ? "<?php echo app('translator')->get('Da li ste sigurni da želite da zabranite kategoriju '); ?>"
                                 : "<?php echo app('translator')->get('Da li ste sigurni da želite da odobrite kategoriju '); ?>";

        button.prop('title', btnTitle);
        button.data('title', btnTitle);
        button.data('text', btnDataText);
        button.find('i').removeClass(buttonElChangeClass).addClass(buttonElActiveClass);

        let row = button.closest('tr');
        let wrapperEl = $(row).find('span.' + statusWrapperElActiveClass);
        let innerEl = $(row).find('span.' + statusWrapperElActiveClass + ' .fa.' + statusElActiveClass);

        innerEl.removeClass(statusElActiveClass).addClass(statusElChangeClass);
        wrapperEl.removeClass(statusWrapperElActiveClass).addClass(statusWrapperElChangeClass);
    }

    // ENABLE/DISABLE MODAL
    let enableDisableDptions = {
        "liveSelector": '[data-action="enable-disable"]'
    };
    $('#entities-table').questionPop(enableDisableDptions).on('success.qp', '[data-action="enable-disable"]', function(e) {
        onEnabledDisabled($(e.target));
    });
});
</script>
<?php $__env->stopPush(); ?><?php /**PATH /opt/cms/resources/views/categories/partials/list.blade.php ENDPATH**/ ?>