<?php

use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Import\ImportServicesFactory;
use MintyPHP\Support\Guard;

define('MINTY_ALLOW_OUTPUT', true);

Guard::requireLogin();
Guard::requirePermission(PermissionService::IMPORTS_VIEW);

$type = trim((string) ($type ?? ''));
$factory = new ImportServicesFactory();
$importService = $factory->createImportService();
$profile = $importService->profile($type);
if (!$profile) {
    http_response_code(404);
    return;
}

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
$requiredPermission = $importService->requiredPermissionForType($type);

if ($requiredPermission === '' || !permissionGateway()->userHas($currentUserId, $requiredPermission)) {
    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;
