<?php

require "localconf.php";

if ($_SERVER['REQUEST_METHOD'] != "POST") {
    echo "Sorry, ich spreche kein GET.";
    return;
}
if (empty($_POST) && empty(file_get_contents('php://input'))) {
    echo "Ich brauche INPUT";
    return;
}

if ($_GET['controller'] == "Article"){
    if ($_GET['action'] == "store") {
        $json = file_get_contents('php://input');
        $file = fopen(__DIR__.'/data/articles.json','w');
        fwrite($file, $json);
        fclose($file);
        echo "Artikel wurden gespeichert.";
    }
}

if ($_GET['controller'] == "Inventur"){
    if ($_GET['action'] == "export") {
        $json = file_get_contents('php://input');
        $list = json_decode($json, true);
        $fp = fopen('data/inventur_'.date('Y-m-d').'.csv', 'w');

        fputcsv($fp,array_keys(flatten($list[0])));
        foreach ($list as $obj) {
            $fields = flatten($obj);
            //array_walk_recursive($obj, function($a)use (&$fields) { $fields[] = $a;});
            //print_r($fields);
            fputcsv($fp,$fields);
        }
        echo "Inventur wurde gespeichert.";
        fclose($fp);
    }
}


function flatten($array, $prefix = '') {
    $result = array();
    foreach($array as $key=>$value) {
        if(is_array($value)) {
            $result = $result + flatten($value, $prefix . $key . '_');
        }
        else {
            $result[$prefix . $key] = $value;
        }
    }
    return $result;
}