<?php

use MintyPHP\Buffer;
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();

$slug = trim((string) ($slug ?? ''));
if ($slug === '') {
    Router::redirect('');
}

$pageBundle = PageService::findBySlugWithLocale($slug, I18n::$locale ?? null);
$page = $pageBundle['page'] ?? null;
$pageContent = $pageBundle['content'] ?? null;
$notFound = $page === null;
if ($notFound) {
    http_response_code(404);
    Buffer::set('title', t('Page not found'));
}

$user = $session['user'] ?? [];
$currentUserId = (int) ($user['id'] ?? 0);
$canEdit = app(UiAccessService::class)->allow(
    $currentUserId,
    SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_UPDATE
);
$returnPath = Request::path();
if ($returnPath === '') {
    $returnPath = 'page/' . $slug;
}
$requestedReturn = Request::safeReturnTarget((string) (requestInput()->bodyAll()['return'] ?? ''));
if ($requestedReturn !== '') {
    $returnPath = $requestedReturn;
}
$formAction = '/' . ltrim($returnPath, '/');
$wantsJson = Request::wantsJson();
$markEditMode = static function (string $pageSlug) use ($sessionStore): void {
    $pageEditMode = $sessionStore->get('page_edit_mode', []);
    if (!is_array($pageEditMode)) {
        $pageEditMode = [];
    }

    $pageEditMode[$pageSlug] = 1;
    $sessionStore->set('page_edit_mode', $pageEditMode);
};

$sessionEdit = false;
if (!empty($session['page_edit_mode']) && is_array($session['page_edit_mode'])) {
    $sessionEdit = !empty($session['page_edit_mode'][$slug]);
    $pageEditMode = $session['page_edit_mode'];
    unset($pageEditMode[$slug]);
    $sessionStore->set('page_edit_mode', $pageEditMode);
}

if (requestInput()->method() === 'POST') {
    if (!$canEdit || $notFound) {
        http_response_code(403);
        Flash::error(t('You are not allowed to edit this page'), $returnPath, 'page_forbidden');
        if ($wantsJson) {
            Router::json(['ok' => false, 'error' => 'forbidden', 'redirect' => $returnPath]);
        }
        Router::redirect($returnPath);
    }

    if (!Session::checkCsrfToken()) {
        Flash::error(t('Form expired, please try again'), $returnPath, 'page_csrf');
        if ($wantsJson) {
            Router::json(['ok' => false, 'error' => 'csrf', 'redirect' => $returnPath]);
        }
        Router::redirect($returnPath);
    }

    $content = (string) (requestInput()->bodyAll()['content'] ?? '');
    $result = PageService::updateContentBySlug($slug, $content, $currentUserId, I18n::$locale ?? null);

    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, $returnPath, 'page_update_failed');
        if ($wantsJson) {
            $markEditMode($slug);
            Router::json(['ok' => false, 'error' => 'invalid', 'redirect' => $returnPath]);
        }
        $markEditMode($slug);
        Router::redirect($returnPath);
    }

    Flash::success(t('Page updated'), $returnPath, 'page_updated');
    if ($wantsJson) {
        $markEditMode($slug);
        Router::json(['ok' => true, 'redirect' => $returnPath]);
    }
    $markEditMode($slug);
    Router::redirect($returnPath);
}

$contentJson = '';
if (is_array($pageContent) && isset($pageContent['content'])) {
    $contentJson = (string) $pageContent['content'];
}
if ($contentJson === '') {
    $contentJson = json_encode(['blocks' => []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

$editMode = $canEdit && (($sessionEdit === true) || ((requestInput()->queryAll()['edit'] ?? '') === '1'));
$locales = defined('APP_LOCALES') ? APP_LOCALES : [I18n::$defaultLocale];
$currentLocale = I18n::$locale ?? (I18n::$defaultLocale ?? 'de');
