@extends('layouts.master')

@section('navigation')
    @include('local.managers.sCoords._new_navigation')
@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 Outcome</label>
                        <div class="form-group col-md-11" id='outcomeForm'>
                            <select id="outcome[0]" name="outcome[0]" class="form-control selectpicker">
                                @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 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>



                    {{ Form::submit('Create', ['class' => 'btn btn-primary btn-block']) }}
                    {{ 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 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 Outcome</label>
                            <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 Outcome
                    </button>


                    <!-- Associated Program -->
                    <div class="form-group">

                        {{ Form::label('program_id2', '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>

                    {{ Form::submit('Update', ['class' => 'btn btn-primary btn-block', 'id' => 'update_button']) }}
                    {{ Form::close() }}
                    <form action="/deleteObjective" method="POST" id='deleteObj'>


                    </form>
                </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;


        function fetchAllObjectives(program, outcome) {
            var program_id_fetch = $('#' + program).val();
            var outcome_fetch = $('#' + outcome).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 ran = false;

        var counter = 1;
        var counterAssoc = 1;
        //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",
                'name': "outcome[" + counter.toString() + "]",
                'data-live-search': 'true'

            });
            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',
                'onclick': 'deleteLast()'
            });
            $button.append('X');
            $divForButton.append($button);

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

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

        }

        function deleteLast() {

            div = document.getElementById('outcomeForm' + (counter - 1).toString());
            div.remove();
            button = document.getElementById('close' + (counter - 1).toString());
            button.remove();
            counter -= 1;
            $('#counter').val(counter);
        }

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

            $.post(
                "{{ URL::action('Objective2Controller@fetchObjectiveWithTrashed') }}", {
                    id: id
                },
                function(json) {
// console.log(json.objective.length);
					if((json.objective.length))
                    {
                    	var text = json.objective[0].text;


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

                    // Select associated outcome
                    for (var i = counterAssoc; i != 1; i--) {
                        deleteLastAssoc(i);

                    }
					if((json.objective.length))
                    {
	                    $('#assoc_outcome0').val(json.outcome[0].outcome_id);
    				}
                    $('#assoc_outcome0').selectpicker('refresh');
                    counterAssoc = 1;
                    for (var i = 1; i < json.outcome.length; i++) {
                        counterAssoc = i + 1;
                        var $select = $('<select />', {
                            'class': "selectpicker form-control ",
                            'name': "assoc_outcome[]",
                            'data-live-search': 'true',
                            'id': 'assoc_outcome' + i.toString()

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

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

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

                        $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');


                    }


                    // Select associated program
                    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);
                    }

		// 			if((json.objective.length))
//                     {

                    // Select status
                    if (json.objective.length && json.objective[0].deleted_at)
                        $('#status').val(0);
                    else
                        $('#status').val(1);
                    if (json.assessment.length) {
                        $('#deleteObj').html(
                            "<p>This objective is currently participating in an assessment, therefore it cannot be deleted</p>"
                            );
                    } else if (json.assoc_criteria.length) {
                        modal =
                            '<button type="button" class="btn btn-primary btn-block" data-toggle="modal" data-target="#delete">' +
                            'Delete' +
                            '</button>';
                    if(json.objective.lenght)
                            modal +='<input type="hidden" value =' + json.objective[0].id + ' name="deleteObj">';

                            modal +='<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>';
                        if(json.objective.length)
                         modal += '<input type="hidden" value =' + json.objective[0].id + ' name="deleteObj">' ;

                        modal += '<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() {

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

        }

        function addAssoc() {


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


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

            });
            var $button = $('<button />', {
                'type': 'button',
                'class': 'btn btn-primary',
                'onclick': 'deleteLastAssoc()'
            });
            $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').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())
            });
            $.post(
                "{{ URL::action('Objective2Controller@update') }}", {
                    assoc_outcome: outcome_id,
                    program_id: program_id,
                    status: status,
                    text: text,
                    id: id
                },
                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
