<?php

require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/app/data-export.php';
require_once __DIR__ . '/app/audit.php';

$pdo = app_db_pdo();
$user = saas_require_login();

if (!saas_can_manage_tenant_settings($user)) {
    http_response_code(403);
    exit('Kein Zugriff.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    app_require_csrf();

    $tenantId = (int)$user['tenant_id'];
    $data = app_export_tenant_data($pdo, $tenantId);
    app_audit_log($pdo, $tenantId, (int)$user['user_id'], 'tenant_data.exported', 'tenant', $tenantId);

    $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $filename = 'kaffeeliste-export-' . $user['tenant_slug'] . '-' . date('Ymd_His') . '.json';

    header('Content-Type: application/json; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . strlen((string)$json));
    echo $json;
    exit;
}

include 'header.php';
include 'headerline.php';
include 'nav.php';
?>

<section id="banner">
    <div class="content">
        <h2>Datenexport</h2>
        <p>Lädt alle für <?php echo saas_html($user['tenant_name']); ?> gespeicherten Daten als
        JSON-Datei herunter: Mitglieder, Zugänge und Rollen, alle Buchungen, Hinweise,
        CSV-Importe, Mail-Versandlog und das Admin-Protokoll. Passwörter werden nicht
        exportiert.</p>

        <form method="post" action="datenexport.php">
            <?php echo app_csrf_field(); ?>
            <button type="submit">Export herunterladen</button>
        </form>

        <ul class="actions">
            <li><a href="konto.php" class="button alt">Zurück</a></li>
        </ul>
    </div>
</section>

<?php include 'footer.php'; ?>
