<?php
header("content-type: application/json");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// connect to the mongo database
$m = new MongoDB\Driver\Manager("mongodb://root:oebb@mongo:27017");

$radsatz = $_GET['radsatz'];
#$station = $_GET['station'];

#$radsatz = '098597DL#1';
$station = 510;

$filter = ['overhauls.radsatznummer' => $radsatz];

$options_status = ['projection' => ['_id' => 0,  'overhauls.radsatznummer' => 1, 'overhauls.process.taetigkeiten.pruefungen' => 1,  'overhauls.process.stationsnummer' => 1, 'overhauls.process.taetigkeiten.name' => 1, 'overhauls.process.taetigkeiten.status' => 1 ]];

$query_status = new MongoDB\Driver\Query($filter,$options_status);

$cursor_status = $m->executeQuery('oebb.process_instances',$query_status);

foreach ($cursor_status as $document) {
  foreach ($document as $overhauls) {
    foreach ($overhauls as $overhaul) {
      if($overhaul->radsatznummer == $radsatz) {
        foreach($overhaul->process as $process) {
          if($process->stationsnummer == $station) {
            foreach($process->taetigkeiten as $taetigkeit) {
             #$result['status']=$taetigkeit->status;
             if(property_exists($taetigkeit, 'name') && strpos($taetigkeit->name, 'AUF') !== false) {
               $result['status']=$taetigkeit->pruefungen;
               foreach($taetigkeit->pruefungen as $pruefung) {
                 if($pruefung->name == "presskrafdiagram_min") {
                   $min = $pruefung->value_int;
                 } elseif ($pruefung->name == "presskrafdiagram_max") {
                   $max = $pruefung->value_int;
                 } elseif ($pruefung->name == "presskrafdiagram_wert") {
                   $value = $pruefung->value_int;
                 }
               }
               if($value < $min || $value > $max) {
                 $result["presskraftdiagramm"] = "Schlecht";
                 break;
               } else {
                 $result["presskraftdiagramm"] = "Gut";
               }
             }
            }
          }
        }
      }
    }
  }
}

echo json_encode($result);
