<?php
/**
 * Script for executing a page commit in the context of the versioning functionality enabled in the cms
 * @author Rihards Siliņš
 * @copyright MTC media Ltd
 */
$cms_root_path = "../../../";
require_once($cms_root_path."includes/compatibility_includer.php");

if (empty($_POST['page_id']) || !is_numeric($_POST['page_id'])) {
    header("HTTP/1.0 400 Bad Request");
    $error_message = "page_id missing from make current request.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}

$page = ContentManagerPanel::loadPage($_POST['page_id'], false);
if (empty($page->id)) {
    header("HTTP/1.0 409 Conflict");
    $error_message = "The page you attempted to make current was not found.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}

$comment = null;
if (!empty($_POST['comment'])) {
    $comment = $_POST['comment'];
}

$content_manager = new ContentManager();
$response = $content_manager->commitPage($page, $comment);

// Drop any extra history pages according to settings
Page::dropHistoryPages($page->draft_for_page_id);
// Drop Corrupt Pages
Page::dropCorruptPages();

if ($response["response"] == 2) {
    // rebuild listing cache if relevant
    \Mtc\Cms\Handlers\ListingCacheHandler::triggerAsyncRefresh($page);
} else {
    ContentManagerPanel::addMessage($response["response_message"]);
}
die(json_encode($response));
