<?php
/*
 * UJS REST-v1 Beispiel als einbindbare PHP-Funktionen.
 *
 * Kompatibel mit PHP 5.5 bis PHP 8.x.
 * Abhaengigkeiten: ext-curl, ext-json.
 *
 * Verwendung:
 * 1. Diese Datei herunterladen/kopieren.
 * 2. Im Zielprojekt als example_funktion.php speichern.
 * 3. Zugangsdaten unten im Konfigurationsblock einsetzen.
 *
 * Direkt testen:
 *
 *   php example_funktion.php
 *
 * Einbindung in ein Projekt:
 *
 *   require_once 'example_funktion.php';
 *   $result = ujs_example_store(
 *       'https://dev.jsonstorage.de',
 *       'TOKEN',
 *       'testmodul',
 *       'test_note',
 *       'K-1001',
 *       array('title' => 'Hallo'),
 *       array('testmodul')
 *   );
 */

/*
 * Zugangsdaten für den Beispielaufruf.
 * Einen echten Token hier nur lokal eintragen, nicht in eine öffentlich
 * abrufbare Datei schreiben.
 */
$ujsExampleBaseUrl = 'https://dev.jsonstorage.de';
$ujsExampleModule = 'testmodul';
$ujsExampleToken = '2618a9dd9eba3515b50c427d66e5635b1bda91cf443e51ce';

if (!function_exists('ujs_example_request')) {
    function ujs_example_request($baseUrl, $token, $method, $path, $query, $body, $extraHeaders)
    {
        if (!function_exists('curl_init')) {
            return array('success' => false, 'error' => 'PHP extension curl fehlt', '_status' => 0);
        }

        $url = rtrim($baseUrl, '/') . '/api/v1' . $path;
        $cleanQuery = array();
        if (is_array($query)) {
            foreach ($query as $key => $value) {
                if ($value !== null && $value !== '') {
                    $cleanQuery[$key] = $value;
                }
            }
        }
        if ($cleanQuery) {
            $url .= '?' . http_build_query($cleanQuery);
        }

        $rawBody = $body !== null ? json_encode($body) : '';
        $headers = array(
            'Authorization: Bearer ' . $token,
            'X-Request-ID: example-' . str_replace('.', '', uniqid('', true)),
        );

        if (is_array($extraHeaders)) {
            foreach ($extraHeaders as $header) {
                $headers[] = $header;
            }
        }
        if ($rawBody !== '') {
            $headers[] = 'Content-Type: application/json';
        }

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if ($rawBody !== '') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $rawBody);
        }

        $response = curl_exec($ch);
        $error = curl_error($ch);
        $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($response === false) {
            return array('success' => false, 'error' => $error ? $error : 'cURL request failed', '_status' => 0);
        }

        $decoded = json_decode($response, true);
        $out = is_array($decoded) ? $decoded : array('raw' => $response);
        $out['_status'] = $status;
        return $out;
    }
}

if (!function_exists('ujs_example_whoami')) {
    function ujs_example_whoami($baseUrl, $token)
    {
        return ujs_example_request($baseUrl, $token, 'GET', '/whoami', array(), null, array());
    }
}

if (!function_exists('ujs_example_store')) {
    function ujs_example_store($baseUrl, $token, $moduleSlug, $type, $customerNo, $data, $tags)
    {
        return ujs_example_request(
            $baseUrl,
            $token,
            'POST',
            '/modules/' . rawurlencode($moduleSlug) . '/entries',
            array(),
            array(
                'type' => $type,
                'customer_no' => $customerNo,
                'data' => $data,
                'tags' => $tags,
            ),
            array()
        );
    }
}

if (!function_exists('ujs_example_get')) {
    function ujs_example_get($baseUrl, $token, $moduleSlug, $id)
    {
        return ujs_example_request($baseUrl, $token, 'GET', '/modules/' . rawurlencode($moduleSlug) . '/entries/' . (int)$id, array(), null, array());
    }
}

if (!function_exists('ujs_example_list')) {
    function ujs_example_list($baseUrl, $token, $moduleSlug, $query)
    {
        return ujs_example_request($baseUrl, $token, 'GET', '/modules/' . rawurlencode($moduleSlug) . '/entries', $query, null, array());
    }
}

if (!function_exists('ujs_example_update')) {
    function ujs_example_update($baseUrl, $token, $moduleSlug, $id, $patch, $ifVersion)
    {
        $headers = array();
        if ($ifVersion !== null) {
            $headers[] = 'If-Match: "v' . (int)$ifVersion . '"';
        }

        return ujs_example_request($baseUrl, $token, 'PUT', '/modules/' . rawurlencode($moduleSlug) . '/entries/' . (int)$id, array(), $patch, $headers);
    }
}

if (!function_exists('ujs_example_history')) {
    function ujs_example_history($baseUrl, $token, $moduleSlug, $id, $limit, $offset)
    {
        return ujs_example_request($baseUrl, $token, 'GET', '/modules/' . rawurlencode($moduleSlug) . '/entries/' . (int)$id . '/history', array(
            'limit' => (int)$limit,
            'offset' => (int)$offset,
        ), null, array());
    }
}

if (!function_exists('ujs_example_aggregate')) {
    function ujs_example_aggregate($baseUrl, $token, $moduleSlug, $query)
    {
        return ujs_example_request($baseUrl, $token, 'GET', '/modules/' . rawurlencode($moduleSlug) . '/aggregate', $query, null, array());
    }
}

if (!function_exists('ujs_example_delete')) {
    function ujs_example_delete($baseUrl, $token, $moduleSlug, $id)
    {
        return ujs_example_request($baseUrl, $token, 'DELETE', '/modules/' . rawurlencode($moduleSlug) . '/entries/' . (int)$id, array(), null, array());
    }
}

if (!function_exists('ujs_example_print')) {
    function ujs_example_print($title, $data)
    {
        echo "\n=== " . $title . " ===\n";
        echo json_encode($data, defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0) . "\n";
    }
}

if (!function_exists('ujs_example_fail')) {
    function ujs_example_fail($message)
    {
        if (PHP_SAPI === 'cli' && defined('STDERR')) {
            fwrite(STDERR, $message . "\n");
        } else {
            if (!headers_sent()) {
                header('Content-Type: text/plain; charset=utf-8');
                http_response_code(400);
            }
            echo $message . "\n";
        }
        exit(1);
    }
}

if (isset($_SERVER['SCRIPT_FILENAME']) && realpath($_SERVER['SCRIPT_FILENAME']) === realpath(__FILE__)) {
    if (PHP_SAPI !== 'cli' && !headers_sent()) {
        header('Content-Type: text/plain; charset=utf-8');
    }

    $baseUrl = getenv('UJS_BASE_URL') ? getenv('UJS_BASE_URL') : $ujsExampleBaseUrl;
    $module = getenv('UJS_MODULE') ? getenv('UJS_MODULE') : $ujsExampleModule;
    $token = getenv('UJS_TOKEN') ? getenv('UJS_TOKEN') : $ujsExampleToken;

    if ($token === '') {
        ujs_example_fail("Bitte im Konfigurationsblock \$ujsExampleToken setzen oder UJS_TOKEN übergeben.");
    }

    ujs_example_print('Token prüfen', ujs_example_whoami($baseUrl, $token));

    $created = ujs_example_store($baseUrl, $token, $module, 'test_note', 'TEST-1001', array(
        'title' => 'UJS Testeintrag',
        'status' => 'open',
        'created_by' => 'example_funktion.php',
        'amount' => 129.90,
    ), array('testmodul', 'php-function'));
    ujs_example_print('Eintrag erstellen', $created);

    $id = isset($created['entry']['id']) ? (int)$created['entry']['id'] : 0;
    if ($id > 0) {
        ujs_example_print('Eintrag lesen', ujs_example_get($baseUrl, $token, $module, $id));
        ujs_example_print('Liste filtern', ujs_example_list($baseUrl, $token, $module, array(
            'customer_no' => 'TEST-1001',
            'q[data.status]' => 'open',
            'limit' => 10,
        )));
        ujs_example_print('Eintrag aktualisieren', ujs_example_update($baseUrl, $token, $module, $id, array(
            'data' => array(
                'title' => 'UJS Testeintrag',
                'status' => 'done',
                'created_by' => 'example_funktion.php',
                'amount' => 129.90,
            ),
            'tags' => array('testmodul', 'php-function', 'done'),
        ), isset($created['entry']['version']) ? (int)$created['entry']['version'] : null));
        ujs_example_print('Historie', ujs_example_history($baseUrl, $token, $module, $id, 100, 0));
        ujs_example_print('Aggregation', ujs_example_aggregate($baseUrl, $token, $module, array(
            'agg' => 'sum',
            'field' => 'amount',
            'group_by' => 'customer_no',
        )));
    }
}