<?php

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

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

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

$slug = trim((string) ($_POST['slug'] ?? ''));
$fromLocale = trim((string) ($_POST['from_locale'] ?? (I18n::$locale ?? '')));
$toLocale = trim((string) ($_POST['to_locale'] ?? ''));

$return = Request::safeReturnTarget((string) ($_POST['return'] ?? ''));
if ($return === '' && $slug !== '') {
    $return = 'page/' . $slug;
}

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

$_SESSION['page_edit_mode'][$slug] = 1;
Flash::success(t('Content copied'), $return, 'page_copy_ok');
Router::redirect($return);
