<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Service\User\UserAccessPdfService;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
define('MINTY_ALLOW_OUTPUT', true);

// Hard gate: user must be logged in and explicitly allowed to generate access PDFs.
Guard::requireLogin();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$userAccountService = app(\MintyPHP\Service\User\UserAccountService::class);
$userAccessPdfService = app(UserAccessPdfService::class);
$request = requestInput();
$errorBag = formErrors();

// Support both route param and POSTed uuid (POST avoids exposing uuid in URL/history).
$uuid = trim((string) ($id ?? ''));
if ($uuid === '' && $request->isMethod('POST')) {
    if (!actionRequireCsrf('admin/users', 'admin/users', 'users_access_pdf')) {
        return;
    }
    $uuid = trim((string) ($request->bodyAll()['uuid'] ?? ''));
}
$user = $uuid !== '' ? $userAccountService->findByUuid($uuid) : null;
if (!$user) {
    if ($request->isMethod('POST')) {
        $errorBag->addGlobal(t('User not found'));
        flashFormErrors($errorBag, 'admin/users', 'users_access_pdf');
        Router::redirect('admin/users');
        return;
    }
    http_response_code(404);
    return;
}

$currentUserId = (int) ($session['user']['id'] ?? 0);
$userId = (int) ($user['id'] ?? 0);
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_ACCESS_PDF, [
    'actor_user_id' => $currentUserId,
    'target_user_id' => $userId,
]);
if (!$decision->isAllowed()) {
    Router::redirect('error/forbidden');
    return;
}

$pdf = $userAccessPdfService->renderUserAccessPdf($user);
if ($pdf === '') {
    // Keep error generic; service handles concrete renderer/asset failures internally.
    http_response_code(500);
    return;
}

$locale = strtolower((string) (\MintyPHP\I18n::$locale ?? \MintyPHP\I18n::$defaultLocale));
$filename = str_starts_with($locale, 'de') ? 'zugangsdaten.pdf' : 'access-details.pdf';

header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Cache-Control: private, no-store, max-age=0');
header('Pragma: no-cache');
header('X-Content-Type-Options: nosniff');
header('Content-Length: ' . strlen($pdf));

$output = fopen('php://output', 'wb');
if ($output === false) {
    http_response_code(500);
    return;
}
fwrite($output, $pdf);
fclose($output);
