@extends('layouts.app')

@section('styles')
    <style>
        .dataTables_wrapper,#DataTables_Table_0_wrapper{margin-top: 25px !important;}
    </style>
@endsection

@section('content')


<?php $tablecount= 0; ?>
    @if(!$user->isTeamMemberAtAnyUnit() || $user->permissionToTask())
        <div class="alert alert-success" role="alert" style="display: none">...</div>
    <div>
        <ul class="nav nav-tabs" role="tablist">
            @foreach($units as $unit)
                <?php if ($openunit == $unit->id) {
                    $active = 'active';
                } else {
                    $active = '';
                } ?>


                <li role="presentation" class="">
                    <a href="#" data-pane="{{ $unit->slug }}" class="nav-tab-trigger {{$active}}"
                       style="background-color: {{ $unit->color }}!important;color:#fff;border:1px solid {{ $unit->color }};"
                       aria-controls="{{ $unit->slug }}" role="tab" data-toggle="tab">
                        {{ $unit->name }}
                    </a>
                </li>
            @endforeach
            <li role="presentation" class="">
                <a href="#" data-pane="todas" class="nav-tab-trigger"
                   style="background-color: {{ $unit->color }}!important;color:#fff;border:1px solid {{ $unit->color }};"
                   aria-controls="todas" role="tab" data-toggle="tab">
                    Todas
                </a>
            </li>
        </ul>

        <div class="dropdown functional-unit">
          <div class="btn-group">
                  <button type="button" class="btn btn-default" data-toggle="dropdown">Seleccionar unidad funcional</button>
                  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                    <span class="sr-only">Toggle Dropdown</span>
                  </button>
                  <ul class="dropdown-menu">
                    @foreach($units as $unit)
                        <?php if ($openunit == $unit->id) {
                            $active = 'active';
                        } else {
                            $active = '';
                        } ?>


                        <li role="presentation" class="">
                            <a href="#" data-pane="{{ $unit->slug }}" class="nav-tab-trigger {{$active}}"
                               style="background-color: {{ $unit->color }}!important;color:#fff;"
                               aria-controls="{{ $unit->slug }}" role="tab" data-toggle="tab">
                                {{ $unit->name }}
                            </a>
                        </li>
                    @endforeach
                    <li role="presentation" class="">
                        <a href="#" data-pane="todas" class="nav-tab-trigger"
                           style="background-color: {{ $unit->color }}!important;color:#fff;border:1px solid {{ $unit->color }};"
                           aria-controls="todas" role="tab" data-toggle="tab">
                            Todas
                        </a>
                    </li>
                  </ul>
                  <!-- <ul class="dropdown-menu" role="menu">
                    <li><a href="#">Action</a></li>
                    <li><a href="#">Another action</a></li>
                    <li><a href="#">Something else here</a></li>
                    <li class="divider"></li>
                    <li><a href="#">Separated link</a></li>
                  </ul> -->
          </div>
          <!-- <a class="dropdown-toggle btn" data-toggle="dropdown" href="#" aria-expanded="false">
            Seleccionar unidad funcional <span class="caret"></span>
          </a> -->

        </div>
    </div>

    @foreach($units as $index=>$unit)
        <?php if ($openunit == $unit->id) {
            $display = 'block';
        } else {
            $display = 'none';
        } ?>

        <div role="tabpanel" class="tab-pane" id="{{ $unit->slug }}" style="display:{{$display}}">
            <br>
            <div class="task-header-actions">

                <h4>{{ $unit->name }}</h4>
                @if (session('status'))
                    <div style="margin-bottom:20px;"class="alert alert-success alert-dismissable">
                        <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                        {{ session('status') }}
                    </div>
                @endif
                <div class="">

                    @if($unit->slug == 'pre-ingreso')
                        <a class="btn btn-default" href="{{URL::to('/') }}/tasks/uninitiated">Abiertas</a>
                        <a class="btn btn-default" href="{{URL::to('/') }}/tasks/in-progress">En curso</a>
                    @else
                        <a class="btn btn-default" href="{{URL::to('/') }}/tasks/unit/{{ $unit->id }}/show">Abiertas</a>
{{--                        <a class="btn btn-default" href="{{URL::to('/') }}/tasks/status/3/unit/{{ $unit->id }}/show">Cerradas</a>--}}
                        <a class="btn btn-default" href="{{ URL::to('/') }}/filterTask/{{ $unit->id }}/3">Cerradas</a>
                    @endif
<br>
                    @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($user->can('create-task') || $user->hasRole('administrator') || $user->hasRole('supervisor') || $user->hasRole('teamleader'))
                        <a class="btn btn-default" href="{{URL::to('/') }}/tasks/teamLeader">Crear tarea</a>

                    @endif
                </div>

            </div>



            @if(count($unit->$filtertasks) != 0 )

            <?php $tablecount++ ?>

                <table id="table{{ $tablecount }}" style="margin-top: 30px;" class="large-only table table-condensed table-data" data-order='[[ 2, "desc" ]]' data-page-length='30'>
                    <thead style="border-bottom:2px solid #ddd;">
                    <th>Título</th>
                    <th>Líneas de producción</th>{{--****--}}
                    <th>Entrada</th>
                    <th>Salida</th>
                    <th>Unidad</th>
                    <th>Estado</th>
                    <th>Acción</th>
                    <th>Pipeline</th> {{----*****-----}}
                    </thead>
                    <tbody>


                    @foreach($unit->$filtertasks as $task)
                        <tr id="fila-{{$task->id}}" >
                            <td style="padding:10px 4px;"> {{ $task->taskdata->title }}</td>
                            <td> {{ $task->pipeline->first()->name }}</td>
                            <td>{{ date('d-m-Y H:i', strtotime(str_replace('/', '-', $task->created_at))) }}</td>
                            <td></td>
                            <td> {{ $task->unit->name }}</td>

                            @if ($unit->id == 1 && ($task->status->id == 1 ||$task->status->id == 5)){{--valor 1 corresponde a unidad ingreso----}}
                                <td>
                                    <div class="js-example-basic"  style="width: auto">
                                        <select id="statu-{{$task->id}}" class="js-example-data" data-data="{{$task->id}}"  name="status" style="width: 80%;float:right">

                                            <option value="">Seleccione estado...</option>
                                            @foreach($status as $key => $statu)

                                                <option value="{{$statu->id}}"

                                                    @if ($statu->id == $task->status_id)
                                                        selected="selected"
                                                    @endif
                                                    >{{$statu->name}}</option>
                                            @endforeach

                                        </select>
                                    </div>
                                </td>{{---{{ $task->status->name }}------------}}
                            @else

                                <td>{{ $task->status->name }}</td>
                            @endif
                            <td>
                                <a href="{{URL::to('/')}}/tasks/{{ $task->id }}/unit/{{ $unit->id }}/show"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> &nbsp;Ver tarea</a>
                            </td>

                            <td>
                                <ul class="pipeline-timeline">
                                   {{----*****-----}}

                                    @foreach($task->pipeline->first()->unitsByRevision($task->pipelineRevision) as $u)


                                        <?php
                                        $circle = "fa-circle-o";
                                        $active = '';
                                        if ($u->id == $task->unit->id) {
                                            $active = 'active';
                                            $circle = "fa-circle";
                                        }
                                        ?>

                                        <li data-unit="{{ $u->name }}" data-toggle="tooltip" title="{{ $u->name }}" class="{{ $active }}">
                                            <a href="{{ URL::to('/') }}/tasks/{{ $task->id }}/unit/{{ $u->id }}/show">
                                                <i style="color:{{ $u->color }};" class="fa {{ $circle }}" aria-hidden="true"></i>
                                            </a>
                                        </li>

                                    @endforeach
                                    {{----*****-----}}
                                </ul>

                            </td>
                        </tr>

                    @endforeach


                    </tbody>
                </table>

            @else

                <div class="panel" style="margin-top:30px;padding:16px"> No hay tareas por el momento</div>
            @endif

        </div>






    @endforeach
    <div role="tabpanel" class="tab-pane" id="todas" style="display:none">
        <div class="task-header-actions">

            <h4>Todas las Tareas</h4>
            <div class="">
                {{--<a class="btn btn-default" href="{{URL::to('/') }}/tasks/unit/{{ $unit->id }}/show">Abiertas</a>--}}
                {{--                <a class="btn btn-default" href="{{URL::to('/') }}/tasks/status/3/unit/{{ $unit->id }}/show">Cerradas</a>--}}
            </div>

        </div>

        {{-- Table responsive --}}
        <div class="">
            <a class="btn btn-default" href="{{URL::to('/') }}/tasks/unit/{{ $unit->id }}/show">Abiertas</a>
            <a class="btn btn-default" href="{{URL::to('/') }}/tasks/status/3/unit/{{ $unit->id }}/show">Cerradas</a>
        </div>

        <?php $tablecount++ ?>

        <table id="table{{ $tablecount }}" style="margin-top: 30px;" class="large-only table table-condensed table-data" data-order='[[ 2, "desc" ]]' data-page-length='30'>
            <thead style="border-bottom:2px solid #ddd;">
            <th>Título</th>
            <th>Líneas de producción</th>{{--****--}}
            <th>Entrada</th>
            <th>Deadline</th>
            <th>Unidad</th>
            <th>Estado</th>
            <th>Pipeline</th>
            </thead>
            <tbody>

            @foreach($alltasks as $t)
                @if(isset( $t->unit))
                <tr>
                    <td>
                        {{ $t->taskdata->title }}
                    </td>
                    <td> {{  $t->pipeline->first()->name }} </td>
                    <td>{{ date('d-m-Y H:i', strtotime(str_replace('/', '-', $t->created_at))) }}</td>

                    @if($t->deadline)
                        <td> {{$t->deadline }}</td>
                    @elseif($t->taskdata->deadline)
                        <td> {{$t->taskdata->deadline }}</td>
                    @else
                        <td></td>
                    @endif
                    <td> {{ $t->unit->name }} </td>
                    <td> {{ $t->status->name }}</td>
                    <td>
                        <ul class="pipeline-timeline">

                            @foreach($t->pipeline->first()->unitsByRevision($t->pipelineRevision) as $u)
                                <?php
                                $circle = "fa-circle-o";
                                $active = '';
                                if ($u->id == $t->unit->id) {
                                    $active = 'active';
                                    $circle = "fa-circle";
                                }
                                ?>

                                <li data-unit="{{ $u->name }}" data-toggle="tooltip" title="{{ $u->name }}" class="{{ $active }}">
                                    <a href="{{ URL::to('/') }}/tasks/{{ $t->id }}/unit/{{ $u->id }}/show">
                                        <i style="color:{{ $u->color }};" class="fa {{ $circle }}" aria-hidden="true"></i>
                                    </a>
                                </li>
                            @endforeach
                        </ul>

                    </td>


                </tr>
                @endif
            @endforeach
            </tbody>
        </table>

    </div>
    @else
        <div class="container">
            <div class="row" style="width:100%;">
                <div class="col-md-10 col-md-offset-1">
                    <div class="panel panel-default" style="width: 120%; padding: 3%">
        <div>
            <h5>No tienes permisos para ver este panel,<a href="{{ URL::to('/') }}/mytasks" >
                    <span class="item-text">regresar a <i>"Mis Tareas"</i></span></a>. </h5>
        </div>
                    </div>
                </div>
            </div>
        </div>
    @endif
@endsection
@section('scripts')
<script>

$(document).ready(function () {



            for (i = 0; i < {{ $tablecount }}; i++) {

               $('#table'+(i+1)).stacktable({myClass:'stacktable small-only'});

            }


//            $('.tab-pane').not('').css({'display': 'none'});
            $('.nav-tab-trigger').click(function (ev) {
                $('.tab-pane').css({'display': 'none'});
                $('.nav-tab-trigger').removeClass('active');
                $(this).addClass('active');

                ev.preventDefault();
                var pane = $(this).attr('data-pane');
//                console.log(pane);

                $('#' + pane).css({'display': 'block'});
            })

    //----------------select of status --------------------//(3 cerrada,6 cancelada,1 abierta,5 en espera)task

    var selects = [];
    var eventSelects = [];
    $('select').each(function(index,element){
//        console.log(element)
        selects[index]=$(element).select2();
//        console.log(selects[index])
        // eventSelects[index] =
        selects[index].on('select2:select',function(ev){

//            console.log($(element).data("data")+"dddd");//valor del id de la tarea

//            console.log(index,element,ev.params.data.id)
            var status = ev.params.data.id

            if(status) {

                if (status == 1 || status == 5) {

                    var  task_id =$(element).data("data");

                    changeStatu(status, task_id); // esta función cambia el estado de estado la tarea

                }else if(status == 3 || status == 6) {

                    var task_id = $(element).data("data");
                    changeStatu(status, task_id);

                    $('#fila-'+task_id).remove();
                }
            }
        });


    });
});

/**
 * función cambia el estado de la tarea
 * @param statu_id
 * @param task_id
 */

    function changeStatu(statu_id,task_id) {

        $.ajax({
            type: 'POST',
            url: '{{ URL::to('/') }}/tasks/update-status',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            dataType: 'json',

            data: {id: task_id, status_id: statu_id},

            success: function (data) {
                  console.log(data);

                if(data[0]==200) {

//                    $('#statu-'+task_id).select2('val', statu_id);
                    $(".alert-success").html('Estado actualizado.');
                    $(".alert-success").show(500);
                    setTimeout(function () {
                        $(".alert-success").hide(500)
                    }, 2000);
                }

            }

    });
//        console.log(e,task_id)
    }

    </script>
@endsection
