<?php
require_once 'lib/api.php';
require_once 'lib/tools.php';
// some sort of limit?!
session_start();

$data = array("handle" => $_GET['handle']);

$ret = api_call('vorgang/lesen', $data);

if (!isset($ret['vorgang'])) {
    echo 'error!';
    die();
}

$vorgang = $ret['vorgang'];

switch ($_GET['action']) {
    case 'delete_gitterbox':
        if (isset($_GET['id'])) {
            $id = $_GET['id'];
            foreach ($vorgang['bestellung'][0]['gitterbox'] as $key => $item) {
                if ($item['id'] == $id) {
                    unset($vorgang['bestellung'][0]['gitterbox'][$key]);
                    break;
                }
            }
        } else {
            array_shift($vorgang['bestellung'][0]['gitterbox']);
        }
        break;
    case 'delete_anhaenger':
        $kennz = $_GET['kennz'];
        foreach ($vorgang['bestellung'][0]['anhaenger'] as $key => $item) {
            if ($item['kennz'] == $kennz) {
                unset($vorgang['bestellung'][0]['anhaenger'][$key]);
                break;
            }
        }
        break;
    case 'add_gitterbox':
        $id = (isset($_GET['id']) ? $_GET['id'] : null);
        $vorgang['bestellung'][0]['gitterbox'][] = array("id" => $id);
        break;
    case 'add_anhaenger':
        $kennz = (isset($_GET['kennz']) ? $_GET['kennz'] : null);
        $vorgang['bestellung'][0]['anhaenger'][] = array("kennz" => $kennz);
        break;
}



$ret = api_call('vorgang/aendern', $vorgang);

if (!isset($ret['vorgang'])) {
    return;
}

header('Content-Type: application/json');
echo json_encode($ret['vorgang']);