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

use \Mtc\Cms\Handlers\TemplateHandler;
use Illuminate\Support\Facades\Event;
use Mtc\Cms\Events\AdminLoadPageEvent;

$cm = new ContentManager();
$page = new Page();

Event::dispatch(new AdminLoadPageEvent($_GET['page_id']));

$page->language_ignored_page = false; // boolean - if this page should be ignored for multilanguage

if (isset($_GET['page_id']) && is_numeric($_GET['page_id'])) {
    if (defined('CMS_MULTI_LANG') && CMS_MULTI_LANG === true) {
        if (CMS_MULTI_LANG_PAGE_IGNORE === true && Language::isIgnoredPage($_GET['page_id'])) {
            $_SESSION['content_manager']['language'] = "";
            $page->language_ignored_page = true; // boolean - if this page should be ignored for multilanguage
            $page->setLanguage("");
        } else {
            if (empty($_SESSION['content_manager']['language'])) {
                $_SESSION['content_manager']['language'] = "";
            }
            $page->setLanguage($_SESSION['content_manager']['language']);
        }
    }
    $page->get($_GET['page_id']);
    if (empty($page->id)) {
        header("HTTP/1.0 409 Conflict");
        $error_message = "The page you attempted to load was not found.";
        ContentManagerPanel::addMessage($error_message);
        die($error_message);
    }
} else {
    header("HTTP/1.0 400 Bad Request");
    $error_message = "page_id missing from load page request.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}

if ($page->type == "history") {
    header("HTTP/1.0 409 Conflict");
    $error_message = "The page you attempted to load was not valid.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}

if (
    defined("CMS_CHECK_IF_PAGE_STRUCTURE_IS_SAVED") &&
    CMS_CHECK_IF_PAGE_STRUCTURE_IS_SAVED === true &&
    $adminuser->isMtcAdmin() &&
    $_SESSION['content_manager']['is_client_view'] == false
) {
    $page->is_structure_saved = TemplateHandler::isStructureSaved($page, $twig_loader);
}

$page->parent_listing_page = $cm->checkPageForParentListingContainer($page); // boolean - if parent is a listing container

if ($page->type != "default" || !defined("CMS_PAGE_PREVIEW") || CMS_PAGE_PREVIEW !== true || CMS_PAGE_PREVIEW_ADV !== true) {
    $page->preview_page = clone $page;
    die(json_encode($page));
}

// If versioning is enabled
if (defined("CMS_PAGE_VERSIONING") && CMS_PAGE_VERSIONING === true) {
    // parse page so that it is ready for versioning
    $page = \Mtc\Cms\Handlers\VersioningHandler::parsePageForCmPanelVersioningPageload($page, $_GET);
} else {
    // Generate a sandbox for this page.
    // Even though versioning isn't enabled - this can be used for adv preview or other features.
    $page->preview_page = \Mtc\Cms\Handlers\VersioningHandler::createNewPageSandbox($page, $page);
}

die(json_encode($page));
