@extends('layouts.master')

@section('navigation')
    @if (Auth::user()->role == 1)
        @include('local.managers.admins._new_navigation')
    @elseif(Auth::user()->role == 2)
        @include('local.managers.sCoords._new_navigation')
    @elseif(Auth::user()->role == 3)
        @include('local.managers.pCoords._new_navigation')
    @endif
@stop
@section('main')
    <div class="row">
        <div class="col-md-12" id='message'>

        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <!-- Form to add a new objective -->
            <div class="panel panel-default panel-button">
                <div class="panel-heading">
                    Create
                </div>
                <div class="panel-body">
                    {{ Form::open(['action' => 'Objective2Controller@create']) }}
                    <div id='outcomeGroup'>
                        <label> Associated Learning Outcome</label>
                        <div class="form-group col-md-11" id='outcomeForm'>


                            <select id="outcome[0]" name="outcome[0]" class="form-control selectpicker createOutcome">

                                @foreach ($outcomes as $outcome)
                                    <option value="{{ $outcome->id }}">

                                        {{ $outcome->name }}







                                    </option>
                                @endforeach

                            </select>


                        </div>

                    </div>
                    <input type='hidden' name='counter' id='counter' value=1>
                    <button id='button-add-outcome' class='btn btn-md btn-secondary' onclick='addOutcomeTest()'>
                        <span class='glyphicon glyphicon-plus'>

                        </span>
                        Add another Learning Outcome
                    </button>

                    <!-- Associated Program -->


                    <div class="form-group">
                        {{ Form::label('program_id', 'Associated Program') }}<br>
                        <br>


                        @foreach ($programs as $program)
                            <input type="checkbox" id="{{ $program->name }}" name="program_id[]"
                                value="{{ $program->id }}">
                            <label for="{{ $program->name }}"> {{ $program->name }}
                                [{{ $program->school->name }}]</label><br>
                        @endforeach

                    </div>

                    <div class="form-group">
                        {{ Form::label('text', 'Text') }}
                        {{ Form::text('text', '', ['class' => 'form-control']) }}
                    </div>

                    <div class = "form-group">
                      
                        <input type="checkbox" id="agreement" name="agreement"
                                value="1">
                                  {{Form::label('agreement', 'I would like to pair criteria without objectives to this one.')}}

                        
                 

                    </div>



                    {{ Form::submit('Create', ['class' => 'btn btn-primary btn-block', 'id' => 'createObjectiveButton']) }}
                    {{ Form::close() }}
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="panel panel-default panel-button">
                <div class="panel-heading">
                    Edit
                </div>


                <div class="panel-body">
                    <button class="btn btn-md btn-secondary filterButton">
                        <span class="glyphicon glyphicon-minus">
                        </span>
                        Filters
                    </button>
                    <div class='filterSection'>

                        {{ Form::open(['action' => 'Objective2Controller@update']) }}

                        <div class="form-group">
                            {{ Form::label('program_id2', 'Associated Program') }}
                            <select id='select-program' class="form-control selectpicker"
                                onchange='fetchAllObjectives("select-program", "assoc_outcomes_fetch")'>
                                @foreach ($programs as $program)
                                    <option value='{{ $program->id }}' data-subtext="{{ $program->code }}">
                                        {{ $program->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Associated Learning Outcome</label>
                            {{-- Form::select('assoc_outcome_fetch', $outcomes, null, ['class'=>'form-control selectpicker', 'id'=>'assoc_outcomes_fetch', 'onchange'=>'fetchAllObjectives("select-program", "assoc_outcomes_fetch")']) --}}
                            <select id="assoc_outcomes_fetch" name="assoc_outcome_fetch" class="form-control selectpicker"
                                onchange="fetchAllObjectives('select-program', 'assoc_outcomes_fetch')">
                                @foreach ($outcomes as $outcome)
                                    <option value="{{ $outcome->id }}">
                                        {{ $outcome->name }}



                                    </option>
                                @endforeach
                            </select>

                        </div>
                    </div>
                    <hr>

                    <div class="form-group">
                        {{ Form::label('objective_id', 'Objectives') }}
                        <select id="select-objective" name='id' class="form-control selectpicker">
                            @foreach ($objectives as $objective)
                                <option value="{{ $objective->id }}"
                                    data-subtext="
                                                                                                                                                                                                                                             @if ($objective->program) &nbsp;&nbsp;&nbsp;[{{ $objective->program->name }}] @endif
                                                                                                                                                                                                                            ">
                                    {{ $objective->text }}



                                </option>
                            @endforeach
                        </select>


                    </div>

                    <!-- Associated Outcome -->

                    <div class="form-group">
                        <div id='assocOutcomeGroup'>
                            <label>Associated Learning Outcome</label>

                            <div id="message_to_disconnect"></div>

                            <select id="assoc_outcome0" name="assoc_outcome[]" class="form-control selectpicker">

                                @foreach ($outcomes as $outcome)
                                    <option value="{{ $outcome->id }}">

                                        {{ $outcome->name }}







                                    </option>
                                @endforeach

                            </select>

                            <br><br>
                        </div>

                    </div>

                    <button id='button-add-assoc-outcome' class='btn btn-md btn-secondary' onclick='addAssoc()'>
                        <span class='glyphicon glyphicon-plus'>

                        </span>
                        Add another Learning Outcome
                    </button>


                    <!-- Associated Program -->
                    <div class="form-group">
                        {{ Form::label('program_id', 'Associated Program') }}<br>
                        <br>


                        @foreach ($programs as $program)
                            <input type="checkbox" id="assoc_program_id_{{ $program->id }}" name="assoc_program_id[]"
                                value="{{ $program->id }}">
                            <label for="assoc_program_id_{{ $program->id }}"> {{ $program->name }}
                                <sub>[{{ $program->school->name }}]</sub></label><br>
                        @endforeach
                    </div>

                    <!-- Status -->
                    <div class="form-group">
                        {{ Form::label('status', 'Status') }}
                        <span data-toggle="tooltip" data-placement="top"
                            title="Use this option to deactivate or reactivate objectives. Inactive objective will stay in the system, but will not be available to use in new rubrics."
                            class="glyphicon glyphicon-question-sign"></span>

                        <select id="status" name="status" class="form-control">
                            <option value="1">Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </div>

                    <div class="form-group">
                        {{ Form::label('text', 'Text') }}
                        {{ Form::text('text', Input::old('text'), ['class' => 'form-control', 'id' => 'objective-text']) }}
                    </div>
                    <div id="text">

                    </div>

                    <div class = "form-group">
                      
                        <input type="checkbox" id="agreement_assoc" name="agreement"
                                value="1">
                                  {{Form::label('agreement_assoc', 'I would like to pair criteria without objectives to this one.')}}

                        
                 

                    </div>

                    {{ Form::submit('Update', ['class' => 'btn btn-primary btn-block', 'id' => 'update_button_to_modal']) }}
                    {{ Form::close() }}

                    <form action="/deleteObjective" method="POST" id='deleteObj'>


                    </form>
                </div>





            </div>
        </div>
    </div>
    <div id="ObjectiveAssocModal" class="modal fade" tabindex="-1" data-criterion-id="0">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h5 class="modal-title">Would you like to pair these new Learning Outcomes to all the Criteria
                        associated to
                        this Objective?</h5>

                </div>
                <div class="modal-body" id="ObjectiveModalBody">

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary"
                        onclick="pair_every_criteria_with_objective =0; $('#update_button').click()"
                        data-dismiss="modal">No</button>
                    <button type="button" onclick="pair_every_criteria_with_objective =1; $('#update_button').click()"
                        class="btn btn-primary" data-dismiss="modal">Yes</button>
                    <button type="hidden" style="display:none" id="update_button" class="btn btn-primary"></button>
                </div>
            </div>
        </div>
    </div>
    <script>
        $('.filterSection').show();

        $('.filterButton').on('click', function() {
            var span = $(this).find('span');
            if (span.attr('class') == 'glyphicon glyphicon-plus') {
                span.attr('class', 'glyphicon glyphicon-minus');
            } else {
                span.attr('class', 'glyphicon glyphicon-plus');

            }

            $('.filterSection').toggle(533);

        });
        var outcomeHTML = document.getElementById('outcomeGroup').innerHTML;
        var selectOptions = document.getElementById('outcome[0]').innerHTML;
        var ran = false;

        function fetchAllObjectives(program, outcome) {
            var program_id_fetch = $('#' + program).find(':selected').val();
            var outcome_fetch = $('#' + outcome).find(':selected').val();
            $.post(
                "{{ URL::action('Objective2Controller@fetchAllObjectives') }}", {
                    program_fetch: program_id_fetch,
                    outcome_fetch: outcome_fetch
                },
                function(json) {
                    json_length = (json.objective.length);
                    fullHTML = '';
                    for (var i = 0; i < json_length; i++) {
                        fullHTML += '<option value="' + json.objective[i].id + '">' + json.objective[i].text +
                            '</option>';
                    }
                    $('#select-objective').html(fullHTML);
                    $('#select-objective').selectpicker('refresh');

                    fetchObjectiveForEditing();

                },
                'json'
            );
        }



        var counter = 1;
        var counterAssoc = 0;
        //Add Another Outcome

        function changeOutcomeHtml() {
            var outcomeHTML = document.getElementById('outcomeGroup').innerHTML;

            outcomeHTML = outcomeHTML.replace('outcome[' + counter.toString() + ']', 'outcome[' + (counter + 1).toString() +
                ']');
            counter += 1;
            document.getElementById("outcomeGroup").innerHTML += outcomeHTML;




            document.getElementById('button-add-outcome').onclick = addOutcome;
        }

        function addOutcome() {
            outcomeHTML = outcomeHTML.replace('outcome[' + counter.toString() + ']', 'outcome[' + (counter + 1).toString() +
                ']');
            counter += 1;

            document.getElementById("outcomeGroup").innerHTML += outcomeHTML;
        }

        function addOutcomeTest() {
            var $select = $('<select/>', {
                'class': "selectpicker form-control createOutcome",
                'name': "outcome[" + counter.toString() + "]",
                'data-live-search': 'true'

            });

            //holds both the select div and the button div
            var $containerdiv = $('<div/>', {
                'id': 'outcomeContainer' + counter.toString(),
            });


            var $div = $('<div/>', {
                'id': 'outcomeForm' + counter.toString(),
                'class': 'form-group col-md-11'
            });
            var $divForButton = $('<div/>', {
                'class': 'col-md-1',
                'id': 'close' + counter.toString()

            });

            var $button = $('<button/>', {
                'type': 'button',
                'class': 'btn btn-primary',
                //send the counter to the function so it can tell which container to remove
                'onclick': 'deleteLast(' + counter + ')',

            });
            $button.append('X');
            $divForButton.append($button);

            $containerdiv.appendTo('#outcomeGroup')
            $div.appendTo('#outcomeContainer' + counter.toString())
            $select.append(selectOptions);

            $select.appendTo('#outcomeForm' + counter.toString()).selectpicker('refresh');
            $divForButton.appendTo('#outcomeContainer' + counter.toString());
            counter += 1;
            $('#counter').val(counter);

        }

        //Recieves the counter variable so it can find the specific div and delete it
        function deleteLast(counter) {
            div = document.getElementById('outcomeContainer' + (counter).toString());
            div.remove();
        }

        function fetchObjectiveForEditing() {
            var id = $('#select-objective').find(':selected').val();

            $.post(
                "{{ URL::action('Objective2Controller@fetchObjectiveWithTrashed') }}", {
                    id: id
                },
                function(json) {

                    var text = json.objective[0].text;


                    // Display info
                    $('#objective-text').val(text);


                    // Select associated outcome
                    $(".removable-outcome").remove();
                    $('.warning-objective').remove();
                    $("#assoc_outcome0").attr('data-old-outcome-id',json.outcome[0].outcome_id);
                    $('#assoc_outcome0').val(json.outcome[0].outcome_id);

                    disabled = 0;

                    //se va a disable cuando pertenece a un plan. 
                    if (json.outcome[0].typ_semester_outcome_id != null){ //|| json.outcome[0].count_criterion_id != 0) {
                        $('#assoc_outcome0').attr('disabled', true);
                        disabled = 1;
                    } else $('#assoc_outcome0').attr('disabled', false);
                    counterAssoc = 0;
                    $('#assoc_outcome0').selectpicker('refresh');
                    for (var i = 1; i < json.outcome.length; i++) {
                        counterAssoc = i;
                        var $select = $('<select />', {
                            'class': "selectpicker form-control ",
                            'name': "assoc_outcome[]",
                            'data-live-search': 'true',
                            'id': 'assoc_outcome' + i.toString(),
                            'data-old-outcome-id': json.outcome[i].outcome_id


                        });
                        var $div = $('<div />', {
                            'id': 'assocOutcomeForm' + i.toString(),
                            'class': 'form-group col-md-11 removable-outcome'
                        });
                        var $divForButton = $('<div />', {
                            'class': 'col-md-1 removable-outcome',
                            'id': 'closeAssoc' + i.toString()

                        });
                        var $button = $('<button />', {
                            'type': 'button',
                            'class': 'btn btn-primary removable-outcome',
                            'onclick': 'deleteLastAssoc(' + i + ')'
                        });
                        $button.append('X');
                        $divForButton.append($button);

                        $div.appendTo('#assocOutcomeGroup')
                        $select.append(selectOptions);
                        if (json.outcome[i].typ_semester_outcome_id != null //|| json.outcome[i].count_criterion_id != 0
                            ) {
                            $select.attr('disabled', true);
                            $button.attr('disabled', true);
                            disabled = 1;
                        }
                        $select.appendTo('#assocOutcomeForm' + i.toString()).selectpicker('refresh');
                        $divForButton.appendTo('#assocOutcomeGroup');


                        $('#assoc_outcome' + i.toString()).val(json.outcome[i].outcome_id);
                        $('#assoc_outcome' + i.toString()).selectpicker('refresh');




                    }


                    if (disabled == 1) {
                        alert = $('<div/>', {
                            'class': 'alert alert-danger alert-dismissible warning-objective',
                            'role': 'alert'
                        })
                        button = $('<button/>', {
                            'type': 'button',
                            'class': 'close',
                            'data-dismiss': 'alert',
                            'alert-label': 'close'
                        }).html('<span aria-hidden="true">×</span>');
                        alert.append(button);
                        alert.append(
                            '<strong>If you wish to edit the disabled Learning Outcomes, you need to detach this Objective from the desired Learning Outcome in every Three Year Plan.</strong>'
                        )

                        alert.appendTo($('#message_to_disconnect'))
                    }



                    var program_length = json.program.length;
                    $('input[type=checkbox]').prop('checked', false);

                    for (var i = 0; i < program_length; i++) {
                        prog = json.program[i].program_id.toString();
                        $('#assoc_program_id_' + prog).prop("checked", true);
                    }


                    // Select status
                    if (json.objective[0].deleted_at)
                        $('#status').val(0);
                    else
                        $('#status').val(1);
                    typ_status = "";

                    warning = "";

                    if (json.typ_semester_objectives.length > 0 && json.assessment.length > 0) {
                        warning =
                            "<p>This objective is currently participating in an Assessment and it is paired to a Three Year Plan, therefore it cannot be deleted </p>";
                        $("#deleteObj").html(warning);
                    } else if (json.assessment.length > 0) {
                        $('#deleteObj').html(
                            "<p>This objective is currently participating in an Assessment, therefore it cannot be deleted</p>"
                        );
                    } else if (json.typ_semester_objectives.length > 0) {
                        warning =
                            "<p>This objective is currently paired to a Three Year Plan, therefore it cannot be deleted </p>";
                        $("#deleteObj").html(
                            warning
                        );
                    } else if (json.assoc_criteria.length > 0) {
                        modal =
                            '<button type="button" class="btn btn-primary btn-block" data-toggle="modal" data-target="#delete">' +
                            'Delete' +
                            '</button>' +
                            '<input type="hidden" value =' + json.objective[0].id + ' name="deleteObj">' +

                            '<div class="modal fade" id="delete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">' +
                            '<div class="modal-dialog" role="document">' +
                            '<div class="modal-content">' +
                            ' <div class="modal-header">' +
                            '<h5 class="modal-title" id="exampleModalLabel">Are you sure?</h5>' +
                            '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
                            '<span aria-hidden="true">&times;</span>' +
                            '</button>' +
                            ' </div>' +
                            '<div class="modal-body">' +
                            "<p>This objective is associated to: <p>" +
                            '<ul>';
                        for (var i = 0; i < json.assoc_criteria.length; i++) {
                            modal += "<li>" + json.assoc_criteria[i].name + '</li>';
                        }
                        modal += ' </ul>' +
                            '<p>Do you still want to delete it?</p>' +
                            '</div>' +
                            '<div class="modal-footer">' +
                            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>' +
                            '<button type="submit" class="btn btn-primary">Delete</button>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        $('#deleteObj').html(modal);


                    } else {
                        modal =
                            '<button type="button" class="btn btn-primary btn-block" data-toggle="modal" data-target="#delete">' +
                            'Delete' +
                            '</button>' +
                            '<input type="hidden" value =' + json.objective[0].id + ' name="deleteObj">' +

                            '<div class="modal fade" id="delete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">' +
                            '<div class="modal-dialog" role="document">' +
                            '<div class="modal-content">' +
                            ' <div class="modal-header">' +
                            '<h5 class="modal-title" id="exampleModalLabel">Are you sure?</h5>' +
                            '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
                            '<span aria-hidden="true">&times;</span>' +
                            '</button>' +
                            ' </div>' +
                            '<div class="modal-body">' +
                            "<p> Once deleted, there is no chance of getting it back.</p>";

                        modal +=
                            '<p>Do you still want to delete it?</p>' +
                            '</div>' +
                            '<div class="modal-footer">' +
                            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>' +
                            '<button type="submit" class="btn btn-primary">Delete</button>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        $('#deleteObj').html(modal);
                    }
                },
                'json'
            );
        }


        function deleteLastAssoc(i) {

            div = document.getElementById('assocOutcomeForm' + (i).toString());
            div.remove();
            button = document.getElementById('closeAssoc' + (i).toString());
            button.remove();
            //counterAssoc -= 1;
            //$('#counterAssoc').val(counterAssoc);

        }

        function addAssoc() {

            counterAssoc += 1;
            var $select = $('<select />', {
                'class': "selectpicker form-control ",
                'name': "assoc_outcome[]",
                'data-live-search': 'true',
                'id': 'assoc_outcome' + counterAssoc.toString(),
                'data-new-outcome': 'true'

            });
            var $div = $('<div />', {
                'id': 'assocOutcomeForm' + counterAssoc.toString(),
                'class': 'form-group col-md-11 removable-outcome'
            });
            var $divForButton = $('<div />', {
                'class': 'col-md-1 removable-outcome',
                'id': 'closeAssoc' + counterAssoc.toString()

            });
            var $button = $('<button />', {
                'type': 'button',
                'class': 'btn btn-primary',
                'onclick': 'deleteLastAssoc(' + counterAssoc + ')'
            });
            $button.append('X');
            $divForButton.append($button);

            $div.appendTo('#assocOutcomeGroup')
            $select.append(selectOptions);

            $select.appendTo('#assocOutcomeForm' + counterAssoc.toString()).selectpicker('refresh');
            $divForButton.appendTo('#assocOutcomeGroup');


            ran = true;
            //counterAssoc += 1;
            $('#counterAssoc').val(counterAssoc);



        }

        $("#update_button_to_modal").on('click', function(e) {
            e.preventDefault();
            newOutcomes = [];
            $('#assocOutcomeGroup').find('select').each(function() {
                if ($(this).data('new-outcome') == true || $(this).data('old-outcome-id') != $(this).val()) {
                    option = $(this).find(':selected');
                    newOutcomes.push(option[0].text);
                }
            })

            if (newOutcomes.length > 0) {
                ul = $("<ul>");

                $.each(newOutcomes, function(id, text) {
                    li = $("<li>").html(text)
                    ul.append(li);
                });

                $("#ObjectiveModalBody").html(ul);
                $('#ObjectiveAssocModal').modal("toggle");
            } else {
                pair_every_criteria_with_objective = 0;
                $("#update_button").click();

            }


        })
        //Terrible notation but


        pair_every_criteria_with_objective = 0;
        $('#update_button').on('click', function(e) {
            e.preventDefault();

            outcome_id = []
            program_id = [];

            status = $('#status').val();
            text = $('#objective-text').val();
            id = $('#select-objective').val();

            $('#assocOutcomeGroup').find('select').each(function() {
                outcome_id.push($(this).val())
            })
            $('input[name="assoc_program_id[]"]').each(function() {
                if (this.checked)
                    program_id.push($(this).val())
            });

            agreement = null;
            if($('#agreement_assoc').is(':checked')){
                agreement = 1;
            }
          
           


            $.post(
                "{{ URL::action('Objective2Controller@update') }}", {
                    assoc_outcome: outcome_id,
                    program_id: program_id,
                    status: status,
                    text: text,
                    id: id,
                    pair_every_criteria_with_objective: pair_every_criteria_with_objective,
                    agreement:agreement
                },
                function($array) {
                    div = $('<div/>', {
                        'class': 'alert alert-dismissible alert-' + $array.status,
                        'role': 'alert'
                    })
                    button = $('<button/>', {
                        'class': 'close',
                        'type': 'button',
                        'data-dismiss': 'alert',
                        'aria-label': 'Close'

                    }).html('<span aria-hidden="true">&times;</span>');
                    div.append(button);
                    if ($array.status == 'danger') {
                        span = $('<span/>', {
                            'class': 'glyphicon glyphicon-remove-sign'
                        });
                    } else {
                        span = $('<span/>', {
                            'class': 'glyphicon glyphicon-ok-sign'
                        });
                    }
                    div.append(span);
                    div.append($array.message);
                    div.appendTo('#message');
                }
            )
        })
    </script>
@stop

@section('javascript')

    // --------------------------------------------------------------------------
    // Page load
    // --------------------------------------------------------------------------

    // Hide accordion panel contents by default
    $('.panel-group .panel-body').hide();

    $('#outcome-display').parent().hide();

    // fetchObjectiveForEditing();
    // setCriterionStatus();



    fetchAllObjectives("select-program", "assoc_outcomes_fetch")


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

    // Fetch criterion info for editing

    $('#button-add-outcome').on('click', function(e) {
    // Prevent the default action of the clicked item. In this case that is submit
    e.preventDefault();


    return false;
    });
    $('#button-add-assoc-outcome').on('click', function(e) {
    // Prevent the default action of the clicked item. In this case that is submit
    e.preventDefault();


    return false;
    });

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

    // When panel heading is clicked, toggle it
    $('.panel-group .panel-heading').on('click', function()
    {
    $(this).next().stop().slideToggle();
    })


    // When list item is clicked, load corresponding info
    $('#select-objective').on('change', function()
    {

    fetchObjectiveForEditing();
    $('.selectpicker').selectpicker('refresh');
    });

    // When list item is clicked, load corresponding info
    $('.selectpicker').on('change', function()
    {
    //alert($(this).find(':selected').val());
    $('.selectpicker').selectpicker('refresh');
    });

@stop