<?php 
defined('PUBLIC_ACCESS') or die('Restricted Access');

class SummDetail  {
  private $selectId;
  private $scope;
  private $baseId;
  private $formDefs;
  private $scopeId;
  private $summary;
  private $subdetail;
  private $messageList;
  private $iterator;  

  public function __construct($entry) {

    if (isset($entry)) {
      $this->selectId  = $entry->selectId;
      $this->scope     = $entry->scope;
      $this->baseId    = $entry->baseId;
      $this->scopeId   = $entry->scopeId;
      $this->subdetail = $entry->subdetail;
      $this->iterator  = $entry->iterator;

      if (isset ($entry->yScroll)) 
        $this->yScroll = "style='height:$entry->yScroll;overflow:auto;'";
      else
        $this->yScroll = "style='overflow:auto;'";

      if (null !== $entry->formDefs)
        $this->formDefs = json_encode($entry->formDefs);
      else
        $this->formDefs = '{}';

      if (null !== $entry->message) {
        $messages = explode(",", $entry->message);
        $this->messageList = "";

        for ($i=0; $i<count($messages); $i++) {
          $this->messageList .= "notify" . $messages[$i] . "(dbRowId); ";
        }
      }
     
      if ((count($entry->summary)) > 0) {
        $this->summary  = $entry->summary;
        $firstRow = reset($this->summary);
        $row = get_object_vars($firstRow);
        $this->props = array_keys($row);

        if ($firstRow->id == 0)       
          $this->summary  = [];

      }
      else {
        $this->summary  = [];
        $this->props = [];
      }
    }
  }

  public function outputLayout() {
      
    $layout = "
<div id='valmsg$this->scope' style='color:red'></div>    
<div id='summ-div$this->scope' $this->yScroll>
    
<table id=fth$this->scope class='table table-condensed'>
  <thead>
    <tr>
    ";

    for ($i=1; $i<count($this->props); $i++) {
      $colLabel = $this->props[$i];

      $layout .= "
      <th>$colLabel</th>  
      ";
    }    
  
    $layout .= "
    </tr>
  </thead>
  <tbody id='body$this->scope' class='filter$this->scope'>      
    ";
 
    foreach ($this->summary as $row) {
      $prop1 = $this->props[1];  
      $rowLabel = $row->$prop1;

      $layout .= "
    <tr>
      <td>
        <label><input class='detail-summ$this->scope' type='checkbox'
          value='$row->id'> $rowLabel</label> 
	    <div id='upd-det$row->id'></div>
      </td>
      ";  

      for ($i=2; $i<count($this->props); $i++) {
        $prop = $this->props[$i];
        $cellValue = $row->$prop;
        $layout .= "
      <td $style>
        $cellValue 
      </td>
        ";    
      }
      $layout .= "
      </tr>
      ";
    }
 	  $layout .= "    
  </tbody>  
</table>
</div>
    "; 


    return $layout;
  }	

  public function outputScript() {

	$script = "

// SUMMARY DETAIL
var commit$this->scope = false;
var default$this->scope;  //default reset values reset
var selectId$this->scope;
var scopeId$this->scope;

$(document).ready(function() {
  
  // passing a fixedOffset param will cause the table header to stick to the bottom of this element
  if ($('#summ-div$this->scope').get(0).scrollHeight > $('#summ-div$this->scope').height()) {  
	  $('#fth$this->scope').stickyTableHeaders({ scrollableArea: $('.scrollable-area')[0], 'fixedOffset': 2 });
  }
  var offset = $('.navbar').height();
//  $('html:not(.legacy) table').stickyTableHeaders({fixedOffset: offset});
//  $('table').stickyTableHeaders({fixedOffset: offset});

  selectId$this->scope = $this->selectId;
  scopeId$this->scope = $this->scopeId;

  default$this->scope = JSON.parse('$this->formDefs');

  if (selectId$this->scope > 0 && scopeId$this->scope > 0) {
    $('.detail-summ$this->scope[value='+selectId$this->scope+']').click();
  }
  else {
    detSet$this->scope(default$this->scope);
  }

});
    
$(document).on('click', '.detail-summ$this->scope', function (e) {

//  $('.slide-panel').each(function(){ $(this).slideUp('slow'); });
  $('#upd-det'+selectId$this->scope).html('');
  
  if (!$(this).prop('checked')) {

    $('#tog$this->iterator').prop('disabled', true);
    $('#tog2$this->iterator').prop('disabled', true);
    $('#tog3$this->iterator').prop('disabled', true);
    $('#tog4$this->iterator').prop('disabled', true);
    $('#del$this->iterator').prop('disabled', true);
    detSet$this->scope(default$this->scope);
    var dbRowId = 0;
    $this->messageList
  }
  else {  
    $('.detail-summ$this->scope').prop('checked', false);
    $(this).prop('checked', true);
    $('#tog$this->iterator').prop('disabled', false);
    $('#tog2$this->iterator').prop('disabled', false);
    $('#tog3$this->iterator').prop('disabled', false);
    $('#tog4$this->iterator').prop('disabled', false);
    $('#del$this->iterator').prop('disabled', false);
    var dbRowId = $(this).val();
    detail$this->scope (dbRowId);
    $this->messageList
  }	
});

function notify$this->scope (msgId) {

  if ('$this->scope' == 'reportgenerator') {
    scopeId$this->scope = msgId;
    detail$this->scope(scopeId$this->scope);
  }
  
  else {
    if ('$this->scope' == 'officetimesheet')
      detSet$this->scope(default$this->scope);
    $('#msg$this->scope').html('');
    $('#hid$this->scope').val(msgId);
    if (msgId != 0 && scopeId$this->scope != msgId) {  
      scopeId$this->scope = msgId;
      get$this->scope(scopeId$this->scope);
    }  
  }    
}

function commit$this->scope () {
  put$this->scope = true;
  put$this->iterator();
}

// Populate detail form
function detSet$this->scope (resp) {
  $('.$this->iterator').each(function(){
    if (typeof resp[$(this).prop('name')] != 'undefined') {
      if (($(this).prop('type') == 'text') || ($(this).prop('type') == 'hidden')) {
//alert ($(this).prop('name') + ' ' + resp[$(this).prop('name')]);  
        $(this).prop('value', resp[$(this).prop('name')]).trigger('chg$this->iterator');
      }    
      else if ($(this).prop('type') == 'time')
        $(this).prop('value', resp[$(this).prop('name')]);
      else if ($(this).prop('type') == 'date')
        $(this).prop('value', resp[$(this).prop('name')]);
      else if($(this).is('textarea')) 
        $(this).val(resp[$(this).prop('name')]);
      else if($(this).is('select')) {
        var selId = $(this).prop('name'); 
        var optId = resp[$(this).prop('name')];
        $('#'+selId+' option[value='+optId+']').prop('selected',true);
      }
    }
  }); 
}

function gen$this->scope (resp) {
  var inner = '';
  var rkeys;
  var highlight;
  var indicator;
  var style;
  var meta = new Array();
  for (var i=0; i<resp.length; i++) {
    if (i == 0) {
      rkeys = Object.keys (resp[i]);
//      inner += '<thead><tr>'
//      for (var j=1; j<rkeys.length; j++) {      
//        inner += '<th>' + formatLabel(rkeys[j]) + '</th>';
//      }  
//      inner += '</tr></thead><tbody>';
//      for (var j=1; j<rkeys.length; j++) {      
//        if (rkeys[j] == 'metadata') {
//          highlight = $row->metadata[0];
//          indicator = $row->metadata[1];
//        }
//      }  
    }
    
    inner += '<tr>';
    for (var j=1; j<rkeys.length; j++) { 
      if (j == 1) {
        inner += '<td><label><input class=detail-summ$this->scope type=checkbox value=' + resp[i].id + '> ' + 
             resp[i][rkeys[j]] + '</label><div id=upd-det' + resp[i].id + '></div>' +
             '<input id=' + resp[i].id + 'class=meta$this->scope type=hidden value=' + resp[i].metadata + '></td>';
      }       
      else if (resp[i].metadata != null) {
        meta = resp[i].metadata.split(',');
        highlight = meta[0];
        indicator = meta[1];
        style = '';
        if ( indicator == 0 && highlight == rkeys[j])        
          style = 'style=background-color:red';
        inner += '<td ' + style + '>' + resp[i][rkeys[j]] + '</td>'; 
      }  
      else
        inner += '<td>' + resp[i][rkeys[j]] + '</td>'; 
    }
    inner += '</tr>';
  }
  inner += '</tbody>';
  return inner;
}

function tog$this->iterator() {
      $('#summ-divsumminstances').animate({ scrollTop: 0 }, 'slow');

}
function tog2$this->iterator() {
}
function tog3$this->iterator() {
}
function tog4$this->iterator() {
}
function tog5$this->iterator() {
}
function tog6$this->iterator() {
}
function tog7$this->iterator() {
}

function put$this->iterator() {

  var params = new FormData();
  params = 'scopeid=' + scopeId$this->scope + '&' + 'baseid=$this->baseId';
//  data = '' + '&' + 'currid=' + selectId$this->scope + '&' + 'table=$this->scope';
  if ('$this->scope' == 'ptp_lots')
    params += '&' + 'cu_id=' + currtest_pits;
  $('.$this->iterator').each(function(){
    params +=   '&' + $(this).prop('name') + '=' + $(this).val();
  });
    
  if ('$this->scope' == 'officetimesheet' && ($('#parcel_id.pwpersonnel').val() == '0' || $('#role_id.pwpersonnel').val() == '0')) {
    $('#valmsg$this->scope').html('Select parcel and project role');
  }
  else if ('$this->scope' == 'sumpwoperations' && $('#seloperationname.pwoperation').val() == '0') {
    $('#valmsg$this->scope').html('Select or add an operation');
  }
  else {
    $('#valmsg$this->scope').html('');
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'ajax/put$this->iterator.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {//Call a function when the state changes.
      if (xhr.readyState == 4 && xhr.status == 200) {
        selectId$this->scope = JSON.parse(xhr.responseText);
        if ('$this->scope' == 'test_pits') {
          var dbRowId = scopeId$this->scope;
          $this->messageList
          $('.spatialunit[name='+'id'+']').val(dbRowId);
          $('#tog4spatialunit').prop('disabled', false);
        }
        else if ('$this->scope' == 'ptp_lots') {    
          selectId$this->scope = $('.detail-summ$this->scope:checkbox:checked').val(); 
          get$this->scope(scopeId$this->scope);
          get$this->scope(scopeId$this->scope);
          detSet$this->scope(default$this->scope);
          $('#del$this->iterator').prop('disabled', true);
          var ptpId = $('.spatialunit [name=id]').val();
          get$this->scope(ptpId);
        }  
        else if ('$this->scope' == 'officetimesheet') {
          var dbRowId = scopeId$this->scope;
          $('#ptr_id.pwpersonnel').val(dbRowId);
          get$this->scope(selectId$this->scope);
          detSet$this->scope(default$this->scope);
          $('#del$this->iterator').prop('disabled', true);
        }
        else if ('$this->scope' == 'summprojects') {
          get$this->scope(scopeId$this->scope);
//          detSet$this->scope(default$this->scope);
          $('#del$this->iterator').prop('disabled', true);
        }
        else {
          selectId$this->scope = $('.detail-summ$this->scope:checkbox:checked').val(); 
          get$this->scope(scopeId$this->scope);
          detSet$this->scope(default$this->scope);
          $('#del$this->iterator').prop('disabled', true);
        }  
      }
    }
    xhr.send(params);
  }    
}

function del$this->iterator() {
  var data = new FormData();
  data = 'table=$this->iterator' + '&' + 'scopeid=$this->scopeId' + '&' +
         'rowid=' + $('.detail-summ$this->scope:checkbox:checked').val();
         
  if ('$this->subdetail' != '')
    data += '&' + 'child=$this->subdetail';
  
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'ajax/putdel$this->iterator.php', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {//Call a function when the state changes.

    if (xhr.readyState == 4 && xhr.status == 200) {
      var response = JSON.parse(xhr.responseText);
      selDetail = 0;
      get$this->scope(scopeId$this->scope);
      detSet$this->scope(default$this->scope);
      $('#del$this->iterator').prop('disabled', true);
    }
  }  
  xhr.send(data);
}

function get$this->scope(id) {

  var params = 'currid=' + id + '&' + 'scopeid=' + scopeId$this->scope + '&' + 'baseid=$this->baseId';
  
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'ajax/get$this->scope.php', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {//Call a function when the state changes.
    if (xhr.readyState == 4 && xhr.status == 200) {
      var response = JSON.parse(xhr.responseText)
      $('#body$this->scope').html(gen$this->scope(response));
      if (selectId$this->scope > 0) {  
        $('#upd-det'+selectId$this->scope).html('<span class=\'glyphicon glyphicon-asterisk\'></span>');
        $('.detail-summ$this->scope[value='+selectId$this->scope+']').click();
      }
    }
  }  
  xhr.send(params);
}

// Ajax select detail for selected summary row
function detail$this->scope (id) {
	
  if (id == 0) { 
    document.getElementById('vars').innerHTML='';
    return;
  }

  var xhr = new XMLHttpRequest();
  var params = 'selid=' + id;

  xhr.open('POST', 'ajax/getdetl$this->scope.php', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function() {//Call a function when the state changes.
    if (xhr.readyState == 4 && xhr.status == 200) {
      var response = JSON.parse(xhr.responseText)
      detSet$this->scope(response);
    }
  }  
  xhr.send(params);
}


  ";

  return $script;
  }
}

?>