<?php
/**
 * Script for storing pagedata structure in the template
 * @author Rihards Siliņš
 * @copyright MTC media Ltd
 * @version 1 20/10/2016
 */
$cms_root_path = "../../../";
require_once($cms_root_path."includes/compatibility_includer.php");

use Mtc\Cms\Handlers\TemplateHandler;
use Mtc\Cms\Models\Page as PageModel;

if (empty($_GET['page_id']) || !is_numeric($_GET['page_id'])) {
    ContentManagerPanel::messageAndDie(
        "page_id missing from store pagedata structure in the template request.",
        "HTTP/1.0 400 Bad Request"
    );
}

$page = ContentManagerPanel::loadPage($_GET['page_id'], false);
if (empty($page->id)) {
    ContentManagerPanel::messageAndDie(
        "The page which pagedata you attempted to store in the template was not found.",
        "HTTP/1.0 409 Conflict"
    );
}

if (empty($_GET['template']) || !TemplateHandler::validTemplateFilename($_GET['template'])) {
    ContentManagerPanel::messageAndDie(
        "valid template missing from store pagedata structure in the template request.",
        "HTTP/1.0 400 Bad Request"
    );
}
$page_template = $_GET['template'];

$include_content_in_structure = false;
if (!empty($_GET['include_content_in_structure'])) {
    $include_content_in_structure = true;
}

$pagedata = new Pagedata();
$result = $pagedata->get($page->id, 0, 0, 0, $include_content_in_structure, true);

if ($result === false) {
    ContentManagerPanel::messageAndDie(
        "The pagedata which you attempted to store in the template failed to be retrieved.",
        "HTTP/1.0 409 Conflict"
    );
}

// wrap it in a structure that can describe what it is
$structure = array(
    'action' => 'add_pagedata_structure',
    'pagedata' => Pagedata::removeDefaultData($pagedata->pagedata)
);

$structure = json_encode($structure, JSON_PRETTY_PRINT);

// create template structure dir if such doesn't exist
$template_structure_dir = SITE_PATH . "/" . THEME_PATH . "/templates/structures";
if (!is_dir($template_structure_dir)) {
    mkdir($template_structure_dir, 0755, true);
}

$structure_filename = str_replace(".twig", ".json", $page_template);

file_put_contents($template_structure_dir . "/" . $structure_filename, $structure);

// get list of pages that have this template so we can use for request to sync changes across all pages
$list_of_pages_that_have_this_template = PageModel::where("template", $page_template)
    ->where("type", "!=", "button")
    ->get(["id", "title"])
    ->toJson();

header('Content-Type: application/json');
exit($list_of_pages_that_have_this_template);
