<?php

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

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

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
$factory = new ImportServicesFactory();
$importService = $factory->createImportService();

$profileOptions = [];
foreach ($importService->listProfileOptions() as $option) {
    $key = (string) $option['key'];
    $permission = $importService->requiredPermissionForType($key);
    $allowed = $permission !== '' && permissionGateway()->userHas($currentUserId, $permission);
    $profileOptions[] = [
        'key' => $key,
        'label' => (string) $option['label'],
        'allowed' => $allowed,
        'permission' => $permission,
    ];
}

$allowedProfileOptions = array_values(array_filter($profileOptions, static fn (array $option): bool => !empty($option['allowed'])));
$firstAllowedType = '';
if ($allowedProfileOptions) {
    $firstAllowedType = (string) ($allowedProfileOptions[0]['key'] ?? '');
}

$selectedType = trim((string) ($_POST['type'] ?? ($_GET['type'] ?? $firstAllowedType)));
if ($selectedType === '' || !$importService->profile($selectedType)) {
    $selectedType = $firstAllowedType;
}

$step = 'upload';
$errors = [];
$token = '';
$state = null;
$mapping = [];
$preview = null;
$result = null;

$csrfKey = Session::$csrfSessionKey;
$csrfToken = $_SESSION[$csrfKey] ?? '';

$hasImportPermission = static function (string $type) use ($currentUserId, $importService): bool {
    $permission = $importService->requiredPermissionForType($type);
    return $permission !== '' && permissionGateway()->userHas($currentUserId, $permission);
};

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $stage = trim((string) ($_POST['stage'] ?? ''));
    if (!Session::checkCsrfToken()) {
        $errors[] = t('Form expired, please try again');
    } elseif ($stage === 'analyze') {
        if ($selectedType === '' || !$hasImportPermission($selectedType)) {
            $errors[] = t('Permission denied');
        } else {
            $analysis = $importService->analyzeUpload($_FILES['csv_file'] ?? [], $selectedType, $currentUserId);
            if (!($analysis['ok'] ?? false)) {
                $errors[] = $importService->messageForCode((string) ($analysis['code'] ?? 'unexpected_error'));
            } else {
                $token = (string) ($analysis['token'] ?? '');
                $state = $importService->state($token);
                $mapping = is_array($analysis['auto_mapping'] ?? null) ? $analysis['auto_mapping'] : [];
                $step = 'mapping';
            }
        }
    } elseif ($stage === 'preview') {
        $token = trim((string) ($_POST['token'] ?? ''));
        $state = $importService->state($token);
        $mapping = is_array($_POST['mapping'] ?? null) ? $_POST['mapping'] : [];
        if (!$state) {
            $errors[] = $importService->messageForCode('invalid_file_type');
        } else {
            $selectedType = (string) ($state['type'] ?? $selectedType);
            if ($selectedType === '' || !$hasImportPermission($selectedType)) {
                $errors[] = t('Permission denied');
            } else {
                $preview = $importService->preview($token, ['mapping' => $mapping], $currentUserId);
                if (!($preview['ok'] ?? false)) {
                    $errors[] = $importService->messageForCode((string) ($preview['code'] ?? 'unexpected_error'));
                    $step = 'mapping';
                } else {
                    $step = 'preview';
                }
            }
        }
    } elseif ($stage === 'commit') {
        $token = trim((string) ($_POST['token'] ?? ''));
        $mapping = is_array($_POST['mapping'] ?? null) ? $_POST['mapping'] : [];
        $state = $importService->state($token);
        if (!$state) {
            $errors[] = $importService->messageForCode('invalid_file_type');
        } else {
            $selectedType = (string) ($state['type'] ?? $selectedType);
            if ($selectedType === '' || !$hasImportPermission($selectedType)) {
                $errors[] = t('Permission denied');
            } else {
                $result = $importService->commit($token, ['mapping' => $mapping], $currentUserId);
                if (!($result['ok'] ?? false)) {
                    $errors[] = $importService->messageForCode((string) ($result['code'] ?? 'unexpected_error'));
                    $step = 'mapping';
                } else {
                    $step = 'result';
                }
            }
        }
    }
}

if ($step === 'mapping' && !$state && $token !== '') {
    $state = $importService->state($token);
}

$activeProfile = $selectedType !== '' ? $importService->profile($selectedType) : null;
$allowedTargets = $activeProfile ? $activeProfile->allowedTargets() : [];
$requiredTargets = $activeProfile ? $activeProfile->requiredTargets() : [];
$requiredTargetsHint = implode(', ', $requiredTargets);
$showAssignmentPermissionHint = $activeProfile ? $activeProfile->requiresAssignmentPermission() : false;
$headers = is_array($state['headers'] ?? null) ? $state['headers'] : [];
$selectedProfileLabel = $selectedType;
foreach ($profileOptions as $option) {
    if ((string) $option['key'] === $selectedType) {
        $selectedProfileLabel = (string) $option['label'];
        break;
    }
}

Buffer::set('title', t('Imports'));
