@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 --}}
    <script type="text/javascript">
        function filterOutcomes() {
            // Declare variables
            var input, filter, div, li, i, outcomeText;
            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++) {
                outcomeText = li[i].textContent;
                if (outcomeText.toUpperCase().indexOf(filter) > -1) {
                    li[i].style.display = "";
                } else {
                    li[i].style.display = "none";
                }
            }
        }
    </script>


    <div class="row" style="display: flex;">
        <div class="category">
            <label for="school">School</label>
            <div class="select">
                <select class="selectpicker" name="school" id="school">

                    @foreach ($schools as $school)
                        <option value="{{ $school->id }}">{{ $school->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>
        <div class="category">
            <label for="program">Academic Program</label>
            <div class="select">
                <select class="selectpicker" name="program" id="program">

                    @foreach ($programs as $program)
                        <option value="{{ $program->id }}">{{ $program->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>
        <div class="category">
            <label for="semesters">Semester</label>
            <div class="select">
                <select class="selectpicker" name="semesters" id="semesters">

                    @foreach ($semesters as $semester)
                        <option value="{{ $semester->id }}">{{ $semester->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>
    </div>
    <br>



    <div class="row">
        <div class="col-md-3">
            <input class="form-control" type="text" id="userInput" onkeyup="filterOutcomes()"
                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"
                        onclick="fetchData($(this),$('#semesters'), $('#program') )">{{ $outcome->name }} </li>

                @endforeach
            </div>
        </div>

        <div class="col-md-9">
            <div id="transformative-display">

            </div>
            <!--<div id="outcome-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="outcome-definition "></p>



                                                                          <div class="table-responsive table-responsive-0">
                                                                            {{-- tables are appended here --}}
                                                                            {{-- <table id="example" class="table table-striped table-condensed" width="100%"></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 createDataTable(table1) {
            title1 = table1[0].dataset.title

            table = $(table1).DataTable({
                lengthMenu: [5, 10, 25, 50],
                autoWidth: false,
                retrieve: true,
                pageLength: 10,
                // //fixed cols
                // fixedColumns:   {
                //     leftColumns: 1,
                // },
                // scrollY:        "600px",
                // scrollX:        true,
                // scrollCollapse: true,
                columnDefs: [{
                    width: 200,
                    targets: 0
                }],
                fixedColumns: true,

                bSortCellsTop: true, // To apply sort using top row only
                order: [
                    [0, "asc"]
                ],
                dom: 'Bflrtip',
                buttons: [{
                        extend: 'collection',
                        text: 'Export <span class="caret"></span>',
                        buttons: [{
                                extend: 'print',
                                exportOptions: {
                                    columns: ':visible'
                                },
                                text: 'Print',
                            },
                            {
                                extend: 'excelHtml5',
                                exportOptions: {
                                    columns: ':visible'
                                }
                            },
                            {
                                extend: 'pdfHtml5',
                                exportOptions: {

                                    columns: ':visible',
                                    stripNewlines: false,
                                    title: title1,
                                    text: title1,

                                },
                                customize: function(doc, dt) {
                                    //$('#loadingModal').modal('show');
                                    tableCopy = doc.content[1];
                                    doc.content[1] = {
                                        text: dt.exportOptions.text,
                                        style: 'title',
                                        margin: [0, 0, 0, 12]
                                    };
                                    doc.content[2] = tableCopy;
                                    doc.content[2].table.widths = ['20%', '20%', '20%', '20%', '20%']
                                    doc.pageSize = 'LEGAL';
                                    doc.pageOrientation = 'landscape';
                                    doc.defaultStyle.fontSize = 10;
                                    doc.styles.tableHeader.fillColor = '#E70033';

                                    // doc.content[1].layout= 'lightHorizontalLines';
                                    doc.content[2].layout = {
                                        hLineWidth: function(i, node) {
                                            if (i === 1) {
                                                return 2;
                                            } else if (i > 1) {
                                                return 1;
                                            } else {
                                                return 0;
                                            }
                                        },
                                        vLineWidth: function(i, node) {
                                            return 0;
                                        },
                                        hLineColor: function(i, node) {
                                            if (i === 1) {
                                                return '#000';
                                            } else if (i > 1) {
                                                return '#ccc';
                                            } else {
                                                return 'transparent';
                                            }
                                        },
                                        // vLineColor: function (i, node) {
                                        //     return (i === 0 || i === node.table.widths.length) ? 'black' : 'gray';
                                        // },
                                        paddingLeft: function(i, node) {
                                            return 5;
                                        },
                                        paddingRight: function(i, node) {
                                            return 5;
                                        },
                                        paddingTop: function(i, node) {
                                            return 5;
                                        },
                                        paddingBottom: function(i, node) {
                                            return 5;
                                        }
                                    };

                                    doc.content.splice(0, 0, {
                                        margin: [0, 0, 0, 12],
                                        alignment: 'center',
                                        width: 150,
                                        image: 'data:image/png;base64,[encoded data, 31780 characters]'
                                    });

                                    //$('#loadingModal').modal('hide');

                                }
                            },
                        ]
                    },
                    {
                        extend: 'colvis',
                        columns: ':gt(0)',
                        text: 'Column visibility <span class="caret"></span>',
                    }
                ],
            });
            // tables.push(table);

            // Apply the search
            table.columns().every(function() {
                // Search by keyword
                var column = this;
                $('input.column-search-bar', column.footer()).on('keyup change', function() {
                    if (column.search() !== this.value) {
                        console.log(this.value)

                        column
                            .search(this.value)
                            .draw();
                    }
                });

                // Search by dropdown menu
                column.data().unique().sort().each(function(d, j) {
                    $('select.column-search-select', column.footer()).append('<option value="' + d + '">' +
                        d + '</option>');
                });

                $('.column-search-select', column.footer()).on('change', function() {
                    var val = $.fn.dataTable.util.escapeRegex($(this).val());

                    column
                        .search(val ? '^' + val + '$' : '', true, false)
                        .draw();

                });
            });

            table.buttons().container()
                .appendTo($('.col-sm-6:eq(0)', table.table().container()));

            $(document).on('click', '.buttons-columnVisibility', function() {
                console.log('visibility toggled');
                table.columns.adjust().responsive.recalc();
            });
            return table;
        }

        function fetchData(outcome, semester, program) {
            //$('.list-group-item').on('click', function()
            // {
            var id = outcome.data('outcome-id');
            var semesters = semester.val();
            var programs = program.val();

            $.post(
                "{{ URL::action('TransformativeActionsController@fetchCourses') }}", {
                    id: id,

                    programs: programs,
                    semesters: semesters,


                },
                function(data) {

                    $('#transformative-display').html('');
                    if (data.length) {
                        var ul = $('<ul/>', {
                            'id': 'levelTabs',
                            'class': 'nav nav-tabs',
                            'role': 'tablist'
                        });
                        var divContent = $("<div/>", {
                            'class': 'tab-content'
                        });


                        if_course_exists = false;
                        $.each(data, function(index, groupedCourse) {
                            if (!groupedCourse.outcome_assessed) {
                                return;
                            }
                            if_course_exists = true;
                            var li = $('<li/>', {
                                'role': 'presentation',


                            })
                            var a = $('<a/>', {
                                'onclick': "$(this).tab('show')",
                                "data-toggle": "tab",
                                'href': '#' + groupedCourse.code + '-' + groupedCourse.number,
                                'aria-controls': groupedCourse.code + '-' + groupedCourse.number,
                                'role': 'tab'
                            }).html(groupedCourse.code + ' ' + groupedCourse.number);

                            li.append(a);
                            ul.append(li);

                            divPanel = $('<div/>', {
                                'role': 'tabpanel',
                                'class': 'tab-pane',
                                'id': groupedCourse.code + '-' + groupedCourse.number
                            });
                            $table = $('<table/>', {
                                "class": "table table-striped table-condensed datatable",
                                //"style": "table-layout: fixed",
                                "id": 'allTablesToExport' + index,
                                "data-title": groupedCourse.code + '-' + groupedCourse.number
                            });
                            $thead = $('<thead/>').html(
                                "<tr><th>Formative Actions</th><th>Section</th><th>Objectives and Criteria Associated </th><th>Activity</th></tr>"
                            );
                            $tbody = $('<tbody/>');
                            $table.append($thead);
                            $table.append($tbody);
                            divPanel.append($table);
                            $table = createDataTable($table);

                            $.each(groupedCourse.sections, function(index2, sections) {
                                courseHTML = sections.section;
                                $.each(sections.activities, function(index3, activities) {
                                    TransInfo = '<p><strong>' + activities.at_text +
                                        ': </strong>' + activities.description + '</p>'

                                    //If the objective_id is inside this dictionary, then the objective is inside the html already, 
                                    doesObjectiveExist = {};


                                    $.each(activities.criterion_with_objective, function(index4,
                                            criterion) {
                                            if (doesObjectiveExist[criterion
                                                    .objective_id] === undefined) {
                                                doesObjectiveExist[criterion.objective_id] =
                                                    "<li><p><strong>" + criterion.text +
                                                    '</strong></p><ul>';
                                            }
                                            doesObjectiveExist[criterion.objective_id] +=
                                                '<li>' + criterion.name + '</li>';

                                        }

                                    )
                                    criterion_objective_html = '<ol>';
                                    $.each(doesObjectiveExist, function(index4, string) {
                                        criterion_objective_html += string + '</ul>'

                                    })
                                    criterion_objective_html += '</ol>'
                                    $table.row.add([
                                        TransInfo,
                                        courseHTML,
                                        criterion_objective_html,
                                        activities.name
                                    ])

                                })
                                $table.draw();
                            });

                            divContent.append(divPanel);

                        })
                        if (if_course_exists) {
                            $('#transformative-display').append(ul);
                            $('#transformative-display').append(divContent);

                            $("a[role='tab']").first().tab('show');
                        } else {
                            $('#transformative-display').html(
                                '<h2 style="text-align: center">There is no course in this program that assessed the outcome on the selected semester </h2><br>'
                            )
                        }
                    } else {
                        $('#transformative-display').html(
                            '<h2 style="text-align: center">There is no course in this program that assessed on this semester </h2><br>'
                        )
                        $('.no-outcome').hide();

                    }
                    $('.no-outcome').hide();
                }
            );


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

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

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

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

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



            // When export button is clicked, export all tables as PDF

            // When list item is clicked, load corresponding info

        });
    </script>
@stop

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

@section('javascript')

@stop
