<?php

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Nur POST erlaubt.');
}

app_require_csrf();

$tenantId = filter_input(INPUT_POST, 'tenant_id', FILTER_VALIDATE_INT);
if ($tenantId === null || $tenantId === false || $tenantId <= 0) {
    http_response_code(400);
    exit('Ungültige Mandanten-ID.');
}

$stmt = $pdo->prepare('SELECT slug FROM tenants WHERE id = ?');
$stmt->execute([$tenantId]);
$slug = $stmt->fetchColumn();
if ($slug === false) {
    http_response_code(404);
    exit('Mandant wurde nicht gefunden.');
}

$data = app_export_tenant_data($pdo, $tenantId);
app_audit_log($pdo, $tenantId, (int)$user['user_id'], 'backoffice.tenant_exported', 'tenant', $tenantId);

$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$filename = 'backoffice-export-' . $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;
