@extends('layouts.master-1')

@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>
  <!--quees la que hay-->

  <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)
          @foreach ($semesters as $semester)
          <?php Log::info($outcome->deactivation_date <= $semester->start)
          
        ; Log::info($outcome->deactivation_date);
        Log::info($semester->start) ?>
            @if(!$outcome->deleted_at && ( !$outcome->deactivation_date  ||$outcome->deactivation_date >= $semester->start))
            <!--if(!$outcome->deleted_at && $outcome->activation_date >= $semester->start && $outcome->activation_date <= $semester->end)-->
              <li data-outcome-id="{{ $outcome->id }}"class="list-group-item">{{ $outcome->name }} [{{$semester->code}}]</li>
            @endif
          @endforeach
        @endforeach
      </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;">
          </h4>
        </div>
        <div class="panel-body">
          <p class="outcome-definition "></p>
          <label for="">View Criterions with </label>
          <select class="view-scales input-sm" name=""></select>
          <label for="">Scales</label>
          {{-- <button type="button" name="button">Export All</button> --}}
          {{-- <div class=""> --}}
          <div class="dropdown show">
            <button class="btn btn-default buttons-collection" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
              <span>Export All
                <span class="caret"></span>
              </span>
            </button>
            <div class="dropdown-menu" role="menu" aria-labelledby="dropdownMenuLink">
              {{-- <a class="export-all print-all" <a href="#" disabled>Print</a></a><br> --}}
              <a class="export-all excel-all" <a href="#">Excel</a></a><br>
              <a class="export-all pdf-all" <a href="#">PDF</a></a>
            </div>
          </div>
          <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>

  <div id="StatusModal" class="modal fade" tabindex="-1" data-criterion-id="0">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Status</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body" id = "modalBody">
                <p></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="$('#temp_id').attr('id', '');">Cancel</button>
                <button type="button" class="btn btn-primary" onclick = 'statusChange()'>Yes</button>
            </div>
        </div>
    </div>
</div>
  <script>
function statusClick(link){
    var criterion_id = $(link).data('criterion-id');
    var text = $(link).text();

    if(text == "Active"){
      $('#modalBody').html('<p>Would you like to deactivate this criterion?</p>');
    }
    else $('#modalBody').html('<p>Would you like to activate this criterion?</p>');
    $(link).attr('id', 'temp_id');

    

    $('#StatusModal').data('criterion-id', criterion_id);
    $('#StatusModal').modal('show');
  }


  function statusChange(){
    criterion_id = $('#StatusModal').data('criterion-id');
    $.post(
    "{{ URL::action('CriteriaController@changeStatus') }}",
    { criterion_id: criterion_id, 

    },
    function(changed)
    {
      $('#StatusModal').modal('hide');
      if(changed == "deleted")
      $('#temp_id').text('Deactivated');
      else
      $('#temp_id').text('Active');
      $('#temp_id').attr('id', '');

    });
  }

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

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

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

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

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

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

  // When export button is clicked, export all tables as PDF
  $(document).on('click', '.export-all', function() {
    var export_type = $(this).attr('class');
    console.log('export_type');
    console.log(export_type);
    var r = confirm("Are you sure you want to download all programs info as separate PDFs? \n It may take a moment to process.");
    if (r == true) {

      //var 'tables' is defined in master.blade.php
      console.log("export all");
      $('table').each(function( t ) {
        var table = $(this).DataTable();

        if(export_type =="export-all print-all"){
          $('.table-responsive').show();
          table.buttons('0-0').trigger();
        }
        else if (export_type =="export-all excel-all"){
          $('.table-responsive').show();
          table.buttons('0-1').trigger();
        }
        else if (export_type =="export-all pdf-all"){
          $('.table-responsive').show();
          table.buttons('0-2').trigger();
        }
      });

      var current = $('select').val();
      $('.table-responsive').hide();
      $('.table-responsive-0').show();
      $('.table-'+current).show();
    }
  });

  // When list item is clicked, load corresponding info
  $('.list-group-item').on('click', function()
  {
    var id = $(this).data('outcome-id');
    var tables = [];

    $.post(
    "{{ URL::action('OutcomesController@fetchOutcome') }}",
    { id: id, 
    },
    function(data)
    {
      var outcome = data.outcome;
      var outcome_id = outcome.id;
      var name = outcome.name;
      var definition = outcome.definition;
      var criteria = outcome.criteria;

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

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

      //Empty table
      $('.table-responsive-0').empty();

      // Add new criteria
      if(criteria.length>0){

        // populate the selector for viewing different levels
        var selector = $('.view-scales');
        selector.empty();
        $.each(criteria, function(index, criterion_info){
          var criterions_levels = criterion_info.amount_of_levels;
          var new_option = $('<option />');
          new_option.attr('value',criterions_levels).html(criterions_levels);
          new_option.appendTo(selector);
        });

        //escibir los valores del outcome seleccionado
        $.each(criteria, function(index, criterion_info){
          var dataset = Array();
          var criterions = criterion_info[0];
          var criterions_levels = criterion_info.amount_of_levels;

          $.each(criterions, function(index, criterion){
              //
              var row = Array();
              var criterion_name = criterion.name;
              var criterion_scales = criterion.scales;
              var criterion_programs = criterion.programs;
              var program_html = '';

              row.push(criterion_name);
              $.each(criterion_scales, function(index, scale){
                  //
                 // var title = scale.title;
                  var description = scale.description;

                  //var cell_text = description;
                  row.push(description);
              });
              howManyPrograms = 0;
              $.each(criterion_programs, function(index, program){

              program_html += (index+1) +'. '+program+'<br>\n';
              howManyPrograms++;
              });
              row.push(program_html);
              role = {{{Auth::user()->role}}};
              
              switch (role) {
                case 1:
                if(!criterion.deleted_at) row.push('<a onclick = "statusClick(this)" data-criterion-id="'+criterion.id+'" href="#" class = "status">Active</a>');
              else row.push('<a href="#" onclick = "statusClick(this)" data-criterion-id="'+criterion.id+'" class = "status">Deactivated</a>');
                  break;
                case 2:
                if(!criterion.deleted_at) row.push('<a onclick = "statusClick(this)" data-criterion-id="'+criterion.id+'" href="#" class = "status">Active</a>');
              else row.push('<a href="#" onclick = "statusClick(this)" data-criterion-id="'+criterion.id+'" class = "status">Deactivated</a>');
              break;
              case 3:
                if(howManyPrograms<=1){
              if(!criterion.deleted_at) row.push('<a onclick = "statusClick(this)" data-criterion-id="'+criterion.id+'" href="#" class = "status">Active</a>');
              else row.push('<a href="#" onclick = "statusClick(this)" data-criterion-id="'+criterion.id+'" class = "status">Deactivated</a>');
                }

                else{
                  if(!criterion.deleted_at) row.push('<p>Active</p>');
              else row.push('<p>Deactivated</p>');
                }
                break;
                case 4:
                if(!criterion.deleted_at) row.push('<p>Active</p>');
              else row.push('<p>Deactivated</p>');
                  break;
              }
  
              if(criterion_scales.length < criterions_levels){
                var i = criterion_scales.length;
                while (i < criterions_levels){
                  //
                  var description = ' ';

                  row.push(description);
                  i++;
                }
              }
              dataset.push(row);
          });
          var columns_titles = Array();
          columns_titles.push({title: "Criterion"})
          var i = 0;
          while(i < criterions_levels){
            columns_titles.push({title: "Level "+(i+1)})
            i++;
          }
          columns_titles.push({title: "Program"});
          columns_titles.push({title: "Status"});

          var table_id = 'table-'+criterions_levels;
          var new_table_div = $('<div />').attr('class','table-responsive table-div '+table_id);
          new_table_div.append('<hr>');

          new_table_div.append('<hr>');
          new_table_div.append('<p><b class="h3">Criterions with '+criterions_levels+' levels</b></p>');
          new_table_div.append('<table id="'+table_id+'" class="table table-striped table-condensed" width="100%"></table>');

          new_table_div.appendTo('.table-responsive-0');
          //A ver si me cuenta

          var table2 = $('#'+table_id).DataTable( {
            order : [[parseInt(criterions_levels)+2, "asc"]],
            buttons: [
            {
              lengthMenu: [5, 10, 25, 50],
              autoWidth: false,
              retrieve: true,
              pageLength: 10,
              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,
                },
                customize: function(doc){
                  //$('#loadingModal').modal('show');

                  doc.pageSize = 'LEGAL';
                  doc.pageOrientation ='landscape';
                  doc.defaultStyle.fontSize = 10;
                  doc.styles.tableHeader.fillColor = '#E70033';

                  // doc.content[1].layout= 'lightHorizontalLines';
                  doc.content[1].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]'
                    } );

                  }
                },
                ]
              },
              {
                extend: 'colvis',
                columns: ':gt(0)',
                text: 'Column visibility <span class="caret"></span>',
              }
              ],
              data: dataset,
              columns: columns_titles,
            } );

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


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

          tables.push(table2);

        });

        var first_table = '.table-'+criteria[0].amount_of_levels;

        $('.table-responsive').hide();
        $('.table-responsive-0').show();
        $(first_table).show();
      } // if


      //else
      //$('table').hide();

      // Update display
      {{-- table.draw(); --}}
    }
    );


  })
});
    </script>
@stop

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

@section('javascript')
/*
$(document).ready(function()
{
  // --------------------------------------------------------------------------
  // Page load
  // --------------------------------------------------------------------------

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

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

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

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

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

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

  // When export button is clicked, export all tables as PDF
  $(document).on('click', '.export-all', function() {
    var export_type = $(this).attr('class');
    console.log('export_type');
    console.log(export_type);
    var r = confirm("Are you sure you want to download all programs info as separate PDFs? \n It may take a moment to process.");
    if (r == true) {

      //var 'tables' is defined in master.blade.php
      console.log("export all");
      $('table').each(function( t ) {
        var table = $(this).DataTable();

        if(export_type =="export-all print-all"){
          $('.table-responsive').show();
          table.buttons('0-0').trigger();
        }
        else if (export_type =="export-all excel-all"){
          $('.table-responsive').show();
          table.buttons('0-1').trigger();
        }
        else if (export_type =="export-all pdf-all"){
          $('.table-responsive').show();
          table.buttons('0-2').trigger();
        }
      });

      var current = $('select').val();
      $('.table-responsive').hide();
      $('.table-responsive-0').show();
      $('.table-'+current).show();
    }
  });

  // When list item is clicked, load corresponding info
  $('.list-group-item').on('click', function()
  {
    var id = $(this).data('outcome-id');
    var tables = [];

    $.post(
    "{{ URL::action('OutcomesController@fetchOutcome') }}",
    { id: id },
    function(data)
    {
      var outcome = data.outcome;
      var outcome_id = outcome.id;
      var name = outcome.name;
      var definition = outcome.definition;
      var criteria = outcome.criteria;

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

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

      //Empty table
      $('.table-responsive-0').empty();

      // Add new criteria
      if(criteria.length>0){

        // populate the selector for viewing different levels
        var selector = $('.view-scales');
        selector.empty();
        $.each(criteria, function(index, criterion_info){
          var criterions_levels = criterion_info.amount_of_levels;
          var new_option = $('<option />');
          new_option.attr('value',criterions_levels).html(criterions_levels);
          new_option.appendTo(selector);
        });

        //escibir los valores del outcome seleccionado
        $.each(criteria, function(index, criterion_info){
          var dataset = Array();
          var criterions = criterion_info[0];
          var criterions_levels = criterion_info.amount_of_levels;

          $.each(criterions, function(index, criterion){
              //
              var row = Array();
              var criterion_name = criterion.name;
              var criterion_scales = criterion.scales;

              row.push(criterion_name);
              $.each(criterion_scales, function(index, scale){
                  //
                  var title = scale.title;
                  var description = scale.description;

                  var cell_text = '<b>'+title+'</b><br>\n'+description;
                  row.push(cell_text);
              });
              if(criterion_scales.length < criterions_levels){
                var i = criterion_scales.length;
                while (i < criterions_levels){
                  //
                  var description = ' ';

                  row.push(description);
                  i++;
                }
              }
              dataset.push(row);
          });
          var columns_titles = Array();
          columns_titles.push({title: "Criterion"})
          var i = 0;
          while(i < criterions_levels){
            columns_titles.push({title: "Level "+(i+1)})
            i++;
          }

          var table_id = 'table-'+criterions_levels;
          var new_table_div = $('<div />').attr('class','table-responsive table-div '+table_id);
          new_table_div.append('<hr>');

          new_table_div.append('<hr>');
          new_table_div.append('<p><b class="h3">Criterions with '+criterions_levels+' levels</b></p>');
          new_table_div.append('<table id="'+table_id+'" class="table table-striped table-condensed" width="100%"></table>');

          new_table_div.appendTo('.table-responsive-0');

          var table2 = $('#'+table_id).DataTable( {
            buttons: [
            {
              lengthMenu: [5, 10, 25, 50],
              autoWidth: false,
              retrieve: true,
              pageLength: 10,
              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,
                },
                customize: function(doc){
                  //$('#loadingModal').modal('show');

                  doc.pageSize = 'LEGAL';
                  doc.pageOrientation ='landscape';
                  doc.defaultStyle.fontSize = 10;
                  doc.styles.tableHeader.fillColor = '#E70033';

                  // doc.content[1].layout= 'lightHorizontalLines';
                  doc.content[1].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]'
                    } );

                  }
                },
                ]
              },
              {
                extend: 'colvis',
                columns: ':gt(0)',
                text: 'Column visibility <span class="caret"></span>',
              }
              ],
              data: dataset,
              columns: columns_titles,
            } );

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


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

          tables.push(table);

        });

        var first_table = '.table-'+criteria[0].amount_of_levels;

        $('.table-responsive').hide();
        $('.table-responsive-0').show();
        $(first_table).show();
      } // if


      //else
      //$('table').hide();

      // Update display
      {{-- table.draw(); --}}
    }
    );


  })
});
*/
@stop
