<?php 

class formDataHandler {
  private $position;
  private $label;
  private $formDefs;
  private $confirmModal;

  public function __construct ($field) {
    if (isset($field)) {
      $this->field    = $field->field;
      $this->headText = $field->headText;
      $this->bodyText = $field->bodyText;
      $this->disabled = $field->disabled;
      $this->label    = $field->label;
      $this->form     = $field->form;
      $this->defLab   = explode ("_", $field->label)[0];

      if (isset($field->hideCommit))
         $this->hideCommit = $field->hideCommit;
      else
        $this->hideCommit = 0;

      if (isset($field->panelLevel))
         $this->panelLevel = $field->panelLevel;
      else
        $this->panelLevel = "panel0";

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

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

      if (isset($field->formData))
        $this->formData = $field->formData;
      else
        $this->formData = '{}';

      if (isset($field->formSeq))
        $this->formSeq = $field->formSeq;
      else
        $this->formSeq = '{}';

      if (isset($field->position) && $field->position == "left")
        $this->position = "float:left";
      else
        $this->position = "float:right";

      if (isset($field->confirmModal)) 
        $this->confirmModal = $field->confirmModal;
      else
        $this->confirmModal = 0;

    }
  }
  
  public function outputLayout() {
  
$html = "

<button id='fdh$this->form' class='btn btn-inverse fdh$this->form' value='$this->label' 
  onclick='processForm$this->field();' style='$this->position;$this->button'>
  $this->defLab
</button>
    ";
  	return $html;
  }
  
  public function outputScript() {
		
    $script = "
    
if (multiFunction === undefined)
  var multiFunction = [];

var str = '$this->summaryId';
var summaryId$this->field = (isNaN (str)) ? str : parseInt (str);
var fkeyId$this->field = 0;
var formDefs$this->field = [];
formDefs$this->field[0]  = JSON.parse('$this->formDef0');
formDefs$this->field[1]  = JSON.parse('$this->formDef1');
var currDef$this->field  = 0;

var formData$this->field = JSON.parse('$this->formData');
var formSeq$this->field  = JSON.parse('$this->formSeq');
hideCommit$this->field = $this->hideCommit;

function processForm$this->field () {
//  document.getElementById('valmsg$this->field').innerHTML = '';
  var valid$this->field = [];
  valid$this->field.fields = '';
  valid$this->field.message = '';
  valid$this->field.mandatoryCheck = false;
  valid$this->field.uniqueCheck = false;
  valid$this->field.confirmCheck = false;
  
  var ampersand = '';
  var dash = '';
  
  for (var i=0; i < formData$this->field.length; i++) {

    if (formData$this->field[i]['dbcolumn'] == 'fkid' || 
        formData$this->field[i]['dbcolumn'] == 'id') {
      valid$this->field.fields += ampersand + formData$this->field[i]['dbcolumn'] +
                '=' + formData$this->field[i]['newvalue'];
      ampersand = '&';            
    }

    if (formData$this->field[i]['mandatory'] == 1 && 
        formData$this->field[i]['newvalue'] == 0) {
      valid$this->field.message += dash + 'Missing ' + formData$this->field[i]['label'];
      dash = '&#8212';
      valid$this->field.mandatoryCheck = true;
    }

    if (formData$this->field[i]['uniquekey'] == 1) {
 
      valid$this->field.fields += ampersand + formData$this->field[i]['dbcolumn'] +
                '=' + formData$this->field[i]['newvalue'];
      ampersand = '&';            

      if (formData$this->field[i]['dbvalue'] != formData$this->field[i]['newvalue'])
        valid$this->field.uniqueCheck = true;
    }
    if (formData$this->field[i]['confirm'] == 1 && 
        formData$this->field[i]['dbvalue'] != 0 && 
        formData$this->field[i]['dbvalue'] != 
        formData$this->field[i]['newvalue']) {
      document.getElementById('cnfmsg$this->confirmModal').innerHTML = 
        formData$this->field[i]['label'] + ': ' + formData$this->field[i]['dbvalue'] + ' to ' + formData$this->field[i]['newvalue'];   
      valid$this->field.confirmCheck = true;
    }
  }
  
  submit$this->field (valid$this->field);
}

function submit$this->field (valid) {
  document.getElementById('valmsg$this->field').innerHTML = '';

  if (!(valid.mandatoryCheck || valid.uniqueCheck || valid.confirmCheck))
    put$this->field ();

  else if (valid.mandatoryCheck)
    document.getElementById('valmsg$this->field').innerHTML = valid.message;

  else if (valid.uniqueCheck && valid.message == '')
    key$this->field (valid);

  else if (valid.uniqueCheck)
    document.getElementById('valmsg$this->field').innerHTML = valid.message;

  else if (valid.confirmCheck)
    $('#modal$this->confirmModal').modal('show'); 
}

function confirm$this->form (okay) {
  if (okay)    
    put$this->field ();
}

function isEmpty(obj) {
  for(var key in obj) {
    if (obj.hasOwnProperty(key))
      return false;
  }
  return true;
}

function com$this->field (message) {
  var key = Object.keys(message);
logMessage ('<td>com msg</td><td>' + key + '</td><td>' + message[key][0] + '</td><td>' + message[key][1] + '</td><td>' + message[key][2] + '</td><td>' + message[key][3] + '</td><td>' + message[key][4] + '</td>'); 

  if (key == 'fkeyId') {
    if (fkeyId$this->field != message[key][1]) {
      fkeyId$this->field = message[key][1];
      var cdkey = message[key][3];
      var dbcolumn = formData$this->field[cdkey]['dbcolumn'];
      formDefs$this->field[0][dbcolumn] = message[key][1];
      formDefs$this->field[1][dbcolumn] = message[key][1];
      formData$this->field[cdkey]['newvalue'] = message[key][1];
      formData$this->field[cdkey]['newattr'] = message[key][2];
    }
  }
  
  else if (key == 'fkeyDate') {
      formDefs$this->field[0].date = message[key][1];
      formDefs$this->field[1].date = message[key][1];
  }

  else if (key == 'summaryId') {

    for (i=0; i < formData$this->field.length; i++) {
      if (formData$this->field[i]['keytype'] == 'fky')
         var dbcolumn = formData$this->field[i]['dbcolumn'];
    }     
 //alert ('com:' + dbcolumn + ' ' + message[key][1]);
    summaryId$this->field = message[key][1];
    formDefs$this->field[0][dbcolumn] = message[key][1];
    formDefs$this->field[1][dbcolumn] = message[key][1];

    selectId$this->field = 0;
    row$this->field (0, 1, '$this->field', 'sumid msg');   //CI
    var msgContent = [];
    msgContent['$this->field'] = [summaryId$this->field, '', 'sequent_ent', '', 'new cas value'];
//    newValue$this->form (msgContent);
  }

  else if (key == 'selectId') {
    row$this->field (message[key][1], 1, '$this->field', 'selid msg'); 
  }    


  else if (key == 'switchId') {

    if (currDef$this->field != message[key][1]) {
       currDef$this->field = message[key][1];
       row$this->field (0, 1, '$this->field', 'switch msg');
    }
  }    
}

multiFunction['com$this->field'] = {
  com$this->field:com$this->field
};  

function set$this->form (value, attr) {
  selectId$this->field = value;
}

multiFunction['set$this->field'] = {
  set$this->form: set$this->form
};

function newValue$this->form (message) {
  document.getElementById('valmsg$this->field').innerHTML = '';
  var key = Object.keys(message);
logMessage ('<td>newValue1</td><td>' + key + '</td><td>' + message[key][0] + '</td><td>' + message[key][1] + '</td><td>' + formData$this->field[key]['keytype'] + '</td><td>' + message[key][3] + '</td><td>' + message[key][4] + '</td>'); 

  var sender = message[key][0];
  var keyType = formData$this->field[key]['keytype'];
  var value = message[key][1];
  var attr = message[key][2];

  if (formData$this->field[key]['keytype'] == 'pky') {
    row$this->field (value, 1, '$this->form', 'newV pky');
  }

  else if (formData$this->field[key]['keytype'] == 'cxt') {
    if (value ==  0)
      row$this->field (0, 0, sender, 'newV cxt 0');
    else
      row$this->field (0, 1, sender, 'newV cxt 1');
    
  }
  
  else if (formData$this->field[key]['keytype'] == 'fky') {
    var dbcolumn = formData$this->field[key]['dbcolumn'];
    formDefs$this->field[0][dbcolumn] = message[key][1];
    formDefs$this->field[1][dbcolumn] = message[key][1];

//    var field = formData$this->field[key].field;
//    var setField = 'set' + field; 
//    var setFunction = setField + '';
//    multiFunction[setField][setFunction] (message[key][0],[attr,0]);
  }    

  formData$this->field[key]['newvalue'] = message[key][1];
  formData$this->field[key]['newattr'] = message[key][2];

  var sender = message[key][0];
// alert ('nv: ' + sender + ': ' + message[key][1] + ' ' + message[key][2]);
  seq$this->field (sender, message[key][1], message[key][2]);

 // if (formControl.action == 'switch' && selectId$this->field == 0)
 //   switchForm$this->field (formControl.sequent, message[key][1], message[key][2]);

 // if (formControl.commit == 1 && selectId$this->field == 0)
 //   processForm$this->field();
}

// Populate detail form
function setForm$this->field (dbResult, sender) {
  const keys = Object.keys(formData$this->field);

  for (const key of keys) {
    var keyType = formData$this->field[key].keytype; 
    if (keyType != 'fky') {
      var column = formData$this->field[key]['dbcolumn']; 
      formData$this->field[key]['dbvalue'] = dbResult[column];
      formData$this->field[key]['dbattr'] = dbResult[column+'_attr'];
      formData$this->field[key]['newvalue'] = dbResult[column];
      formData$this->field[key]['newattr'] = dbResult[column+'_attr'];
    
      var field = formData$this->field[key]['field'];
      var setField = 'set' + field; 
      var setFunction = setField + '';
      multiFunction[setField][setFunction] (dbResult[column], dbResult[column+'_attr']);

      var sdr = (keyType == 'pky') ? sender : field;
//alert ('sf:' + sdr + ' ' + column + ' ' + dbResult[column] + ' ' + dbResult[column+'_attr']);

      seq$this->field (sdr, dbResult[column], dbResult[column+'_attr']);
    }    
  }
}

function seq$this->field (sender, value, attr) {
//alert ('$this->form seq:' + sender + ' ' + value + ' ' + attr);
  if (formSeq$this->field[sender] !== undefined) {
    for (i=0; i<formSeq$this->field[sender].length;i++) {
      var comKey = formSeq$this->field[sender][i].comkey;
      var comField = 'com' + formSeq$this->field[sender][i].receiver; 
      var comFunction = comField + '';
//alert (comKey + ' s:' + sender + ' v:' + value + ' r:' + formSeq$this->field[sender][i].receiver + ' t:send com');
      var msgContent = [];
      msgContent[comKey] = [sender, value, attr, formSeq$this->field[sender][i].receiver, 'send com'];
      multiFunction[comField][comFunction] (msgContent);
    }
  }    
}

function switchForm$this->field (sequent, value, attr) {
  var keys = Object.keys(sequent);

  if (currDef$this->field != value) {
     currDef$this->field = value;
     row$this->field (0, 1, '$this->field', 'switch');
  }     
}

// Populate ajax params
function setData$this->field () {
  var reqData = null;
  const keys = Object.keys(formData$this->field);
  for (const key of keys) {
    reqData += '&' + formData$this->field[key]['dbcolumn'] + '=' + formData$this->field[key]['newvalue'] +
               '&' + formData$this->field[key]['dbcolumn'] + '_attr=' + formData$this->field[key]['newattr'];
  }
  return reqData;
}

// ROW form db data for selected summary row
function row$this->field (selectId, display, sender, reason) {

logMessage ('<td>get row</td><td>' + '$this->form' + '</td><td>' + sender + '</td><td>' + selectId + '</td><td>' + display + '</td><td>$this->form</td><td>' + reason + '</td>');  

  if (selectId == 0) { 

    if (display == 0)
      $('.fdh$this->form').prop('disabled', true);
    else 
      $('.fdh$this->form').prop('disabled', false);

    $('#del$this->form').prop('disabled', true);
    $('.fdh$this->form').html($('#fdh$this->form').prop('value').split('_')[0]);
    $('.tog$this->form').prop('disabled', true);
    $('[class^=$this->panelLevel]').each(function(){ $(this).slideUp('slow'); });
    setForm$this->field(formDefs$this->field[currDef$this->field], sender);
  }

  else {
    $('.fdh$this->form').prop('disabled', false);
    $('#del$this->form').prop('disabled', false);
    $('.fdh$this->form').html($('#fdh$this->form').prop('value').split('_')[1]);
    $('.tog$this->form').prop('disabled', false);

    var params = 'selectid=' + selectId;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'ajax/row$this->form.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);
        setForm$this->field(response, sender);
      }
    }
    xhr.send(params);
  }
}

// check for existing parent mapping
function map$this->field () {
  var xhr = new XMLHttpRequest();
  var params = '';
  var ampersand = '';
  var fkidUnset = false;

  for (var i=0; i < formData$this->field.length; i++) {
    if (formData$this->field[i]['keytype'] == 'mky') {
      params += ampersand + formData$this->field[i]['dbcolumn'] + '=' + formData$this->field[i]['newvalue'] +
               '&' + formData$this->field[i]['dbcolumn'] + '_attr=' + formData$this->field[i]['newattr'];
      ampersand = '&';
      if (formData$this->field[i]['newvalue'] == 0)
        fkidUnset = true;
    }    
  }

  if (fkidUnset) 
    formDefs$this->field[currDef$this->field].fkid = 0;

  else { 
    xhr.open('POST', 'ajax/map$this->field.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);
        formDefs$this->field[currDef$this->field].fkid = response;
        var source = (response == 0) ? 'sequent_frm' : 'sequent_upd'; 
        var sender = 'mapControlField';
        row$this->field (0, 1, sender, 'map chk');
      }
    }
    xhr.send(params);
  }    
}

// Ajax get form db data for selected summary row
function key$this->field (valid) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'ajax/key$this->field.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);
      valid.uniqueCheck = response[0];
      valid.message = response[1];
      submit$this->field (valid);
    }
  }
  xhr.send(valid.fields);
}

function put$this->field() {
  currDef$this->field  = 0;

  var params = setData$this->field ();
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'ajax/put$this->field.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);
      var sender = 'upd' + '$this->form';
      row$this->field (response, 1, sender, 'put resp');
    }  
  }
  xhr.send(params);
}

function del$this->form() {

  var params = setData$this->field ();
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'ajax/del$this->form.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);
//      formDefs$this->field[currDef$this->field].fkid = response;
      $('#del$this->form').prop('disabled', true);
      var sender = 'upd' + '$this->form';
      row$this->field (0, 0, sender, 'del resp')
    }
  }  
  xhr.send(params);
}
    ";
    return $script;
  }
}

?>
