@extends('Layout.master')

@section('title', 'Edit group')

@section('content')

    <section id="content">
        <form method="POST" role="form" class="vbox form-horizontal clearfix">
            {{--{{ @csrf_field() }}--}}
            <section class="scrollable padder">
                <ul class="breadcrumb no-border no-radius b-b b-light pull-in">
                    <li><a href="."><i class="fa fa-home"></i>Home</a></li>
                    <li><a href="/deductions">Deductions</a></li>
                    <li>Edit group</li>
                </ul>
                <section class="panel panel-default">
                    <header class="panel-heading text-right bg-light">
                        <ul class="nav nav-tabs pull-left">
                            <li class="active" style="border-right:1px solid rgba(0,0,0,0.1);"><a href="#multiple-employees" data-toggle="tab"><b>Multiple employees</b></a></li>
                        </ul>
                        <span class="hidden-sm" style="color:white;">Select an assignment type</span>
                    </header>
                    <div class="panel-body">
                        <div class="tab-content">
                            <div class="tab-pane fade active in" id="multiple-employees">
                                <div class="col-md-3 no-padder">
                                    <?php $tabulation_type = $_GET['tblt'] ?>
                                    @if($tabulation_type !== '3')
                                        <section class="panel panel-default col-md-12 no-padder">
                                                <header class="panel-heading font-semibold">
                                                    Deduction
                                                </header>
                                                <div class="panel-body no-padder" style="margin-bottom:10px;">
                                                    <div class="col-md-12">
                                                        <label class="control-label"></label>
                                                        <input id="deduction_value" type="number" class="form-control" placeholder="Enter an amount here" value="{{ $group->value }}">
                                                    </div>
                                                </div>
                                        </section>
                                    @endif
                                    <section class="panel panel-default col-md-12 no-padder" style="margin-right:30px;">
                                        <header class="panel-heading font-semibold">
                                            Filter
                                        </header>
                                        <div class="panel-body range-preview clearfix">
                                            @include('Layout.errors')
                                            <div class="col-md-12">
                                                <label class="control-label">Scope</label>
                                                <select id="scope" class="form-control">
                                                    <option value="1">Organization</option>
                                                    <option value="2">Business unit</option>
                                                    <option value="3">Resident employees</option>
                                                    <option value="4">Seconded employees</option>
                                                </select>
                                            </div>
                                            <div class="col-md-12 business-unit" style="display:none;">
                                                <label class="control-label">Business unit</label>
                                                <select id="business_unit" class="form-control">
                                                    <option value=""></option>
                                                </select>
                                            </div>
                                            <div class="col-md-12">
                                                <label class="control-label">Department</label>
                                                <select id="department" class="form-control">
                                                    <option value="0">All departments</option>
                                                    @foreach($departments as $department)
                                                        <option value="{{ $department->id }}">{{ $department->department_name }}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            <div class="col-md-12" style="margin-top:10px;">
                                                <div class="pull-right" id="error">
                                                    <a href="/deductions"  class="btn btn-default filter-employees"><i class="fa fa-filter"></i>Filter</a>
                                                </div>
                                            </div>
                                        </div>
                                    </section>
                                </div>
                                <div class="col-md-9 no-padder pull-right">
                                    <section class="panel panel-default col-md-5 no-padder" style="margin-left:30px;">
                                        <header class="panel-heading font-semibold">
                                            Filtered results
                                        </header>
                                        <div class="panel-body">
                                            <div class="col-md-12 no-padder" style="margin-bottom:15px;">
                                                <input type="text" class="form-control search-filter" placeholder="Search" data-container="selected">
                                            </div>
                                            <div class="col-md-12 employee-list no-padder selected" id="filtered-employees">

                                            </div>
                                        </div>
                                        <div class="col-md-12" style="margin-bottom:10px;border-top:1px solid rgba(0,0,0,0.08);padding-top:10px;">
                                            <div class="pull-right">
                                                <span class="btn btn-default move-all"><i class="fa fa-arrow-circle-o-right"></i>Move All</span>
                                                <span class="btn btn-default move-selected"><i class="fa fa-arrow-circle-o-right"></i>Move selected</span>
                                            </div>
                                        </div>
                                    </section>
                                    <section class="panel panel-default col-md-6 no-padder pull-right">
                                        <header class="panel-heading font-semibold">
                                            Selected employees
                                        </header>
                                        <div class="panel-body">
                                            <div class="col-md-12 no-padder" style="margin-bottom:15px;">
                                                <input type="text" class="form-control search-filter" placeholder="Search" data-container="filtered">
                                            </div>
                                            <div class="col-md-12 employee-list no-padder filtered" id="selected-employees">
                                                <?php
                                                    for ($i=0;$i<count($employee_names);$i++){
                                                        echo
                                                        "
                                                            <div class='checkbox'>
                                                                <label>
                                                                    <input class='selected-employees' type='checkbox' data-employee-id='{$employee_names[$i]['id']}' data-employee-name='{$employee_names[$i]['name']}'>
                                                                    {$employee_names[$i]['name']}
                                                                    </label>
                                                                <i class='fa fa-times-circle-o remove-single-employee' data-employee-id='{$employee_names[$i]['id']}'></i>
                                                            </div>
                                                        ";
                                                    }
                                                ?>
                                            </div>
                                        </div>
                                        <div class="col-md-12" style="margin-bottom:10px;border-top:1px solid rgba(0,0,0,0.08);padding-top:10px;">
                                            <div class="pull-right">
                                                <a href="javascript:void(0);"  class="btn btn-default remove-all-employees"><i class="fa fa-times-circle-o"></i>Remove all</a>
                                                <a href="javascript:void(0);"  class="btn btn-default remove-selected-employees"><i class="fa fa-times-circle-o"></i>Remove selected</a>
                                            </div>
                                        </div>
                                    </section>
                                    <div class="col-md-12 no-padder clearfix">
                                        <div class="pull-right">
                                            <a href="/deductions" class="btn btn-default"><i class="fa fa-close"></i> Close</a>
                                            <span class="btn btn-success update-group-members" data-group-id="{{ request()->route('group_id') }}"><i class="fa fa-save"></i> Save</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>
            </section>
            <a href="#" class="hide nav-off-screen-block" data-toggle="class:nav-off-screen, open" data-target="#nav,html"></a>
        </form>
    </section>

@endsection

{{--@section('footer-include')

@endsection--}}

@section('j-script')
    <!-- Jquery -->
    <script>

        $(document).on('ready', function(){
            $.expr[":"].contains = $.expr.createPseudo(function(arg){
                return function(elem){
                    return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
                }
            });

            //Filter the people in the list using a wildcard
            $('.search-filter').on('keyup', function(){
                let searchText = $(this).val().trim();

                let container = $(this).data('container');
                let parent = $('.' + container + ' div');
                let searchElements = $('.' + container + ' div label:contains(\'' + searchText + '\')');

                if (!searchText){
                    parent.css({'display':'block'});
                    return false;
                }

                parent.css({'display':'none'});
                searchElements.parent().css({'display':'block'});
            });

            //Move a single employee
            $(document).on('click', '.move-single-employee', function(){
                let employeeName = $(this).data('employee-name');
                let employeeId = $(this).data('employee-id');

                let newEmployee = "<div class='checkbox' style='color:blue;'>\n" +
"                                       <label>\n" +
"                                           <input class='selected-employees' type='checkbox' data-employee-id='" + employeeId + "' data-employee-name='" + employeeName + "'>\n" +
"                                           " + employeeName + "\n" +
"                                       </label>\n" +
"                                       <i class='fa fa-times-circle-o remove-single-employee' data-employee-id='" + employeeId + "'></i>\n" +
"                                  </div>";

                $('#selected-employees').prepend(newEmployee);
                $(this).parent().remove();
            });

            //Remove a selected employee
            $(document).on('click', '.remove-single-employee', function(){
                $(this).parent().remove();
            });

            //Remove selected employee(s)
            $(document).on('click', '.remove-selected-employees', function(e){
                e.preventDefault();

                removeSelectedEmployees();
            });

            //Remove all selected employees
            $(document).on('click', '.remove-all-employees', function(e){
                e.preventDefault();
                let selectedEmployees = $('.selected-employees');
                selectedEmployees.prop('checked', true);

                removeSelectedEmployees();
            });

            function removeSelectedEmployees(){
                let selectedEmployeesEl = $('.selected-employees:checked');

                selectedEmployeesEl.parent().parent().remove();
            }

            //Move multiple employees
            $(document).on('click', '.move-selected', function(){
                moveSelectedEmployees();
            });

            $(document).on('click', '.move-all', function(){
                let filteredEmployees = $('.filtered-employees');
                filteredEmployees.prop('checked', true);

                moveSelectedEmployees();
            });

            function moveSelectedEmployees(){
                let filteredEmployeesEl = $('.filtered-employees:checked');
                let filteredEmployees = filteredEmployeesEl.map(function(){
                    return $(this).data('employeeName');
                });
                let filteredEmployeeIds = filteredEmployeesEl.map(function(){
                    return $(this).data('employeeId');
                });

                if (filteredEmployees.length === 0){
                    alert("Please select at least 1 employee to move");
                    return false;
                }

                for (i=0;i<filteredEmployees.length;i++){
                    let employeeName = filteredEmployees[i];
                    let employeeId = filteredEmployeeIds[i];

                    let newEmployee = "<div class='checkbox' style='color:blue;'>\n" +
    "                                       <label>\n" +
    "                                           <input class='selected-employees' type='checkbox' data-employee-id='" + employeeId + "' data-employee-name='" + employeeName + "'>\n" +
    "                                           " + employeeName + "\n" +
    "                                       </label>\n" +
    "                                       <i class='fa fa-times-circle-o remove-single-employee' data-employee-id='" + employeeId + "'></i>\n" +
    "                                  </div>";

                    $('#selected-employees').prepend(newEmployee);
                }

                filteredEmployeesEl.parent().parent().remove();
            }

            $(document).on('click', '.update-group-members', function(e){
                e.preventDefault();

                let el = $(this);

                let selectedEmployees = $('.selected-employees').map(function(){
                    return $(this).data('employeeId');
                });

                if (selectedEmployees.length < 1){
                    alert('Please selected at least 1 employee to add to this group');
                    console.log('Not enough data to perform requested operation');
                    return false;
                }

                let employeeArray = [];
                for (i=0;i<selectedEmployees.length;i++){
                    employeeArray.push(selectedEmployees[i]);
                }

                selectedEmployees = employeeArray.join(',');

                let deductionValueEl = $('#allowance_value');
                let deductionValue = "";

                if (deductionValueEl.length){
                    deductionValue = deductionValueEl.val().trim();
                    if (deductionValue === ""){
                        alert("Please provide an allowance value");
                        return false;
                    }
                }

                let saveSelectedEmployeesRequest = $.ajax({
                    type:'POST',
                    url:'/allowances/employees/update_group_members',
                    data:{
                        groupId:el.data('groupId'),
                        allowanceValue:deductionValue,
                        selectedEmployees:selectedEmployees,
                        payrollItem:'deduction'
                    },
                    dataType:'json',
                    timeout:10000,
                    beforeSend:function(){
                        el.addClass('disabled');
                    },
                    success:function(response){
                        el.removeClass('disabled');
                        if (response.status !== 1){
                            alert(errorMessage);
                        }
                    },
                    error(x,t,m){
                        el.removeClass('disabled');
                        if (t === "timeout"){
                            saveSelectedEmployeesRequest.abort();
                            console.log('Request time out');
                        }
                    }
                });
            });

            $(document).on('change', '#scope', function(){
                let businessUnitEl = $('.business-unit');

                if ($(this).val() === '2'){
                    businessUnitEl.css({
                        'display':'block'
                    });
                    return true;
                }

                businessUnitEl.css({
                    'display':'none'
                });
            });

            $(document).on('click', '.filter-employees', function(e){
                e.preventDefault();

                let el = $(this);
                let filteredEmployees = $('#filtered-employees');

                let scope = $('#scope').val();
                let department = $('#department').val();
                let businessUnit = '';

                if (scope === '2'){
                    businessUnit = $('business_unit').val();
                }

                let filterEmployeesRequest = $.ajax({
                    type:'POST',
                    url:'/allowances/employees/filter_employees',
                    data:{
                        scope:scope,
                        businessUnit:businessUnit,
                        department:department
                    },
                    dataType:'json',
                    timeout:10000,
                    beforeSend:function(){
                        el.addClass('disabled');
                    },
                    success:function(response){
                        if (response.status === 1){

                            filteredEmployees.empty();
                            let results = response.results;
                            for(i=0;i<results.length;i++){
                                filteredEmployees.append(
                                    "<div class='checkbox'>\n" +
"                                        <label>\n" +
"                                            <input class='filtered-employees' name='filtered-employees[]' type='checkbox' data-employee-name='" + results[i].last_name.toUpperCase() + ", " + results[i].first_name.charAt(0).toUpperCase() + results[i].first_name.slice(1) + "' data-employee-id='" + results[i].id + "'>\n" +
"                                            " + results[i].last_name.toUpperCase() + ", " + results[i].first_name.charAt(0).toUpperCase() + results[i].first_name.slice(1) + "\n" +
"                                        </label>\n" +
"                                        <i class='fa fa-arrow-circle-o-right move-single-employee' data-employee-name='" + results[i].last_name.toUpperCase() + ", " + results[i].first_name.charAt(0).toUpperCase() + results[i].first_name.slice(1) + "' data-employee-id='" + results[i].id + "'></i>\n" +
"                                    </div>"
                                )
                            }
                        }else{
                            alert(errorMessage);
                        }
                    },
                    error(x,t,m){
                        el.removeClass('disabled');
                        if (t === "timeout"){
                            filterEmployeesRequest.abort();
                            console.log('Request time out');
                        }
                    }
                });
            });

        });
    </script>
@endsection