<?php

use MintyPHP\Buffer;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Service\Content\PageService;
use MintyPHP\Http\Request;
use MintyPHP\I18n;

$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 = $currentUserId > 0;
$returnPath = Request::path();
if ($returnPath === '') {
    $returnPath = 'page/' . $slug;
}
$requestedReturn = Request::safeReturnTarget((string) ($_POST['return'] ?? ''));
if ($requestedReturn !== '') {
    $returnPath = $requestedReturn;
}
$formAction = '/' . ltrim($returnPath, '/');
$wantsJson = Request::wantsJson();

$sessionEdit = false;
if (!empty($_SESSION['page_edit_mode']) && is_array($_SESSION['page_edit_mode'])) {
    $sessionEdit = !empty($_SESSION['page_edit_mode'][$slug]);
    unset($_SESSION['page_edit_mode'][$slug]);
}

if ($_SERVER['REQUEST_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) ($_POST['content'] ?? '');
    $result = PageService::updateContentBySlug($slug, $content, $currentUserId, I18n::$locale ?? null);

    if (!($result['ok'] ?? false)) {
        $errors = $result['errors'] ?? [t('Page can not be updated')];
        Flash::error((string) $errors[0], $returnPath, 'page_update_failed');
        if ($wantsJson) {
            $_SESSION['page_edit_mode'][$slug] = 1;
            Router::json(['ok' => false, 'error' => 'invalid', 'redirect' => $returnPath]);
        }
        $_SESSION['page_edit_mode'][$slug] = 1;
        Router::redirect($returnPath);
    }

    Flash::success(t('Page updated'), $returnPath, 'page_updated');
    if ($wantsJson) {
        $_SESSION['page_edit_mode'][$slug] = 1;
        Router::json(['ok' => true, 'redirect' => $returnPath]);
    }
    $_SESSION['page_edit_mode'][$slug] = 1;
    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) || (($_GET['edit'] ?? '') === '1'));
$locales = defined('APP_LOCALES') ? APP_LOCALES : [I18n::$defaultLocale];
$currentLocale = I18n::$locale ?? (I18n::$defaultLocale ?? 'de');
