@extends('layouts.master')

@section('navigation')
    @include('local.managers.admins._navigation')
@stop

@section('main')

<!-- Edit User -->
<div class="modal fade" id="modal-edit-user">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Edit User</h4>
      </div>
        <div class="modal-body">
            {{ Form::open(array('action' => array('UsersController@update'))) }}
                <input name="id" id="id" type="hidden"></input>
                <div class="form-group">
                    <label for="name" class="control-label">Name</label>
                    <p id="name" name="name" class="form-control-static"></p>
                </div>
                <div class="form-group">
                    <label for="" class="control-label">Email</label>
                    <p id="email" name="email" class="form-control-static"></p>
                </div>
                <div class="form-group">
                    {{ Form::label('role', 'Role') }}
                    <select id="role" name="role" class="role form-control">
                        <option value="1">Administrator</option>
                        <option value="2">School Coordinator</option>
                        <option value="3">Program Coordinator</option>
                        <option value="4">Professor</option>
                    </select>
                </div>
                <div class="form-group">
                    {{ Form::label('school', 'School or College') }}
                    <select name="school" class="school form-control">
                        <option value="0">All</option>
                        @foreach ($schools as $school)
                        <option value="{{ $school->id }}">
                        {{ $school->name }}
                        </option>
                        @endforeach
                    </select>
                </div>

                {{ Form::label('program', 'Program(s)') }}
                <div class="programs">
                    <div class="form-group">
                        <select class="program form-control" name="programs[]"></select>
                    </div>
                </div>

                <p id="add-program-wrapper" class="text-right">
                    <button id="add-program" class="add-program btn-xs btn btn-success"><span class="glyphicon glyphicon-plus"></span></button>
                </p>

                <div class="form-group">
                    {{ Form::label('has_access', 'Active (has access)') }}
                    <select name="has_access" id="has_access" class="form-control">
                        <option value="1">Yes</option>
                        <option value="0">No</option>
                    </select>
                </div>
        </div>
      <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button name="submit_roles" class="btn btn-primary" value="Save" type="submit">Save</button>
        {{ Form::close() }}
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<!-- New User -->
<div class="modal fade" id="modal-new-user">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">New User</h4>
      </div>
        <div class="modal-body">
            {{ Form::open(array('action' => array('UsersController@store'))) }}
                <input name="new_id" id="new_id" type="hidden"></input>
                <div class="form-group">
                    <label for="new_first_name" class="control-label">Name</label>
                    {{ Form::text('new_first_name', Input::old('new_first_name'), array('class'=>'form-control'))}}
                </div>
                <div class="form-group">
                    <label for="new_surnames" class="control-label">Surnames</label>
                    {{ Form::text('new_surnames', Input::old('new_surnames'), array('class'=>'form-control'))}}
                </div>
                <div class="form-group">
                    <label for="new_email" class="control-label">Email</label>
                    {{ Form::text('new_email', Input::old('new_email'), array('class'=>'form-control'))}}
                </div>
                <div class="form-group">
                    {{ Form::label('new_role', 'Role') }}
                    <select id="new_role" name="new_role" class="role form-control">
                        <option value="1">Administrator</option>
                        <option value="2">School Coordinator</option>
                        <option value="3">Program Coordinator</option>
                        <option value="4">Professor</option>
                    </select>
                </div>
                <div class="form-group">
                    {{ Form::label('new_school', 'School or College') }}
                    <select id="new_school" name="new_school" class="school form-control">
                        <option value="0">All</option>
                        @foreach ($schools as $school)
                        <option value="{{ $school->id }}">
                        {{ $school->name }}
                        </option>
                        @endforeach
                    </select>
                </div>

                {{ Form::label('new_programs', 'Program(s)') }}
                <div class="programs">
                    <div class="form-group">
                        <select class="program form-control" name="new_programs[]"></select>
                    </div>
                </div>

                <p id="new-add-program-wrapper" class="text-right">
                    <button id="new-add-program" class="add-program btn-xs btn btn-success"><span class="add-program glyphicon glyphicon-plus"></span></button>
                </p>
        </div>
      <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button name="submit_new_user" class="btn btn-primary" value="Save" type="submit">Save</button>
        {{ Form::close() }}
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->



<div class="row">
    <div class="col-md-12">

        @if(count($users))
            <div class="table-responsive">
                <table id="user_table" class="table table-striped table-condensed datatable-user">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>College/School</th>
                            <th>Program(s)</th>
                            <th>Email</th>
                            <th>Role</th>
                            <th>Active</th>
                            <th>Office Phone</th>
                            <th>Cell Phone</th>
                            <th>Edit</th>
                        </tr>
                    </thead>
                    <tfoot>
                        <tr class="column-search">
                            <th><input class="column-search-bar form-control" type="text" placeholder="Search"/></th>
                            <th><select class="column-search-select form-control"><option value=""></option></select></th>
                            <th><input class="column-search-bar form-control" type="text" placeholder="Search"/></th>
                            <th><input class="column-search-bar form-control" type="text" placeholder="Search"/></th>
                            <th><select class="column-search-select form-control"><option value=""></option></select></th>
                            <th><select class="column-search-select form-control"><option value=""></option></select></th>
                            <th><input class="column-search-bar form-control" type="text" placeholder="Search"/></th>
                            <th><input class="column-search-bar form-control" type="text" placeholder="Search"/></th>
                            <th></th>
                        </tr>
                    </tfoot>
                    <tbody>
                        @foreach ($users as $user)
                            <tr>
                                <td data-user-id="{{ $user->id }}" class="user-name">{{ $user->surnames }}, {{ $user->first_name }}</td>

                                <!-- If user has school, set school data -->
                                @if($user->school_id)
                                    <td class="user-school" data-school-id="{{ $user->school_id }}">
                                        {{ $user->school->name }}
                                    </td>
                                @elseif(count($user->programs)>0)
                                    <td class="user-school" data-school-id="{{ $user->programs[0]->school_id }}">
                                        {{ $user->programs[0]->school->name }}
                                    </td>
                                @else
                                    <td>
                                        All
                                    </td>
                                @endif

                                <!-- If user has programs, set program data -->
                                @if(count($user->programs))
                                    <td class="user-program">
                                        @foreach ($user->programs as $program)
                                            <p data-program-id="{{$program->id}}">{{ $program->name }}</p>
                                        @endforeach
                                    </td>
                                @else
                                    <td>
                                        All
                                    </td>
                                @endif

                                <td class="user-email">{{ $user->email }}</td>
                                @if($user->role==4)
                                    <td data-role-number="4" class="user-role">Professor</td>
                                @elseif($user->role==3)
                                    <td data-role-number="3" class="user-role">Program Coordinator</td>
                                @elseif($user->role==2)
                                    <td data-role-number="2" class="user-role">School Coordinator</td>
                                @elseif($user->role==1)
                                    <td data-role-number="1" class="user-role">Administrator</td>
                                @endif

                                @if($user->has_access)
                                    <td class="user-has-access" data-value="1">Yes</td>
                                @else
                                    <td class="user-has-access" data-value="0">No</td>
                                @endif
                                <td class="col-md-2">
                                    {{ $user->office_phone }}
                                    @if($user->office_extension)
                                         x. {{ $user->office_extension }}
                                    @endif
                                </td>

                                <td>
                                    {{ $user->cell_phone }}
                                </td>
                                <td>
                                    <span class="glyphicon glyphicon-pencil edit-user icon-btn"></span>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
            <div>
                <button class="btn btn-primary pull-right" id="new_user"><span class="glyphicon glyphicon-plus"></span> New User</button>
            </div>

            <br><br>
        @endif
    </div>

</div>
<div class="row">
    <div class="col-md-3">
        <h3>User Access</h3>
        <p>Use this section to control application access. Select the preferred access level and click 'Update'.</p>

        {{ Form::open(array('action' => 'UsersController@updateAccess')) }}
            <div class="form-group">
                <select name="access_level" class="form-control">
                    @if($access_level == 1)
                    <option selected="selected" value="1">Only Administrators</option>
                    @else
                    <option value="1">Only Administrators</option>
                    @endif

                    @if($access_level == 2)
                    <option selected="selected" value="2">Only Administrators and School Coordinators</option>
                    @else
                    <option value="2">Only Administrators and School Coordinators</option>
                    @endif

                    @if($access_level == 3)
                    <option selected="selected" value="3">Only Administrators, School Coordinators, and Program Coordinators</option>
                    @else
                    <option value="3">Only Administrators, School Coordinators, and Program Coordinators</option>
                    @endif

                    @if($access_level == 4)
                    <option selected="selected" value="4">All users</option>
                    @else
                    <option value="4">All Users</option>
                    @endif
                </select>
            </div>

            <button type="submit" class="btn btn-primary">Update</button>
        {{ Form::close() }}
    </div>
</div>

@stop

@section('included-js')
    @include('global._datatables_js')
@stop

@section('javascript')

    // ------------------------------------------------------------------------
    // Page Load
    // ------------------------------------------------------------------------


    // ------------------------------------------------------------------------
    // Events
    // ------------------------------------------------------------------------

    function triggerEditModal(element)
    {
        // Set static info in modal
        var user= element.closest('tr');
        $('#id').val(user.find('.user-name').data('user-id'));
        $('#name').text(user.find('.user-name').text());
        $('#email').text(user.find('.user-email').text());

        $('#has_access').val(user.find('.user-has-access').data('value'));



        // Select the selected user's current role
        var currentRole= user.find('.user-role').data('role-number');
        $('.role option[value="'+currentRole+'"]').prop('selected', true);

        selectSchoolandProgram(user, currentRole, $('#modal-edit-user'));

        //Open modal
        $('#modal-edit-user').modal();
    }



    // When user clicks on button to edit a user on the list
    $('.edit-user').on('click', function(e){
        triggerEditModal($(this));
    });

    // After user changes page (table is redrawn), bind modal trigger events
    $('table').on('draw.dt', function(e){

        // When user clicks on button to edit a user on the list
        $('.edit-user').on('click', function(e){
            triggerEditModal($(this));
        });
    });

    // When user clicks on button to create new user
    $('#new_user').on('click', function()
    {
        var modal = $('#modal-new-user');


        modal.find('.add-program').hide();

        // Remove all but first program
        modal.find('.program').not(':first').parent().remove();

        <!-- Select Admin role and "All" school and program -->
        $('#new_role option[value="1"]').prop('selected', true);
        $('#new_school option[value="0"]').prop('selected', true);
        modal.find('.program option[value="0"]').prop('selected', true);

        fetchPrograms(modal);

        <!-- Disable school and program -->
        $('#new_school').prop('disabled', true);
        modal.find('.program').prop('disabled', true);

        //Open modal
        modal.modal();
    });

    // Remove a program from the list
    $('.remove-program').on('click', function(e)
    {
        if($(this).parent().siblings().length > 0)
            $(this).parent().remove();
    });

    // On role change
    $('.role').on('change', function()
    {

        var modal = $(this).closest('.modal');
        switch($(this).find(':selected').val())
        {
            <!-- If admin, set both to All and disable selection on both-->
            case '1':

                modal.find('.school option[value="0"]').prop('selected', true);
                modal.find('.program option[value="0"]').prop('selected', true);
                modal.find('.school').prop('disabled', true);
                modal.find('.program').prop('disabled', true);

                // Remove all but first program
                modal.find('.program').not(':first').parent().remove();

                // Remove delete button and fix width of select
                modal.find('.program').removeClass('shortened-select');
                $('.remove-program').remove();

                //Hide button to add program
                modal.find('.add-program').hide();

                break;
            <!-- If scoord, set program to all and disable it -->
            case '2':
                <!-- Disable "All" option in schools and program -->
                modal.find('.school option[value="0"]').attr('disabled', true);

                if(modal.find('.school').find(':selected').val() == 0)
                {
                    modal.find('.school option:enabled:first').prop('selected', true);
                }

                modal.find('.program option[value="0"]').prop('selected', true);
                modal.find('.school').prop('disabled', false);
                modal.find('.program').prop('disabled', true);

                // Remove all but first program
                modal.find('.program').not(':first').parent().remove();

                // Remove delete button and fix width of select
                modal.find('.program').removeClass('shortened-select');
                $('.remove-program').remove();

                //Hide button to add program
                modal.find('.add-program').hide();

                break;
            <!-- If pcoord or professor, enable everything -->
            case '3':
            case '4':
                <!-- Disable "All" option in school -->
                modal.find('.school option[value="0"]').attr('disabled', true);

                <!-- Enable School and select an available  option for school-->
                modal.find('.school').prop('disabled', false);

                if(modal.find('.school').find(':selected').val() == 0)
                {
                    modal.find('.school option:enabled:first').prop('selected', true);
                }

                <!-- Enable program-->
                modal.find('.program').prop('disabled', false);

                // If it only has one child (most likely when changing from admin or scoord)
                if(modal.find('.programs').children().length == 1)
                {
                    <!-- Fetch programs for the available school -->
                    fetchPrograms(modal);

                    <!-- Disable "All" option in schools and program -->
                    modal.find('.program option[value="0"]').attr('disabled', true);

                    <!-- Select available option -->
                    modal.find('.program option:enabled:first').prop('selected', true);
                }
                else
                {
                    <!-- Disable "All" option in schools and program -->
                    modal.find('.program option[value="0"]').attr('disabled', true);
                }

                // Add delete button and fix width of select
                modal.find('.program').addClass('shortened-select');

                modal.find('.program').each(function() {

                    if($(this).siblings().length ==0)
                    {
                        $(this).parent().append(
                            ' <span class="remove-program glyphicon glyphicon-remove text-primary icon-btn"></span>'
                        );
                    }

                });

                $('.remove-program').on('click', function(e)
                {
                    if($(this).parent().siblings().length > 0)
                        $(this).parent().remove();
                });

                //Hide button to add program
                modal.find('.add-program').show();
                break;
            default:
                break;
        }
    });

    $('.school').on('change', function()
    {
        var modal = $(this).closest('.modal');
        switch(modal.find('.role').find(':selected').val())
        {
            case '3':
            case '4':
                // Remove all but first program
                modal.find('.program').not(':first').parent().remove();

                fetchPrograms(modal);

                modal.find('.program option[value="0"]').attr('disabled', true);
                modal.find('.program option:enabled:first').prop('selected', true);

                break;
        }
    });

    $('.add-program').on('click', function(e)
    {
        e.preventDefault();
        var modal = $(this).closest('.modal');

        var clone = modal.find('.program:last')
            .parent()
            .clone();

        // Change name
        clone
            .children('select')
            .attr('name', 'programs[]');

        // Append
        modal.find('.programs').append(clone);


        modal.find('.remove-program').on('click', function(e)
        {
            if($(this).parent().siblings().length > 0)
                $(this).parent().remove();
        });
    });

    // ------------------------------------------------------------------------
    // Functions
    // ------------------------------------------------------------------------

    function selectSchoolandProgram(user, role, modal)
    {
        modal.find('.add-program').hide();

        switch(role)
        {
            case 1:
                fetchPrograms(modal);

                <!-- Select "All" in school and program -->
                $('.school option[value="0"]').prop('selected', true);
                modal.find('.program option[value="0"]').prop('selected', true);

                <!-- Disable school and program -->
                $('.school').prop('disabled', true);
                modal.find('.program').prop('disabled', true);

                break;
            case 2:

                <!-- Find and select user's school -->
                var school_id = user.find('.user-school').data('school-id');
                $('.school option[value="'+school_id+'"]').prop('selected', true);

                <!-- Fetch programs -->
                fetchPrograms(modal);

                <!-- Disable "All" option in school and select the next one-->
                $('.school option[value="0"]').attr('disabled', true);

                <!-- Disable all options in program -->
                modal.find('.program').prop('disabled', true);

                <!--  -->

                break;
            case 3:
            case 4:
                <!-- Make sure school and program are not disabled -->
                $('.school').prop('disabled', false);
                modal.find('.program').prop('disabled', false);

                var school_id = user.find('.user-school').data('school-id');
                $('.school option[value="'+school_id+'"]').prop('selected', true);


                var program_ids = new Array();
                modal.find('.programs').empty();

                user.find('.user-program').children().each(function(index, value)
                {
                    $(this).parent().siblings().find('.remove-program').prop('disabled', true);

                    var program_id = $(this).data('program-id');
                    modal.find('.programs').append(
                        '<div class="form-group">'+
                            '<select class="program form-control shortened-select" name="programs[]"></select>'+
                            ' <span class="remove-program glyphicon glyphicon-remove text-primary icon-btn"></span>'+
                        '</div>'
                    );

                    $('.remove-program').on('click', function(e)
                    {
                        if($(this).parent().siblings().length > 0)
                            $(this).parent().remove();
                    });

                    fetchPrograms(modal);
                    program_ids.push(program_id);

                });

                for(var i =0; i < program_ids.length; i++)
                {
                    var program_id = program_ids[i];
                    modal.find('.program:eq('+i+') option[value="'+program_id+'"]').prop('selected', true);
                }

                modal.find('.add-program').show();

                <!-- Disable "All" option in school and program-->
                $('.school option[value="0"]').attr('disabled', true);
                modal.find('.program option[value="0"]').attr('disabled', true);

                break;
        }
    }

    // Fetch programs associated to a specific school
    function fetchPrograms(modal, index = 1)
    {
        //If school is set to All, do not search for programs
        if(modal.find('.school').find(':selected').val()!=0)
        {
            $.ajax({
                type: 'POST',
                url: "{{ URL::action('ProgramsController@fetch') }}",
                data: { id: modal.find('.school').find(':selected').val()},
                success: function(data)
                {
                    modal.find('.program').empty();
                    modal.find('.program').append('<option value="0">All</option>');

                    data.forEach( function (program)
                    {
                        modal.find('.program')
                        .append('<option value="'+program.id+'" >'+program.name+'</option>');
                    });
                },
                async:false
            });
        }
        else
        {
            modal.find('.program').empty();
            modal.find('.program').append('<option value="0">All</option>');
        }
    }

@stop