@extends('layouts.app')
@section('styles')
    <link rel="stylesheet" href="{{ URL::to('/') }}/js/vendor/jquery-palette-color-picker/palette-color-picker.css">
    <style>
        .navbar,
        aside {
            /*display: none;*/
        }

        form label {
            /*display: block;*/

        }
        .dataTables_wrapper{margin-top: 25px !important;}

        element {
            width: 130px !important;
        }
    </style>
@endsection
@section('content')
    @if(session()->has('message'))
        <div class="alert alert-success alert-dismissable">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>

            {{ session()->get('message') }}
        </div>
    @endif
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    <h3>
        {{ __('s.edit_unit') }}: <strong>{{ $unit->name }}</strong>

    </h3>
    @if($errors->any())
        <h4>{{$errors->first()}}</h4>
    @endif
    <form action="{{URL::to('/')}}/admin/unit/update" method="POST">
        <div class="form-group">
            <label for="">{{ __('s.name') }}</label><br>
            <input type="text" name="name" value="{{old('name', $unit->name) }}">
        </div>
        <div class="form-group">
            <label for="">{{ __('s.slug') }} </label><br>

            <input type="text" name="slug" value="{{old('slug',$unit->slug )}}">
        </div>
        <div class="form-group">
            <label for="">{{ __('s.color') }}</label><br>
            <input type="text" name="color" id="color" value="{{ old('color',$unit->color )}}"
                   data-palette='[{"#EE7373":"#EE7373"},{"#6597AA":"#6597AA"},{"#88BE84":"#88BE84"},{"#84BEB1":"#84BEB1"},{"#EE7373":"#EE7373"},{"#6597AA":"#6597AA"},{"#88BE84":"#88BE84"}]'
                   value="">
        </div>
        <div class="form-group">
            <label for="">{{ __('s.unit_type') }}</label><br>

            <select name="unitType_id" id="">
                @foreach($unitTypes as $ut)
                    <option  value="{{ $ut->id }}">{{ $ut->name }}</option>
                @endforeach
            </select>
        </div>
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
        <input type="hidden" name="id" value="{{ $unit->id }}">


        <button type="button" onclick="form.submit()" class="btn btn-default" name="submit_1" value="{{ __('s.send') }}">{{ __('s.send') }}</button>

    </form>
    <br><br>

    <h4>
        Usuarios Vinculados
    </h4>
    <table class="table table-condensed table-unidad-users table-data"  data-page-length='30'>
        <thead style="border-bottom:2px solid #ddd;">

        <th class="text-center" style="width: 14%">Usuario</th>
        <th class="text-center" style="width: 10%">tipo</th>
        <th class="text-center">Pipelines</th>
        <th class="text-center" style="width: 16%">Auto etiquetado</th>
        <th class="text-center" style="width: 20%">Perfiles</th>
        <th class="text-center" style="width: 10%">Accion</th>
        </thead>
        <tbody>
        @foreach($unit->users as $index=>$us )

        {{--{{$us->pivot->id  es el id en la tabla user_unit}}--}}
            <tr data-rel="{{$us->pivot->id}}">

            <td > {{ $us->name }} {{ $us->surname }}</td>

            @foreach($teamroles as $tr)
                @if($tr->id == $us->pivot->teamrole_id)
                <td class="text-center"> {{ $tr->name }}</td>
                @endif

            @endforeach

            <td>
                <div id="tabla_pipelinetags_ajax-{{$us->id}}-{{$us->pivot->teamrole_id}}"  class="panel-body" style="font-size: small;padding: 0px">


                    @foreach($auto_tag as $tag)

                        @foreach ($tag->pipeline as $p)


                            @if($tag->user_id == $us->id && $tag->teamrole_id ==$us->pivot->teamrole_id)

                                <span id="pipeButton{{$p->id}}-{{$us->id}}-{{$us->pivot->teamrole_id}}" class="glyphicon-class">
                                <button class="badge " style="color: #454c48; background-color: #b5cbe3">
                                    <label >{{$p->name}}</label>

                                    <span  onClick="untagPipeline({{$p->id}},{{$us->id}},{{$us->pivot->teamrole_id}})" class="glyphicon glyphicon-remove" aria-hidden="true" title="Eliminar"> </span>
                                </button>
                                </span>
                            @endif


                        @endforeach

                    @endforeach


                </div>
            </td>
            <td class="text-center">
                <div class="addPipelineButton addPipelineButton-{{$us->id}}-{{$us->pivot->teamrole_id}}">
                    <button onclick="addPipeline(this,{{$us->id}},{{$us->pivot->teamrole_id}})" class="btn btn-primary btn-sm" style="font-size: 85%;margin-left: auto">Agregar Pipeline</button>
                </div>

                <div class="s2-example col-sm-6" id="selectPipeline{{$us->id}}-{{$us->pivot->teamrole_id}}" style=" width: 100%;display:none;" >
                    <select class="js-example-data-array pipelineTag" multiple="multiple" id="pipelineTag" name="selectPipeline[]" style="width: 70%;padding: 0%"  >

                        <option></option>
                        @foreach($pipeline as $p)
                        <option value="{{$p->id}}">{{$p->name}}</option>

                        @endforeach
                    </select>
                    <button class="btn btn btn-primary" onclick="autoTag({{$us->id}},{{$us->pivot->teamrole_id}})" style="float:right;">+</button>
                </div>

            </td>
            {{-- fin etiquetas de pipeline--}}

            <td class="text-center">
                <!-- Small button groups (default and split) -->
                <p>
                    <button class="btn btn-secondary btn-sm dropdown-toggle asignarbtn" data-toggle="collapse" href="#collapseExample-addProfile-{{$us->id}}-{{$us->pivot->teamrole_id}}" role="button" aria-expanded="false" aria-controls="collapseExample" data-userId ="{{$us->id}}"  data-role="{{$us->pivot->teamrole_id}}"  onclick="addProfile({{$us->id}},{{$us->pivot->teamrole_id}})" style="margin-top: 6%;color:rgb(221, 221, 221) !important">

Agregar perfiles
                    </button>
                </p>
                <div class="collapse " id="collapseExample-addProfile-{{$us->id}}-{{$us->pivot->teamrole_id}}">
                    <div class="card card-body" style="width: 100%;">
                        <select class="js-example-placeholder-multiple selectaddprofile" multiple="multiple" style="width: 60%" id="selectaddprofile-{{$us->id}}-{{$us->pivot->teamrole_id}}">
                            <option></option>
                            @foreach($arrayperfil as $p)
                                <option  value="{{$p['id']}}">{{$p['area']}}</option>
                                @endforeach
                        </select>
                        <button class="btn btn-secondary btn-sm" id="profiletag-{{$us->id}}-{{$us->pivot->teamrole_id}}" style="">+</button>
                        <div>
                            <div class="btn-group btn-group-sm" role="group" aria-label="..."style="margin-top: 2%">


                                @if(isset($autotag_profile))


                                    @foreach($autotag_profile as $tag)

                                        @foreach ($tag->profile as $p)

                                            @if($tag->user_id == $us->id && $tag->teamrole_id == $us->pivot->teamrole_id)

                                                <div id="tagaddprofile-{{$p->id}}-{{$us->id}}-{{$us->pivot->teamrole_id}}" class="contadorasignados" data-tiene="si">
                                                   <button class="badge badge-info btn-sm " id="btntagprofile-{{$p->id}}-{{$us->id}}-{{$us->pivot->teamrole_id}}"  title="{{$p->area}}" style="background-color:#cdc5b9 ;color: #454c48" >
                                                       {{ $app['utils']->cutText( $p->area,20) }}&nbsp
                                                       <span class="glyphicon glyphicon-remove " aria-hidden="true" title="Eliminar perfil" style="color: #454c48" onClick="untagProfile({{$p->id}},{{$us->id}},{{$us->pivot->teamrole_id}})" > </span>
                                                   </button>
                                                </div>

                                            @endif

                                        @endforeach
                                    @endforeach
                                @endif

                                    <div id="tagaddprofile-{{$us->id}}-{{$us->pivot->teamrole_id}}"  ></div>
                            </div>
                        </div>
                    </div>
                </div>
            </td>

                {{-- fin addprofile--}}
            <td class="text-center">

                <a class="deleteUser" href="#" data-userUnitId ="{{$us->pivot->id}}"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> &nbsp;Eliminar</a>
            </td>
        </tr>
        @endforeach
        </tbody>
    </table>

    <form action="{{URL::to('/')}}/admin/unit/add-user" method="POST">
        <input type="hidden" name="unit_id" value="{{ $unit->id }}">
        <select class="js-example-data-array" name="user_id" id="">
            @foreach($users as $us)
                <option value="{{$us->id}}">{{ $us->name }} {{ $us->surname }}</option>
            @endforeach
        </select>

        <select  name="teamrole_id" id="">
            @foreach($teamroles as $teamrole)

                @if($teamrole->eligible ==1)

                    <option value="{{$teamrole->id}}">{{ $teamrole->name }}</option>
                @endif
            @endforeach
        </select>
        <input type="hidden" name="_token" value="{{ csrf_token() }}">

        <input type="button" onclick="form.submit()" name="submit_2" value="{{ __('s.send') }}">

    </form>
@endsection
@section('scripts')
<script src="{{ URL::to('/') }}/js/vendor/jquery-palette-color-picker/palette-color-picker.js"></script>

<script>

        $(document).ready(function(){


            $( ".contadorasignados" ).each(function( i ) {

                if($(this).data("tiene")=="si"){

                    $(this).parent().parent().parent().parent().prev().children().html("Ver perfiles");


                }
            });

            $(".asignarbtn").css("color","#454c48");


            $('[name="color"]').paletteColorPicker({
//                colors: [
//                    {"primary": "#E91E63"},
//                    {"primary_dark": "#C2185B"},
//                    {"primary_light": "#F8BBD0"},
//                    {"accent": "#CDDC39"},
//                    {"primary_text": "#212121"},
//                    {"secondary_text": "#727272"},
//                    {"divider": "#B6B6B6"}
//                ],
                // Add custom class to the picker
                custom_class: 'double',
                // Force the position of picker's bubble
                position: 'downside', // default -> 'upside'
                // Where is inserted the color picker's button, related to the input
                insert: 'after', // default -> 'before'
                // Don't add clear_btn
                clear_btn: 'last', // null -> without clear button, default -> 'first'
                // Timeout for the picker's fade out in ms
                timeout: 2000, // default -> 2000
                // Forces closin all bubbles that are open before opening the current one
                close_all_but_this: false, // default is false
                // Sets the input's background color to the selected one on click
                // seems that some users find this useful ;)
                set_background: false, // default is false

                // Events
                // Callback on bubbl show
                onbeforeshow_callback: function( what ) {
                    console.log(what);
                },

                // Callback on change value
                onchange_callback: function( clicked_color ) {
                    console.log(clicked_color);
                }
            });


            $('.deleteUser').click(function(ev){

                ev.preventDefault();
                var userUnit_id =$(this).attr('data-userUnitId');

                $.ajax({
                    type: 'POST',
                    url: '{{ URL::to('/') }}/admin/unit/delete-user',
                    data:{id_userUnit :userUnit_id},
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },

                    success: function (data) {
                        // on success use return data here
                        var data = JSON.parse(data);


                        $('tr[data-rel="'+ data.deleted +'"]').remove()


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



            })

        });


//prueba

    //etiquetar pipeline
//        $('.pipelineTag').select2({
//            placeholder:'Seleccione ...',
//        });


        function addPipeline(e,id,teamrole_id) {

            $('#selectPipeline'+id+'-'+teamrole_id).show();
            $(e).hide();
        }

        var pipelineSelect = $(".js-example-data-array");


        pipelineSelect.select2({
        placeholder: 'Seleccione...',
        });



        var pipelineArray =[];//arreglo global ,guarda usuarios etiquetados


        pipelineSelect.on('select2:select', function (e) {

            pipelineArray.push(e.params.data.id);//agrego al arreglo los pipeline seleccionados

        });

        pipelineSelect.on('select2:unselect', function (e) {

            var noPipeline = e.params.data.id;

            if (noPipeline != null) {

                for (var x = 0; x < pipelineArray.length; x++) {

                    if (noPipeline == pipelineArray[x]) {
                        //                        console.log(noUser,userArray[x]);
                        pipelineArray[x] = null;
                    }

                }
            }
        });




   function autoTag(id,teamrole_id) {



        pipelineSelect.select2('val', 'all');

            var user_id =id;
            var teamrole_id =teamrole_id;
            var unit = '{{ $unit->id }}';


        if (pipelineArray.length > 0) {
//            console.log(pipelineArray);

            $.ajax({

                data: {user_id: user_id, unit_id: unit, pipelines: pipelineArray,teamrole_id :teamrole_id},
                type: "post",
                url: '{{ URL::to('/') }}/admin/tagPipeline',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },

                success: function (data) {

                    var pipelines = data;
                    $('#selectPipeline' + id+'-'+teamrole_id).hide();
                    $('#tabla_pipelinetags_ajax-' + id+'-'+teamrole_id).show();
                    $('.addPipelineButton-'+id+'-'+teamrole_id+'>.btn').show();


                    if (pipelines.length > 0) {

                        for (var x = 0; x < data.length; x++) {
                            $('#tabla_pipelinetags_ajax-' + id+'-'+teamrole_id).append('<span id="pipeButton'+pipelines[x][1]+'-'+user_id+'-'+teamrole_id+'" class="glyphicon-class">' +
                                '<button class="badge " style="color: #454c48;background-color: #b5cbe3">' +
                                '<label>' + pipelines[x][0] +'&nbsp&nbsp</label>' +
                                '<span onClick="untagPipeline('+pipelines[x][1]+','+user_id+','+teamrole_id+')" class="glyphicon glyphicon-remove" aria-hidden="true" title="Eliminar"></span>' +
                                '</button>' +
                                '</span>');

                        }

                        pipelineArray = [];
                    }else{
                        alert("Debe seleccionar un pipeline diferente");
                    }

                 }

            });
        }
    }


    /***
     * @param id_pipeline
     * @param user_id
     * @post Remueve la etiqueta del pipeline seleccionado
     *
     */
    var flag = 0
    function untagPipeline(id_pipeline,user_id,teamrole_id) {




        if (flag == 0) {
            flag = 1;

            $.ajax({

                data: {id_pipeline: id_pipeline, user_id: user_id, unit_id: '{{$unit->id}}',teamrole_id :teamrole_id},
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                },
                dataType: 'json',
                url: "{{ URL::to('/') }}/admin/untagPipeline",
                type: 'POST',
                success: function (data) {

                    $('#pipeButton' + data + '-' + user_id+'-'+teamrole_id).remove();
                    flag = 0;
                },
                error: function (xhr, type, exception) {
                    // if ajax fails display error alert
                    flag=0;
                    alert("se ha eliminado la etiqueta ");
                }
            });
        }


    }

        $('.selectaddprofile').select2({
            placeholder:"Seleccione perfil",

        });


        //etiquetar perfil
        function addProfile(user_id,teamrole_id) {



            $('#selectaddprofile-'+user_id+'-'+teamrole_id).select2('val', 'all');

//         $("#addProfile-"+id+"-"+teamrole_id).click(function () {


            //        $(".addprofile").select2({
            //            templateSelection: profileOfUser,
            //
            //        });

            var arrayProfile =[];
            var unit = '{{ $unit->id }}';

            $('#selectaddprofile-'+user_id+'-'+teamrole_id).on('select2:select', function (e) {

                arrayProfile.push(e.params.data.id);

            });

            $('#selectaddprofile-'+user_id+'-'+teamrole_id).on('select2:unselect', function (e) {

                var i = arrayProfile.indexOf(e.params.data.id);//busca el indice del arreglo donde esta el id

                arrayProfile[i] = null;

            });

//                     console.log(arrayProfile);

            $("#profiletag-"+user_id+"-"+teamrole_id).click(function () {

                $('#selectaddprofile-'+user_id+'-'+teamrole_id).select2('val', 'all'); //limpia el select

                console.log(arrayProfile);

                $.ajax({
                    type: 'POST',
                    url: '{{ URL::to('/') }}/admin/unit/add-profile',
                    //falta agregar unit
                    data:{ids_profile :arrayProfile, user_id:user_id, unit_id: unit, teamrole_id :teamrole_id},
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },

                    success: function (data) {
                        // on success use return data here
//
                        var profiles =data;
                        if (profiles.length > 0) {

                            for (x in profiles) {

                                $('#tagaddprofile-'+user_id+'-'+teamrole_id).append('<button class="badge badge-info btn-sm " id="btntagprofile-'+profiles[x][2]+'-'+user_id+'-'+teamrole_id+'" title=" '+profiles[x][1]+' " style="background-color:#cdc5b9 ;color: #454c48" >'+profiles[x][0]+
                                    '&nbsp <span class="glyphicon glyphicon-remove " aria-hidden="true" title="Eliminar perfil" style="color: #454c48 " onClick="untagProfile('+profiles[x][2]+','+user_id+','+teamrole_id+')"> </span>');

                            }
                        }
                    },

                });
            });

        }

        /***
         * @param id_profile
         * @param user_id
         * @post Remueve la etiqueta del profile seleccionado
         *
         */
        var flag = 0
        function untagProfile(id_profile,user_id,teamrole_id) {




            if (flag == 0) {
                flag = 1;

                $.ajax({

                    data: {id_profile: id_profile, user_id: user_id, unit_id: '{{$unit->id}}',teamrole_id :teamrole_id},
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    },
                    dataType: 'json',
                    url: "{{ URL::to('/') }}/admin/untagProfile",
                    type: 'POST',
                    success: function (data) {

//                        console.log(data);
                        $('#btntagprofile-'+id_profile+'-'+user_id+'-'+teamrole_id).remove();
                        flag = 0;
                    },
                    error: function (xhr, type, exception) {
                        // if ajax fails display error alert
                        flag=0;
                        alert("se ha eliminado la etiqueta ");
                    }
                });
            }


        }


</script>

@endsection
