<?php

use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\I18n;
use MintyPHP\Router;
use MintyPHP\Service\Access\SettingsAuthorizationPolicy;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Service\Content\PageService;
use MintyPHP\Session;
use MintyPHP\Support\Flash;

$sessionStore = app(SessionStoreInterface::class);
$session = $sessionStore->all();

$user = $session['user'] ?? [];
$currentUserId = (int) ($user['id'] ?? 0);
if ($currentUserId <= 0) {
    Flash::error(t('Login required'), Request::safeReturnTarget((string) (requestInput()->bodyAll()['return'] ?? '')), 'login_required');
    Router::redirect('login');
}

$return = Request::safeReturnTarget((string) (requestInput()->bodyAll()['return'] ?? ''));
$canEdit = app(UiAccessService::class)->allow(
    $currentUserId,
    SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_UPDATE
);
if (!$canEdit) {
    http_response_code(403);
    Flash::error(t('You are not allowed to edit this page'), $return, 'page_forbidden');
    Router::redirect($return !== '' ? $return : '');
}

if (!Session::checkCsrfToken()) {
    Flash::error(t('Form expired, please try again'), $return, 'page_csrf');
    Router::redirect($return !== '' ? $return : '');
}

$slug = trim((string) (requestInput()->bodyAll()['slug'] ?? ''));
$fromLocale = trim((string) (requestInput()->bodyAll()['from_locale'] ?? (I18n::$locale ?? '')));
$toLocale = trim((string) (requestInput()->bodyAll()['to_locale'] ?? ''));

if ($return === '' && $slug !== '') {
    $return = 'page/' . $slug;
}

$result = PageService::copyContentToLocale($slug, $fromLocale, $toLocale, $currentUserId);
if (!($result['ok'] ?? false)) {
    $errors = formErrorsFrom($result['errors'] ?? [t('Page can not be updated')])->toFlatList();
    $firstError = (string) ($errors[0] ?? t('Page can not be updated'));
    Flash::error($firstError, $return, 'page_copy_failed');
    Router::redirect($return);
}

$pageEditMode = $sessionStore->get('page_edit_mode', []);
if (!is_array($pageEditMode)) {
    $pageEditMode = [];
}
$pageEditMode[$slug] = 1;
$sessionStore->set('page_edit_mode', $pageEditMode);

Flash::success(t('Content copied'), $return, 'page_copy_ok');
Router::redirect($return);
