<?php

$cms_root_path = "../../../";
require_once($cms_root_path."includes/compatibility_includer.php");

use \Mtc\Cms\Handlers\ListingCacheHandler;

$target_page_id = 0;
if (!empty($_POST['target_page_id']) && is_numeric($_POST['target_page_id'])) {
    $target_page_id = $_POST['target_page_id'];
}

if ( !empty($_POST['mode']) && $_POST['mode'] == "session" ) {
	$_POST['logic'] = $_SESSION['content_manager']['clipboard_page'];
}

// Replace insecure PHP serialization with JSON parsing and validation
$logic = null;
if (isset($_POST['logic'])) {
    if (is_array($_POST['logic'])) {
        $logic = $_POST['logic'];
    } elseif (is_string($_POST['logic'])) {
        $raw = stripslashes($_POST['logic']);
        $decoded = json_decode($raw, true);
        if (is_array($decoded)) {
            $logic = $decoded;
        }
    }
}

if (!is_array($logic) || !isset($logic['action']) || $logic['action'] !== "lapsg") {
    die("false");
}

$cm = new ContentManager();
$cm->setTwigLoader($twig_loader);
$generated_pages_on_this_level = $cm->processLapsg($logic['logic']['pages'], $target_page_id);

$target_page = new Page();
$target_page->get($target_page_id);
$return_to_page_id = $target_page_id;

if (empty($logic['logic']['pages'])) {
    die($target_page_id);
} else {
    for ($i=0; $i < count($generated_pages_on_this_level); $i++) {
        $cm->processSlugsForPageAndSubs($generated_pages_on_this_level[$i]);
    }
    // rebuild listing cache if relevant
    ListingCacheHandler::triggerAsyncRefresh($target_page);

    if ($target_page->listing_container == 1 && count($logic['logic']['pages']) > 1) {
        die($target_page_id);
    } else {
        die($generated_pages_on_this_level[0]);
    }
}
