<?php

$defaultJson = file_get_contents(__DIR__ . '/werbewand-demo.json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $payload = $_POST['payload_json'] ?? $defaultJson;

    $ch = curl_init('http://jasper:8080/api/v1/demo/werbewand/render.pdf');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER => false,
        CURLOPT_TIMEOUT => 60,
    ]);

    $response = curl_exec($ch);
    $statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($response !== false && $statusCode >= 200 && $statusCode < 300) {
        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="werbewand-demo.pdf"');
        echo $response;
        exit;
    }

    http_response_code(502);
    header('Content-Type: text/plain; charset=utf-8');
    echo "Reporting upstream failed.\n";
    echo "HTTP status: " . $statusCode . "\n";
    if ($error !== '') {
        echo "cURL error: " . $error . "\n";
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Purpoze Reporting Demo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f6f3f5;
            color: #1e1a1d;
            margin: 0;
            padding: 2rem;
        }

        main {
            max-width: 900px;
            margin: 0 auto;
        }

        h1 {
            margin: 0 0 0.5rem;
            font-size: 2rem;
        }

        p {
            margin: 0 0 1rem;
            line-height: 1.5;
        }

        textarea {
            width: 100%;
            min-height: 28rem;
            border: 1px solid #d7ccd2;
            border-radius: 8px;
            padding: 1rem;
            font-family: "SFMono-Regular", Consolas, monospace;
            font-size: 0.9rem;
            box-sizing: border-box;
            background: #fff;
        }

        button {
            margin-top: 1rem;
            padding: 0.8rem 1.2rem;
            border: 0;
            border-radius: 999px;
            background: #e4007f;
            color: #fff;
            font-size: 1rem;
            cursor: pointer;
        }
    </style>
</head>
<body>
<main>
    <h1>Purpoze Reporting Demo</h1>
    <p>Werbewand demo renderer running through the reporting service on this host.</p>
    <form method="post">
        <textarea name="payload_json"><?= htmlspecialchars($defaultJson, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?></textarea>
        <button type="submit">Render PDF</button>
    </form>
</main>
</body>
</html>
