<?php

include 'apitest/infoapi/inc_common.php';

$mDebugLevel = getPostValue ('debuglevel', 0);
$mDebugSection = getPostValue ('debugsection', '');
$mJSONQuery = getPostValue ('jsonquery', '{"api_version": "1.0",
"app_option": "info",
"checksum": "B94EE5A90D07F3E6101E855EB1BB6EDA",
"client_id": "DEMO",
"client_version": "0.0.1",
"username": "info",
"password": "demo",
"poslovna_godina": 2016,
"req_id": "DOTEST_4S60QRPEI",
"data": "{\"result_database_format\": \"PLAIN_OBJ\"}",
"_class_name": "Tapiqueryenvelope"}');
$mShowEnvelope = getPostValue ('showenvelope', '');

$m_response = '';

$m_req_id = uniqid('', true);

// adresa Info API servera
//$m_url = 'http://apitest.infosys.rs:31000/InfoAPI.aspx';
//$m_url = 'http://localhost:31000/InfoAPI.aspx';
//$m_url = 'http://localhost:31001/InfoAPI.aspx';

$m_url = 'http://' . $_SERVER["HTTP_HOST"] . '/InfoAPI.aspx';
//$m_url = 'http://' . $_SERVER["HTTP_HOST"] . '/papi/';

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>PHP INFO API TESTER</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<p>API server: <?php echo $m_url; ?></p>

<form action="index.php" method="post">
JSON upit<br />
<textarea name="jsonquery" rows="12" cols="100">
<?php echo $mJSONQuery; ?>
</textarea>
<div>
DebugLevel: <input type="text" name="debuglevel" value="<?php echo $mDebugLevel; ?>"></input>
DebugSection: <input type="text" name="debugsection" value="<?php echo $mDebugSection; ?>"></input>
<input type="submit" name="submit" value="Izvrsi upit"></input> <input type="checkbox" name="showenvelope" <?php echo ($mShowEnvelope == 'on' ? 'checked' : ''); ?>> prikazi ceo sadrzaj odgovora</input>
</div>
</form>

<?php


  // ucitaj pripmer komande u JSON formatu
  //$m_json_query = file_get_contents ('json_test/apitest.json');
  $m_json_query = $mJSONQuery;

  // pripremi parametar za poziv servera
	$m_fields['json'] = $m_json_query;

//$m_fields['DebugLevel'] = 255;
//$m_fields['DebugSection'] = "SYSTEM,CLASS,APF_GETARTIKLILIST";

  $m_fields['DebugLevel'] = $mDebugLevel;
  $m_fields['DebugSection'] = $mDebugSection;

  // pripremi CURL konekciju
  $m_session = curl_init();

  // podesi URL APi servera
	curl_setopt($m_session, CURLOPT_URL, $m_url);

  // podesi broj polja u POST upitu
	curl_setopt($m_session, CURLOPT_POST, count ($m_fields));
  
echo "<p>POST: <br>";
  print_r ($m_fields);  

	// konvertuj polja upita u HTTP oblik
  $m_fields_query = http_build_query ($m_fields);

  // podesi upit
	curl_setopt($m_session, CURLOPT_POSTFIELDS, $m_fields_query);

  // podesi upit
	curl_setopt($m_session, CURLOPT_RETURNTRANSFER, true);

   // dozvoli svaku SSL konekciju
    curl_setopt($m_session, CURLOPT_SSL_VERIFYPEER, false);

  // izvrsi upit i preuzmi rezultat
	$m_json_data = curl_exec($m_session);

echo "<p>Response: <br>";
print_r ($m_json_data);


    if($m_json_data === false) {
      echo 'Curl error: ' . curl_error($m_session);
    }

  // zatvori konekciju
	curl_close($m_session);

  // dekodiraj omotnicu koja je u JSON formatu
  $m_envelope = json_decode ($m_json_data, true);
  
  set_if_empty ($m_envelope['error_message'], '');
  set_if_empty ($m_envelope['mesto'], '');
  set_if_empty ($m_envelope['referent'], '');

  //if (empty ($m_envelope['error_message'])) {
  //  $m_envelope['error_message'] = '';
  //}

  $m_data = $m_envelope['data'];

	if (! empty ($m_data)) {

    // dekodiraj odgovor koji je u JSON formatu
    $m_response = json_decode ($m_data, true);

  }
 
?>
<h2>Rezultat: [<?php echo $m_envelope['error_state']; ?>] <?php echo $m_envelope['error_message']; ?></h2>
<p>API funkcija: [<?php echo $m_envelope['app_option']; ?>]</p>
<p>Req_id: [<?php echo $m_envelope['req_id']; ?>] Sesija: [<?php echo $m_envelope['session_id']; ?>] Instanca: [<?php echo $m_envelope['instance_id']; ?>]</p>
<p>Poslovna godina: [<?php echo $m_envelope['poslovna_godina']; ?>] Pozicija: [<?php echo $m_envelope['pozicija']; ?> Job: <?php echo $m_envelope['job']; ?>]<br />
Sif. firme: [<?php echo $m_envelope['sif_firme']; ?>] Mesto: [<?php echo $m_envelope['mesto']; ?>]<br/>
<p>Referent: [<?php echo $m_envelope['referent']; ?>]</p>

<h3>Data</h3>
<?php
echo "<pre>";
print_r ($m_response);
echo "</pre>";
?>

<?php
if (! empty ($m_response['databaseattachment']) && ($m_response['database_format'] == 'PLAIN_OBJ') ) {
?>
<h4>Database attachment</h4>
<?php

echo $m_response['databaseattachment'];

  $m_databaseattachment = json_decode ($m_response['databaseattachment'], true);

echo '<p>DatabaseAttachmentDecodeError: ' . json_last_error() . ' ';

switch (json_last_error()) {
        case JSON_ERROR_NONE:
            echo ' - No errors';
        break;
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
        break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Underflow or the modes mismatch';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
        break;
        case JSON_ERROR_UTF8:
            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
        break;
        default:
            echo ' - Unknown error';
        break;
    }

echo '</p>';

echo "<pre>#";
print_r ($m_databaseattachment);
echo "#</pre>";

 foreach ($m_databaseattachment['items'] as $mTable) {

//  echo "<pre>";
//  print_r ($mTable);
//  echo "</pre>";

?>
<table border="1">
<caption><?php echo $mTable['table_name']; ?></caption>
<tr>
<?php
   foreach ($mTable['fields']['items'] as $mField) {
?>
<th><?php echo $mField['name']; ?></th>
<?php
  }
?>
</tr>


<?php
   foreach ($mTable['rows']['items'] as $mRow) {
?>
<tr>

<?php
     foreach ($mTable['fields']['items'] as $mField) {
?>
<td><?php 
	if (isset ($mRow[strtolower ($mField['name'])])) {
		echo $mRow[strtolower ($mField['name'])]; 
	} else {
		echo "";
	}
?></td>
<?php
    }
?>


</tr>
<?php
  }
?>


</table>
<?php
 }
}
?>


<?php
if (! empty ($m_envelope['debug_log'])) {
?>
<h3>Debug</h3>
DebugLevel: <?php echo $mDebugLevel; ?> DebugSection: <?php echo $mDebugSection; ?>

<?php
  echo "<pre>";
  print_r ($m_envelope['debug_log']);
  echo "</pre>";
}
?>

<?php
if ($mShowEnvelope == 'on') {
?>
<h3>Envelope</h3>
<?php
  echo "<pre>m_envelope=";
  print_r ($m_envelope);
  echo "</pre>";
}
?>
</body>
</html>
<?php

function set_if_empty (&$pValue, $pDefaultValue) {
  if (empty ($pValue)) {
    $pValue = $pDefaultValue;
  }
  return $pValue;
}

?>