@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')
    @elseif(Auth::user()->role == 4)
        @include('local.professors._navigation')
    @endif
@stop

@section('main')
    {{-- TODO: look where to place this script.
          if placed inside .ready() or before it,
            an error that the function is not defined occurs. --}}
    {{-- TODO: no reconoce acentos --}}
    <script type="text/javascript">
        function filterObjectives() {
            // Declare variables
            var input, filter, div, li, i, objectiveText;
            input = document.getElementById('userInput');
            filter = input.value.toUpperCase();
            div = document.getElementById("list");
            li = div.getElementsByTagName('li');

            // Loop through all list items, and hide those who don't match the search query
            for (i = 0; i < li.length; i++) {
                objectiveText = li[i].textContent;
                if (objectiveText.toUpperCase().indexOf(filter) > -1) {
                    li[i].style.display = "";
                } else {
                    li[i].style.display = "none";
                }
            }
        }
    </script>

    <div class="row">
        <div class="col-md-3">
            <input class="form-control" type="text" id="userInput" onkeyup="filterObjectives()"
                placeholder="Search for Learning Outcomes..">
            <div class="list-group" id='list'>
                @foreach ($outcomes as $outcome)
                    <li data-outcome-id="{{ $outcome->id }}" class="list-group-item">{{ $outcome->name }}</li>
                @endforeach
            </div>
        </div>

        <div class="col-md-9">
            <div id="objective-display" class="panel panel-default">
                <div class="panel-heading">
                    <h4 class=" panel-title" style="cursor:auto!important;">
                    </h4>
                </div>
                <div class="panel-body">
                    <p class="objective-definition "></p>

                    <div class="table-responsive table-responsive-0">
                        <table class="table table-striped table-condensed datatable">
                            <thead id="theHead">
                                <th>Objective</th>
                                <th>Program</th>
                                <th>Match to Criteria</th>
                            </thead>
                            <tfoot>

                            </tfoot>
                            <tbody id="table_objectives">
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>

        <div class="col-md-9">
            <div class="no-objective alert alert-info">
                <p>Select a Learning Objective to view its information</p>
            </div>
        </div>

    </div>

    

    <div id="match_criteria" class="modal fade" tabindex="-1" data-objective-id="0">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id = 'match_criteria_title'></h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body" id = "match_criteria_body">
                    <p>The following criteria appear based on objective's programs and your available programs</p>

                    <div class ='form-group col-md-12'>
                        <label for="match_criteria_program">Program</label>
                        <select id="match_criteria_program" class ='form-control selectpicker select_program' onchange="changeCriteriaDisplayed('#match_criteria_program')">
                            
                        </select>
                    </div>
                    <hr>
                    <label>Criteria associated to program</label>
                    <div id="program_objectives" class ='form-group col-md-12' >

                    </div>

                




                </div>
                <div class="modal-footer">
                    <hr>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="">Close</button>

                </div>
            </div>
        </div>
    </div>

    
    <div id="warning" class="modal fade" tabindex="-1" data-objective-id="0">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id = 'warning_title'></h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body" id = "warning_body">
                    

                




                </div>
                <div class="modal-footer">
                    <hr>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="$('#match_criteria').data('objective-id', '0');">Cancel</button>
                    <button  id='warning_delete' type="button" class="btn btn-primary" onclick = ''>Delete</button>
                </div>
            </div>
        </div>
    </div>


    
    <script>
        $(document).ready(function() {
            // --------------------------------------------------------------------------
            // Page load
            // --------------------------------------------------------------------------

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

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

            // --------------------------------------------------------------------------
            // Functions
            // --------------------------------------------------------------------------
            /*

              */

            
            function fetchObjectives(li) {
                {

                    var id = $(li).data('outcome-id');

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

                            // Retrieve datatable instance
                            //var table = $('.table-responsive-0').;

                            var name = $(li).html();
                            //var definition = json.objective.program.name;
                            //var criteria = json.objective.criteria;

                            $('#objective-display').parent().show();
                            $('.no-objective').parent().hide();

                            //Display title and definition
                            $('#objective-display .panel-title').html(name);
                            // $('#objective-display .objective-definition').html(definition);

                            //Empty table
                            $('#table_objectives').empty();

                            $.each(json, function(ind2, objective) {
                                tr = $("<tr>");

                                //objectives
                                td_text = $("<td>",{
                                    'id':"objective-"+objective.id
                                }).html(objective.text);
                                 //programs
                                td_programs = $("<td>");
                                ol = $("<ol>");

                                $.each(objective.programs, function(ind, prog) {
                                    li = $("<li>").html(prog.name);
                                    li.appendTo(ol);
                                })
                                ol.appendTo(td_programs);

                                //link to criteria matching
                                link_td = $("<td>");
                                
                                a = $('<a>',{
                                    'onclick':'fetchCriteria(this)',
                                    'data-objective-id': objective.id,
                                    'data-outcome-id':id

                                    
                                }).html("Change Associated Criteria");

                                link_td.append(a)

                                
                                tr.append(td_text);
                                tr.append(td_programs);
                                tr.append(link_td)
                                tr.appendTo($('#table_objectives'))


                                

                            })
                        },
                        'json'
                    );

                }
            }
            // --------------------------------------------------------------------------
            // Events
            // --------------------------------------------------------------------------

            // When list item is clicked, load corresponding info
            $('.list-group-item').on('click', function() {
                fetchObjectives(this);
            })
        });

        function postDeleteCrit(criterion_id ,program_id ,outcome_id ,objective_id ,cobo_id ,pcobo_id){
            
            $.post(
                "{{URL::action('Objective2Controller@deletePCOBO')}}",
                {
                    criterion_id:criterion_id,
                    program_id:program_id,
                    outcome_id:outcome_id,
                    objective_id:objective_id,
                    cobo_id:cobo_id,
                    pcobo_id:pcobo_id
                },
                function (status){

                    if(status == 200){
                    $('.selected_criteria_to_delete').parent().parent().remove();
                    }
                    else{
                        alert("something went wrong, try again later.");
                    }
                    
                }
            )
        }


        function createSelectForModal(options){
            
            div_master = $('<div>',{
                'class':'removable_div'
            })
            div_select = $("<div>",{
                'class':'form-group col-md-11',

            })
            select = $('<select>',{
                'class':'selectpicker form-control criteria_select',
                'name':'criteria[]',
                'onchange':'saveChanges(this)'

            }).html(options);
            div_rem_button = $('<div>',
                {
                    'class':'col-md-1 remove-btn'
                    
                })
            rem_button = $('<button>',{
                'type':'button',
                'class':'btn btn-primary',
                'onclick':'deleteCriterion(this);'
            }).html("<span class='glyphicon glyphicon-remove'></span>")

            div_select.append(select);
            div_rem_button.append(rem_button);
            div_master.append(div_select);
            div_master.append(div_rem_button);

            return div_master;

        }

        function saveChanges(select){
            
            //Create if old-cobo doesnt exist

            option = $(select).find(':selected');
            
            criterion_id = option.val()
            if(criterion_id ==0){
                return;
            }
            pcobo_id = option.data('pcobo-id')
            cobo_id = option.data('cobo-id');
            objective_id = option.data('objective-id')
            outcome_id =  option.data('outcome-id');
            program_id = option.data('program-id')

            dict_to_send = {};
   
            if($(select).data('old-pcobo') ===undefined){
               dict_to_send=    {
                        criterion_id:criterion_id,
                        pcobo_id:pcobo_id,
                        cobo_id:cobo_id,
                        objective_id:objective_id,
                        outcome_id:outcome_id,
                        program_id:program_id
                    } 
                url = "{{URL::action('Objective2Controller@insertPCOBO')}}";

                   
            }
            else{

                url= "{{URL::action('Objective2Controller@updatePCOBO')}}";


                old_crit = $(select).data('old-criterion')
                old_outcome= $(select).data('old-outcome')
                old_cobo = $(select).data('old-cobo')
                old_pcobo = $(select).data('old-pcobo')
                dict_to_send ={
                        criterion_id:criterion_id,
                        pcobo_id:pcobo_id,
                        cobo_id:cobo_id,
                        objective_id:objective_id,
                        outcome_id:outcome_id,
                        program_id:program_id,
                        old_crit:old_crit,
                        old_outcome:old_outcome,
                        old_cobo:old_cobo,
                        old_pcobo:old_pcobo

                        
                    } 

                    
                

            }

            $.post(
                    url,
                    dict_to_send,
                    function(code){
                        if(code == "DUPLICATE"){
                            alert("This criteria is already paired to this objective")
                            $(select).val(0)
                            $(select).selectpicker('refresh');
                        }
                        else if (code==200){
                          
                            
                            $(select).attr('data-old-pcobo', pcobo_id)
                            $(select).attr('data-old-cobo', cobo_id)
                            $(select).attr('data-old-criterion', criterion_id)
                            $(select).attr('data-old-outcome', outcome_id)
                            $(select).attr('data-old-objective', objective_id)


                        }
                    }
                )
                
            
          


        }

    

        function fetchCriteria(a){
            objective_id = $(a).data('objective-id');
            objective_text = $("#objective-"+objective_id).html()
            outcome_id = $(a).data('outcome-id')

            $.post(
                "{{URL::action('Objective2Controller@fetchProgramCriteria')}}",
                {
                    objective_id:objective_id,
                    outcome_id:outcome_id
                },
                function(programs){
                    //modal, and its subvariants
                    mc = "#match_criteria";

                    $(mc).data('objective-id', objective_id)

                    title_h = $('<h5>',{
                        'class':'modal-title'
                    }).html("Match "+ objective_text +" to Criteria")
                    $(mc+"_title").html(title_h)

                    $('.removable_div').remove();

                    //select= $(".select_criteria").html(" ");
                    program_select = $("#match_criteria_program").html(" ");
                    
                    $.each(programs, function(ind, program){

                        prog_div = $("<div>",{
                            "id":"program-"+program.id,
                            "class": "program_divs removable_div",
                            "style":"display: none"
                        })
                        program_option = $('<option>',{
                            "value":program.id
                        }).html(program.name)

                        program_select.append(program_option);
                        

                        criteria = program.criteria
                        options_html = '<option value="0">Nothing Selected</option>';

                        more_than_one = false;
                        selected_options  = [];

                        $.each(criteria, function(ind, cri){

                            if(cri.objective_id == objective_id && cri.outcome_id == outcome_id){
                                dictionary_to_keep = {
                                'value':cri.criterion_id,
                                'data-program-id':program.id,
                                'data-outcome-id':outcome_id,
                                'data-objective-id':objective_id,
                                'data-cobo-id':cri.cobo_id,
                                'data-pcobo-id':cri.pcobo_id
                                
                            }
                                option = $("<option>",{
                                'value':cri.criterion_id,
                                'data-program-id':program.id,
                                'data-outcome-id':outcome_id,
                                'data-objective-id':objective_id,
                                'data-cobo-id':cri.cobo_id,
                                'data-pcobo-id':cri.pcobo_id
                                
                            }).html(cri.name)
                           // option.prop('selected', true);

                            
                            selected_options.push(dictionary_to_keep);
                            
                            
                            
                            

                            }
                            else if (cri.outcome_id == outcome_id){
                            option = $("<option>",{
                                'value':cri.criterion_id,
                                'data-program-id':program.id,
                                'data-outcome-id':outcome_id,
                                'data-objective-id':objective_id,
                                'data-cobo-id':cri.cobo_id,
                                'data-pcobo-id':cri.pcobo_id

                                
                            }).html(cri.name)
                        }
                        
                  

                            options_html += option.prop('outerHTML');
                            //$(select).selectpicker('refresh');

                            //if(criteria)

                        
                        })


                        //create multiple selects. 

                        // el query es , Si no esta en program id, objetivo es 0. 
                        //Si program id 



                        
                        $('#program_objectives').append(prog_div);
                        select = createSelectForModal(options_html)

                        select.find('div.remove-btn').hide()
                        prog_div.append(select);
                        $('select.criteria_select').selectpicker('refresh');
                        if(selected_options.length>0){
                            $.each(selected_options, function(ind, cri){

                                the_picker = select.find('select.criteria_select').first();
                                the_picker.val(cri['value']);
                                the_picker.attr('data-old-pcobo', cri['data-pcobo-id'])
                                the_picker.attr('data-old-cobo', cri['data-cobo-id'])
                                the_picker.attr('data-old-criterion', cri['value'])
                                the_picker.attr('data-old-outcome', cri['data-outcome-id'])
                                the_picker.attr('data-old-objective', cri['data-objective-id'])

                                select = createSelectForModal(options_html)
                                prog_div.append(select)
                            // $('.criteria_select').selectpicker('refresh');
                            })
                            // to remove the last one
                            select.remove();
                        }
                        //prog_div.append(select)

                       // $('#program_objectives').append(prog_div);

                        $('select.criteria_select').selectpicker('refresh');

                        prog_div.append(createAddCriteriaButton("program-"+program.id))
                        

                    
                    })

                    program_select.selectpicker('refresh');
                    program_select.trigger('change');

                    $(mc).modal('show');


                    

                    

                    

                }
            )
        }
        
        wr = "#warning"
        function deleteCriterion(button){
            select =  $(button).parent().parent().find('select.criteria_select');

            $('.selected_criteria_to_delete').removeClass('selected_criteria_to_delete');

            $(button).addClass('selected_criteria_to_delete');
          
            criterion_id = $(select).val()
            if(criterion_id ==0){
                $(button).parent().parent().remove()
                return
            }
            option = $(select).find(':selected');
            name = $(select).find(':selected').html();
            program_id = $(option).data('program-id')
            outcome_id = $(option).data('outcome-id')
            objective_id = $(option).data('objective-id')
            cobo_id = $(option).data('cobo-id')
            pcobo_id = $(option).data('pcobo-id')
            $(wr+'_title').html("Are you sure you want to remove this Criterion?")
            $(wr+"_delete").attr('onclick', 'postDeleteCrit('+criterion_id+' ,'+program_id+' ,'+outcome_id+' ,'+objective_id+' ,'+cobo_id+' ,'+pcobo_id+'); $("'+wr+'").modal("hide") ');
            $(wr+'_body').html("<p>You are about to detach <strong>"+ name+"</strong> </p>")
            $(wr).modal('show');
        }

        function createAddCriteriaButton(program_div_id){

            div= $("<div>",{
                'class':'col-md-12'
            });
            
            button = $("<button>", {
                'class':'add_criteria btn btn-secondary',
                'type':'button',
                'onclick':'addSelect("#'+program_div_id+'")',
                'style':'float: right'  
            }).html(" <span class = 'glyphicon glyphicon-plus'></span> Add Criteria");
            div.append(button)
            div.append('<br><br>')
            return div;
        }

        function addSelect(program_div_id){
            options = $(program_div_id).children('.removable_div').first().find('select.criteria_select').html();
            $(program_div_id).children(".removable_div").last().after(createSelectForModal(options));
            $('select.criteria_select').selectpicker('refresh');
        }

        $('.view-scales').on('click', function() {
            var number_of_scales = this.value;

            $('.table-responsive').hide();
            $('.table-responsive-0').show();
            $('.table-' + number_of_scales).show();
        })

        function changeCriteriaDisplayed(select){

            select = $(select)

            program_id = select.val();

            $('.program_divs').hide();
            $("#program-"+program_id).show();
        }

    </script>
@stop

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

@section('javascript')
