<?php

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

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

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

$new_list_item = array(
    'new_pagedata_name' => trim($_POST['new_pagedata_name']),
    'new_pagedata_value' => (isset($_POST['new_pagedata_value']) ? $_POST['new_pagedata_value'] : ''),
    'new_pagedata_type' => $_POST['new_pagedata_type'],
);

$cm = new ContentManager();
$result = $cm->processAddPagedata($new_list_item, $page);
if ($result === false) {
    header("HTTP/1.0 400 Bad Request");
    $error_message = "Adding pagedata failed.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}
Pagedata::orderFix($page->id);

$pagedata = new Pagedata();
$pagedata->Get($_GET['page_id']);

$_POST['pagedata_lists'][0] = $pagedata->pagedata[count($pagedata->pagedata)-1];
$_POST['pagedata_lists'] = json_encode($_POST['pagedata_lists']);

include("../templates/edit_page_lists.php");
