@extends('layouts.master')

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

<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(array('action' => 'Objective2Controller@create' )) }}
                <div id='outcomeGroup'>
                    <label> Associated Outcome</label>
                    <div class="form-group col-md-11" id='outcomeForm'>


                        {{ Form::select('outcome[0]', $outcomes, null, ['class'=>'form-control selectpicker', 'id' =>'outcome[0]']) }}

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


                <!-- 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', '', array('class' => 'form-control')) }}
                </div>



                {{ Form::submit('Create', array('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">

                {{ Form::open(array('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")']) }}

                </div>
                <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>

                        {{ Form::select('assoc_outcome[]', $outcomes, null, ['class'=>'form-control selectpicker', 'id'=>'assoc_outcome0']) }}

                    </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 -->
                <!-- 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="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'), array('class' => 'form-control', 'id'=>'objective-text')) }}
                </div>
                <div id="text">

                </div>

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

                </form>
            </div>




        </div>
    </div>
</div>
<script>
    var outcomeHTML = document.getElementById('outcomeGroup').innerHTML;
    var selectOptions = document.getElementById('outcome[0]').innerHTML;
    fetchAllObjectives("select-program", "assoc_outcomes_fetch")

    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 = 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) {

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


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


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

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


                // Select status
                if (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>' +
                        '<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() {

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

    }

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



        counterAssoc += 1;


    }
</script>
@stop

@section('javascript')

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

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

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

fetchObjectiveForEditing();
// setCriterionStatus();




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