<?php

use MintyPHP\Buffer;
use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\I18n;
use MintyPHP\Router;
use MintyPHP\Service\Content\PageService;

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

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

$currentUserId = (int) (($session['user']['id'] ?? 0));
if ($currentUserId > 0) {
    Router::redirect(Request::withLocale('page/' . $slug, I18n::$locale ?? I18n::$defaultLocale));
}

$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'));
}

$returnPath = Request::path();
if ($returnPath === '') {
    $returnPath = $slug;
}
$formAction = '/' . ltrim($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);
}

$canEdit = false;
$editMode = false;
