@extends('layouts.master-2')

@section('navigation')
    @if (Auth::user()->role == 1)
        @include('local.managers.admins._navigation')
    @elseif(Auth::user()->role == 2)
        @include('local.managers.sCoords._navigation')
    @elseif(Auth::user()->role == 3)
        @include('local.managers.pCoords._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 --}}


    <div class="row">
        <div class="col-md-3">
            <select class="form-control selectpicker" id="annual_plan" onchange="fetchInfo('annual_plan')">
                <option value='0'> Nothing Selected</option>
                @foreach ($annual_plans as $an_plan)
                    <option value={{ $an_plan->annual_id }}>Plan {{ $an_plan->academic_year }}</option>

                @endforeach
            </select>
            <br>



            <div id='allOutcomes'>

            </div>
        </div>


        <div class="col-md-9">
            <div id="outcome-display" class="panel panel-default">
                <div class="panel-heading">
                    <h4 class=" panel-title" style="cursor:auto!important;">
                        Primer Semestre 2019-2020
                    </h4>
                </div>
                <div class="panel-body">
                    <div id='outcomeInfo'>

                    </div>
                    <div id="tableOutcome">
                    </div>

                    <ul id="levelTabs" class="nav nav-tabs" role="tablist">

                    </ul>
                    <div id="allLists" class="tab-content">

                    </div>
                    <!-- <div class="table-responsive">
                    <table class="table table-striped table-condensed datatable" style="table-layout: fixed ; width : 100%">
                      <thead><tr><th>Objectives for courses</th><th>Criteria per Course</th><th>Transformative Actions</th></tr></thead>
                      <tbody>
                      </tbody>

                    </table>
                    
                </div>-->

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


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

    </div>
    <script>
        function nextChar(c) {
            return String.fromCharCode(c.charCodeAt(0) + 1);
        }
        changed = false;

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

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

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

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

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

            // When list item is clicked, load corresponding info

        });

        function fetchEverything(li) {
            var outcome_id = $(li).data('outcome-id');
            var name = $(li).data('outcome-name');
            var semester_id = $(li).data('semester-id');
            var annual_plan_id = $(li).data('annual-plan');
            var typ_semester_outcome_id = $(li).data('typ-semester-outcome-id');
            $('#theChange').data('annual-plan', annual_plan);
            $.post(
                "{{ URL::action('AnnualPlansController@fetchReportWithOutcome') }}", {
                    semester_id: semester_id,
                    outcome_id: outcome_id,
                    program_id: {{ $program->id }},
                    annual_plan_id: annual_plan_id,
                    typ_semester_outcome_id: typ_semester_outcome_id
                },
                function(outcome) {
                    if (outcome.objectives) {
                        $('table').show();
                        $('#outcome-display').parent().show();
                        $('#outcome-display .panel-title').html(name);
                        $('#allLists').empty();
                        $('#levelTabs').empty();
                        $('.no-outcome').hide();
                        if(outcome.outcome_program_goal){
                            outcome.outcome_program_goal = outcome.outcome_program_goal.expected_target;
                        }
                        else{
                            outcome.outcome_program_goal ='It has not been defined';
                        }
                        var outcomeHTML = "<h4>Performance of Students by Learning Outcome</h4>" +
                            '<h5 style = "display: inline; margin:30px;">Target learning by learning outcome: </h5>' +
                            '<p  style = "display: inline;"> <i>>= ' + outcome.expected_outcome +
                            ' of the attempts</i>' + '</p>' +
                            '<br><h5 style = "display: inline; margin:30px;">Expected percent of students achieving the target by learning outcome: </h5>' +
                            '<p  style = "display: inline;"> <i>' + outcome.outcome_program_goal + '</i></p>';
                        $('#outcomeInfo').html('<p class="outcome-definition">' + outcome.definition + '</p>' +
                            outcomeHTML);
                        //theStudentOutcomeTable = $("<table/>");
                        //theStudentOutcomeTable.hide();
                        ///$('#outcomeInfo').append(theStudentOutcomeTable);



                        wholeDict = {};


                        tableStudent = $('<table/>', {
                            'class': 'table table-striped table-condensed datatable'
                        });
                        tableStudent.html('<thead><tr>' +
                            '<th>Student</th>' +
                            '<th>Criteria Attempted</th>' +
                            '<th>Criteria Achieved</th>' +
                            '<th>Percentage</th>' +
                            '<th>Outcome Achieved</th>' +
                            '</tr></thead><tbody></tbody>');
                        $.each(outcome.objectives, function(index, objective) {

                            li = $('<li/>', {
                                'role': 'presentation'
                            });
                            a = $('<a/>', {
                                'data-toggle': 'tab',
                                'href': '#' + objective.id,
                                'role': 'tab'
                            }).html('Objective ' + (index + 1));
                            li.append(a);
                            $('#levelTabs').append(li);
                            objective_title = "<h3>" + objective.text + '</h3>';
                            div = $('<div/>', {
                                'role': 'tabpanel',
                                'class': 'tab-pane',
                                'id': objective.id
                            }).html(objective_title);




                            div.appendTo($('#allLists'))


                            if (objective.courses) {
                                $.each(objective.courses, function(index, course_code) {
                                    if (course_code.criteria.length) {

                                        $.each(course_code.students, function(index, student) {
                                            if (wholeDict[student.student_id] === undefined) {
                                                wholeDict[student.student_id] = {
                                                    'student': student.student_id,
                                                    'criteria_attempted': 0,
                                                    'criteria_achieved': 0
                                                }

                                            }
                                            wholeDict[student.student_id][
                                                "criteria_attempted"] += student
                                                .criteria_attempted;
                                            wholeDict[student.student_id][
                                                "criteria_achieved"] += student
                                                .criteria_achieved;

                                        });
                                        div.append(
                                            '<p>The following results are from the courses in the selected semester with the focused criteria in the selected annual plan</p>'
                                            );
                                        table = $('<table/>', {
                                            'class': 'table table-striped table-condensed datatable'
                                        }).html('<thead><th>Criterion</th><th>' +
                                            'Number of Students Assessed </th>' +
                                            '<th>Number of students that achieved the target</th></thead>'
                                            );
                                        tbody = $('<tbody/>')
                                        $.each(course_code.criteria, function(index, criterion) {

                                            tr = $('<tr/>').append(
                                                "<td>" + criterion.name + "</td>" +
                                                "<td>" + criterion.criteria_attempted +
                                                "</td>" +
                                                "<td>" + criterion.criteria_achieved +
                                                "</td>"
                                            );
                                            tbody.append(tr);
                                        });
                                        table.append(tbody);
                                        Course_and_transformative = '<h3>' + course_code.code + ' ' +
                                            course_code.number + '</h3><hr>';
                                        if (course_code.transforming_actions.length) {
                                            Course_and_transformative +=
                                                '<h5> This course was tied to the following transformative actions</h5>';
                                            Course_and_transformative += '<ol>';
                                            $.each(course_code.transforming_actions, function(index,
                                                transformative_action) {
                                                Course_and_transformative += '<li><p><strong>' +
                                                    transformative_action.at_text +
                                                    '</strong>: ' + transformative_action
                                                    .description + '</p></li>'
                                            })
                                        }

                                        div.append(Course_and_transformative)
                                        div.append(table);
                                        table.DataTable();


                                    }


                                })




                            } else {
                                div.append('<div class="no-outcome alert alert-info"' +
                                    '<p>No Course in plan has assessed yet</p>' +
                                    '</div>')
                            }


                        })
                        theArray = [];

                        $('#tableOutcome').html(tableStudent);
                        //tableStudent.appendTo($('#outcomeInfo'));

                        tableStudent = tableStudent.DataTable({
                            dom: 'Bfrtip',
                            buttons: [
                                'csv', 'excel', 'pdf', 'print'
                            ]
                        });
                        students_attempted = 0;
                        students_achieved = 0;
                        $.each(wholeDict, function(key, dict) {


                            if (dict.criteria_attempted) {
                                students_attempted += 1;
                                percentage = ((dict.criteria_achieved / dict.criteria_attempted) * 100).toFixed(
                                    2);
                                if (parseFloat(percentage) >= parseFloat(outcome.expected_outcome)) {
                                    achieved = "Yes"
                                    students_achieved += 1;
                                } else achieved = "No"
                            } else {
                                percentage = "N/A"
                                achieved = "N/A"
                            }
                            tableStudent.row.add([
                                dict.student,
                                dict.criteria_attempted,
                                dict.criteria_achieved,
                                percentage,
                                achieved

                            ]);
                        })

                        tableStudent.draw();

                        if (students_attempted) {
                            studentPercentage = ((students_achieved / students_attempted) * 100).toFixed(2);
                            if (parseFloat(studentPercentage) >= parseFloat(outcome.outcome_program_goal)) {
                                FinalReport = "<br><p><strong>The students achieved the Learning Outcome with " +
                                    studentPercentage + "% of students achieving.</strong></p>";
                            } else {
                                FinalReport = "<br><p><strong>The students did not achieve the Learning Outcome with " +
                                    studentPercentage + "% of students achieving.</strong></p>";

                            }
                        }

                        $("#outcomeInfo").append(FinalReport)





                        /* table.row.add([
                              objectivesHTML,
                              courseshtml,
                              
                              courseTAhtml
                              
                            ]);
                            table.draw();
                           */
                    } else {
                        $('table').hide();
                    }









                }

            );

        }

        function posttoTransAnnual(annual_id, selectTransId, typ_course_id) {
            ta = $("#" + selectTransId).val();
            old_ta = $("#" + selectTransId).data('old-TA');
            if (ta == "0") return;
            $.post("../annual-plan-postTA", {
                    annual_id: annual_id,
                    TA_id: ta,
                    typ_course_id: typ_course_id,
                    old_ta: old_ta
                },
                function(message) {

                    $("#" + selectTransId).data('old-TA', ta);

                }
            )
        }

        function addTAselect(options, master_div, annual_plan_id, objective_id, typ_course_id, selected_ta) {
            var $div = $('<div/>', {

                'class': 'form-group '
            });
            counter = parseInt($('#' + master_div).data('amount-ta'));

            var selectTA = $('<select/>', {
                'class': "selectpicker form-control",
                'data-live-search': 'true',
                'data-old-TA': '0',
                'data-width': '180px',

                'id': 'transformativeForObjective' + master_div + '_' + counter,
                'onchange': 'posttoTransAnnual(' + annual_plan_id + ', "transformativeForObjective' + master_div +
                    '_' + counter + '", ' + typ_course_id + ')'

            });
            selectTA.append(options);

            selectTA.appendTo($div);
            selectTA.val(selected_ta);
            selectTA.data('old-TA', selected_ta);
            selectTA.selectpicker('refresh');
            $span = $('<span/>', {
                'id': 'close',
                'onclick': '  postDeleteTA(' + annual_plan_id + ', "transformativeForObjective' + master_div + '_' +
                    counter + '", ' + typ_course_id +
                    '); this.parentNode.parentNode.removeChild(this.parentNode);return false;'
            }).html('x');
            $span.appendTo($div);
            $div.append("<br><br>");
            $('#' + master_div).append("<br>");

            $div.appendTo($('#' + master_div));
            $('#' + master_div).data('amount-ta', counter + 1);


        }

        function postDeleteTA(annual_id, selectTransId, typ_course_id) {
            ta = $("#" + selectTransId).val();


            if (ta == "0") return;
            $.post("../annual-plan-deleteTA", {
                annual_id: annual_id,
                TA_id: ta,
                typ_id: typ_course_id,

            });
            parent = $("#" + selectTransId).parent().parent().parent();
            counter = parseInt(parent.data('amount-ta'));
            parent.data('amount-ta', counter - 1);
        }

        function postToAnnualPlans(typ_course_id, criteria_select) {
            var criteria = $('#' + criteria_select).val();
            var oldCriteria = $('#' + criteria_select).data('old-criteria');
            var criteriaNode = document.getElementById(criteria_select).parentNode.parentNode.parentNode;

            var annual = criteriaNode.dataset.annualPlan;
            $.post("../annual-plan-postOnChange", {
                    criteria: criteria,
                    typ_course_id: typ_course_id,
                    annual_plan: annual,
                    old_criteria: oldCriteria
                },
                function(message) {
                    if (message == "Duplicate entry, please choose another criteria.") {
                        alert(message)
                    } else {
                        $('#' + criteria_select).data('old-criteria', criteria);
                        changed = true;
                    }

                })
        }


        function addCriteriaTest(div, new_id_for_select, typ_course_id, i = null, options) {

            if (!i) amount_select = $('#' + div).data("amount-select");
            else amount_select = i;
            $select = $('<select/>', {
                'class': "selectpicker form-control",
                'data-live-search': 'true',
                'data-old-criteria': '0',
                'data-width': '180px',

                'id': 'criteriaFor' + new_id_for_select + '_' + amount_select,
                'onchange': 'postToAnnualPlans(' + typ_course_id + ', "criteriaFor' + new_id_for_select + '_' +
                    amount_select + '")'

            })

            var $div = $('<div/>', {
                'id': 'courseSelect_' + new_id_for_select + '_' + amount_select,
                'class': 'form-group '
            });

            $select.append(options);
            $select.appendTo($div);
            $span = $('<span/>', {
                'id': 'close',
                'onclick': '  postDelete(' + typ_course_id + ', "criteriaFor' + new_id_for_select + '_' +
                    amount_select + '"); this.parentNode.parentNode.removeChild(this.parentNode);return false;'
            }).html('x');
            $div.append($span);
            $div.append("<br><br>")
            $('#' + div).append("<br>");
            $div.appendTo($("#" + div));



            $select.selectpicker('refresh');




            $("#" + div).data("amount-select", amount_select + 1);

        }
        $('#allOutcomes').hide();

        function postDelete(typ_course_id, criteria_select) {
            var criteria = $('#' + criteria_select).val();
            var oldCriteria = $('#' + criteria_select).data('old-criteria');
            var criteriaNode = document.getElementById(criteria_select).parentNode.parentNode.parentNode;

            var annual = criteriaNode.dataset.annualPlan;
            $.post("../annual-plan-deleteCriteria", {
                criteria: criteria,
                typ_course_id: typ_course_id,
                annual_plan: annual,
                old_criteria: oldCriteria
            });

        }

        function fetchInfo(id) {
            annual_id = $("#" + id).val();
            program_id = {{ $program->id }};
            $.post("{{ URL::action('AnnualPlansController@fetchInfo') }}", {
                    id: annual_id,
                    program_id: program_id


                },
                function(json) {

                    div = $('<div/>', {
                        'class': 'list-group',
                        'id': 'list'
                    });
                    if(json.outcomes.first){
                    header5 = $('<h5/>', {
                        'style': "padding-left: 10px"
                    }).html("First Semester");
                    div.append(header5);
                    list = '';
                    for (outcome in json.outcomes.first) {
                        list +=
                            "<li style='padding-left: 25px' onclick = 'fetchEverything(this)' data-annual-plan = '" +
                            json.annual_plans.id + "' data-typ-semester-outcome-id ='"+json.outcomes.first[outcome].typ_semester_outcome_id+"' data-semester-id = '" + json.allSemesterOrder.first.id +
                            "' data-outcome-id='" + json.outcomes.first[outcome].id + "' data-outcome-name ='" + json
                            .outcomes.first[outcome].name + "' class='list-group-item' >" + json.outcomes.first[outcome]
                            .name + " </li>";

                    }
                    div.append(list);
                    }
                    if(json.outcomes.second){
                    header4 = $('<h5/>', {
                        'style': "padding-left: 10px"
                    }).html("Second Semester");
                    div.append(header4);
                    list = '';
                    for (outcome in json.outcomes.second) {
                        list +=
                            "<li style='padding-left: 25px' onclick = 'fetchEverything(this)' data-annual-plan = '" +
                            json.annual_plans.id + "' data-typ-semester-outcome-id ='"+json.outcomes.first[outcome].typ_semester_outcome_id+"'data-semester-id = '" + json.allSemesterOrder.second.id +
                            "' data-outcome-id='" + json.outcomes.second[outcome].id + "' data-outcome-name ='" + json
                            .outcomes.second[outcome].name + "' class='list-group-item' >" + json.outcomes.second[
                                outcome].name + " </li>";

                    }
                    div.append(list);}
                    html = div[0].innerHTML;

                    $("#allOutcomes").html(div[0].innerHTML);
                    $("#allOutcomes").show();

                },
                "json",
            );

        }


        function deleteObjective(objectiveSelectDiv, closeObj) {

            $('#' + objectiveSelectDiv).remove();
            $('#' + closeObj).remove();
            $('#' + div).data("amount-select", $('#' + div).data("amount-select") - 1);

        }
    </script>




@stop

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