@extends('layouts.app')
@section('styles')
    <style>
        .navbar,
        aside {
            /*display: none;*/
        }
    </style>
@endsection
@section('content')
    <h3>
        Listado de Líneas de producción
        <span class="pull-right">
			<a href="{{ URL::to('/') }}/admin/pipeline/create" class="btn btn-primary btn-sm">{{ __('s.add_pipeline') }}</a>
		</span>
    </h3>
    <div style="background-color:#fff;">
        <table class="table table-condensed table-data">
            <thead style="border-bottom:2px solid #ddd;">
            <th>Titulo</th>
            <th>Unidades Funcionales</th>
            <th class="text-center">Acciones</th>
            </thead>
            <tbody>

            {{--@foreach($pipelines as $pipeline)--}}
            {{--{{ $pipeline->slug }}--}}
            {{--@foreach($pipeline->units as $unit)--}}
            {{--{{ $unit->slug }}--}}
            {{--@endforeach--}}
            {{--@endforeach--}}



            @foreach($pipelines as $pipeline)
                <tr data-category-id="{{ $pipeline->id}}" class="unity-list">
                    <td style="padding:10px 4px;">{{ $pipeline->name }}</td>
                    <td>
                        <ul class="sortable unit-list-{{ $pipeline->id }}" id="{{ $pipeline->id }}"
                            style="margin:0;padding:0;">

                            @foreach($pipeline->unitsByRevision($pipeline->latestRevision) as $unit)


                                <li class="ui-state-default" id="{{ $pipeline->id }}_{{ $unit->id }}" data-order="{{ $unit->pivot->order }}"
                                    data-unidad-desc="{{ $pipeline->slug }}" data-unidad-id="{{ $unit->id }}"
                                    style="cursor:pointer;border-radius:4px;padding:2px 10px;margin:5px 0;background:{{$unit->color}}!important;color:#fff;">

                                    {{ $unit->name }}

                                    <a href="javascript:void(0);"
                                       onclick="deleteUnit({{ $pipeline->id }},{{$unit->id}});" class="pull-right"
                                       style="color:#fff;">
                                        <i class="fa fa-trash" aria-hidden="true"></i>
                                    </a>
                                </li>

                            @endforeach


                        </ul>
                        <div style="display: flex">
                            <select name="unit-select-{{ $pipeline->id }}" data-category={{$pipeline->id }}=""
                                    style="width: 75%;">
                                <option value="">-</option>

                                {{--{% for unidad in unidadesfuncionales %}--}}
                                @foreach($units as $u)
                                    <option value="{{ $u->id }}">{{ $u->name }}</option>
                                @endforeach
                                {{--{% endfor %}--}}
                            </select>
                            <a style="margin-left:auto" class="btn btn-primary btn-sm" href="javascript:void(0);" onclick="agregarUnidad({{ $pipeline->id }})">Agregar</a>
                        </div>
                        <br>
                        <br>

                    </td>
                    <td class="text-center">
                        <a href="{{URL::to('/')}}/admin/pipeline/{{ $pipeline->id }}/edit"><i
                                    class="fa fa-pencil-square-o" aria-hidden="true"></i> &nbsp;Editar</a>
                        &nbsp;&nbsp;&nbsp;
                    <?php /* <a href="{{URL::to('/')}}/admin/pipeline/{{$pipeline->id}}/delete">
                            <i class="fa fa-pencil-square-o" aria-hidden="true"></i> &nbsp;Eliminar</a> */ ?>
                    </td>
                </tr>
            @endforeach


            </tbody>
        </table>
    </div>



@endsection
@section('scripts')
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>

        var urlBase = "{{ URL::to('/') }}";





        function cleanRepeatedUnitsFromSelects() {
            $('.unity-list').each(function () {
                var ids = [];
                self = this;
                $(this).find('li').each(function () {
                    ids.push($(this).attr('data-unidad-id'));
                });
                $.each($('option'),function(){
                   $(this).attr('disabled',false);
                });
                $('option').show();
                $.each(ids, function (i) {
                    // conta++;
                    //  console.log( $(self).find('select').find('li[data-unidad-id="'+ids[i] +'"]' ) );
                    $(self).find('select').find('option[value="' + ids[i] + '"]').attr('disabled','true');
                    $('option[disabled="disabled"]').hide(); //then hide them

                });

            });
        }


//        function deleteCategoria(id) {
//            if (confirm("Seguro que quieres eliminar esta Categoria?")) {
//                $.ajax({
//                    type: "POST",
//                    data: {id: id},
//                    url: urlBase + '/categorias/deleteCategoriaById/',
//                    success: function (data) {
//                        location.href = urlBase + 'unidades/categorias';
//                    }
//                });
//            }
//        }

        function updateCategoria(id_lista, items) {
            console.log(JSON.stringify(id_lista));
            console.log(JSON.stringify(items));
            $.ajax({
                type: "POST",
                data: {id: id_lista, units: JSON.stringify(items)},
                url: urlBase + '/admin/pipeline/order-pipeline-units',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                dataType: 'json',

                success: function (data) {
                    //location.href = urlBase + '/unidades/listado';
                    console.log(data);
                }
            });
        }


        function agregarUnidad(pipeline) {
            var unit = $('select[name="unit-select-' + pipeline + '"]').val();
//            console.log(categoria);
//            console.log(unidad);


            if(!unit){

                alert("Seleccionar una unidad");
                return false;

            }


            $.ajax({
                type: 'POST',
                url: urlBase + '/api/pipeline/add-unit',
                data: {pipeline_id: pipeline, unit_id: unit},
                success: function (data) {
                    // on success use return data here
                    console.log(data);
                    $('.unit-list-' + pipeline).append('<li class="ui-state-default" id="' + pipeline + '_' + data.id + '" data-unidad-desc="' + data.slug + '" data-unidad-id="' + data.id + '" style="cursor:pointer;border-radius:4px;padding:2px 10px;margin:5px 0;background-color:' + data.color + ';color:#fff;">' + data.name + '<a href="javascript:void(0);" onclick="deleteUnit(' + pipeline + ','+ data.id+');" class="pull-right" style="color:#fff;"> <i class="fa fa-trash" aria-hidden="true"></i> </a> </li>	');
                    cleanRepeatedUnitsFromSelects();
                    $('select').val('');
                },
                error: function (xhr, type, exception) {
                    // if ajax fails display error alert
                    alert("ajax error response type " + type);
                }
            });


        }
        function deleteUnit(pipeline,unit) {

            if (confirm("Seguro que quieres eliminar esta Unidad Funcional?")) {
                var self = this;
                $.ajax({
                    type: 'POST',
                    url: urlBase + '/api/pipeline/delete-unit',
                    data: {pipeline_id: pipeline, unit_id: unit},
                    success: function (data) {
                        // on success use return data here
                  $('#'+pipeline+'_'+unit).remove();
                        cleanRepeatedUnitsFromSelects();

                    },
                    error: function (xhr, type, exception) {
                        // if ajax fails display error alert
                        alert("ajax error response type " + type);
                    }
                });
            }

        }

        $(function () {

            $(".sortable").sortable({
                update: function (event, ui) {

                    var id_lista = $(ui.item).parent().attr("id");

                    var items = new Array();

                    $("ul#" + id_lista + " li").each(function (index) {

                        var res = $(this).attr("id").split("_");

                        items.push(res[1]);

                    });

                    updateCategoria(id_lista, items);

                    //alert(items.join(";"));

                }
            });

            $(".sortable").disableSelection();
        });

        // sort function callback
        function sort_li(a, b){
            return ($(b).data('order')) < ($(a).data('order')) ? 1 : -1;
        }
        $(document).ready(function () {
            cleanRepeatedUnitsFromSelects();
            $('.unity-list').each(function () {
                ul = $(this).find('ul');

                $(this).find("ul li").sort(sort_li) // sort elements
                    .appendTo(ul); // append again to the list
            });

        });
    </script>

@endsection
