<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Support\Guard;

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

Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_IMPORTS_VIEW);

$type = trim((string) ($type ?? ''));
$importService = app(\MintyPHP\Service\Import\ImportService::class);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$profile = $importService->profile($type);
if (!$profile) {
    http_response_code(404);
    return;
}

$currentUserId = (int) ($session['user']['id'] ?? 0);
$ability = match ($type) {
    'users' => \MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_IMPORTS_TYPE_USERS,
    'departments' => \MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_IMPORTS_TYPE_DEPARTMENTS,
    default => '',
};
$decision = $ability !== ''
    ? $authorizationService->authorize($ability, ['actor_user_id' => $currentUserId])
    : \MintyPHP\Service\Access\AuthorizationDecision::deny(403, 'forbidden');
if (!$decision->isAllowed()) {
    http_response_code(403);
    return;
}

$headers = array_keys($profile->allowedTargets());
$sampleRows = [];
if ($type === 'users') {
    $sampleRows[] = [
        'first_name' => 'Max',
        'last_name' => 'Mustermann',
        'email' => 'max.mustermann@example.com',
        'job_title' => 'Sales Manager',
        'profile_description' => 'Imported user',
        'phone' => '+49 555 12345',
        'mobile' => '+49 171 5551234',
        'short_dial' => '123',
        'address' => 'Musterstrasse 1',
        'postal_code' => '12345',
        'city' => 'Berlin',
        'region' => 'Berlin',
        'country' => 'DE',
        'hire_date' => '2026-01-15',
        'locale' => 'de',
        'active' => 'active',
        'tenant' => 'TENANT_UUID_OR_ID',
        'role' => 'ROLE_UUID_OR_ID',
        'department' => 'DEPARTMENT_UUID_OR_ID',
    ];
} elseif ($type === 'departments') {
    $sampleRows[] = [
        'description' => 'Sales',
        'tenant' => 'TENANT_UUID',
        'code' => 'SALES',
        'cost_center' => 'CC-100',
        'active' => 'active',
    ];
}

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $type . '-import-sample.csv"');
header('X-Content-Type-Options: nosniff');

$out = fopen('php://output', 'wb');
if (!$out) {
    http_response_code(500);
    return;
}

fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, $headers, ';', '"', '\\');
foreach ($sampleRows as $row) {
    $line = [];
    foreach ($headers as $header) {
        $line[] = (string) ($row[$header] ?? '');
    }
    fputcsv($out, $line, ';', '"', '\\');
}
fclose($out);
return;
