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

// Check if feature is enabled.
if (!$_SESSION['content_manager']['is_mtcadmin']) {
    if (!defined('CMS_ALLOW_CLIENTS_TO_SWITCH_TEMPLATES') || CMS_ALLOW_CLIENTS_TO_SWITCH_TEMPLATES === false) {
        exit(
            json_encode([
                "result" => false,
                "message" => "Feature CMS_ALLOW_CLIENTS_TO_SWITCH_TEMPLATES not enabled!"
            ])
        );
    }
}

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

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

if (!isset($_GET['page_id'])) {
    ContentManagerPanel::messageAndDie(
        "page_id is missing from load pagedata structure from template request.",
        "HTTP/1.0 400 Bad Request"
    );
}

if ($_GET['page_id'] != "*" && !is_numeric($_GET['page_id'])) {
    ContentManagerPanel::messageAndDie(
        "page_id is malformed in load pagedata structure from template request.",
        "HTTP/1.0 400 Bad Request"
    );
} elseif ($_GET['page_id'] === "*" && !$_SESSION['content_manager']['is_mtcadmin'])  {
    ContentManagerPanel::messageAndDie(
        "non-mtcadmin users should not be able to change pagedata structure for several pages at once.",
        "HTTP/1.0 409 Conflict"
    );
}

if ($_GET['page_id'] === "*") {
    $pages = PageModel::where("template", $page_template)
        ->where("type", "!=", "button")
        ->get();
} else {
    $page = ContentManagerPanel::loadPage($_GET['page_id'], false);
    if (empty($page->id)) {
        ContentManagerPanel::messageAndDie(
            "The page which you wanted to add pagedata structure to was not found.",
            "HTTP/1.0 409 Conflict"
        );
    }

    if (!$_SESSION['content_manager']['is_mtcadmin']) {
        $page_logic = json_decode($page->logic);
        $client_selectable_templates = [];
        $allow_all_templates = false;
        if (!empty($page_logic) && !empty($page_logic->client_selectable_templates)) {
            $client_selectable_templates = $page_logic->client_selectable_templates;
        } else if (CMS_ALLOW_CLIENTS_TO_SWITCH_TEMPLATES_DEFAULT_TO_ALL_TEMPLATES === true) {
            $allow_all_templates = true;
        }
        // if there are not client_selectable_templates set then all templates can be switched between
        // if there are - it need to get checked
        if (!$allow_all_templates && !in_array($page_template, $client_selectable_templates)) {
            exit(
                json_encode([
                    "result" => false,
                    "message" => "Your aren't allowed to switch to this template!"
                ])
            );
        }
    }

    $pages = [$page];
}

$clear_pagedata = false;
if (isset($_GET['clear_pagedata']) && $_GET['clear_pagedata'] == 1) {
    $clear_pagedata = true;
}

$merge_pagedata = true;
if (isset($_GET['merge_pagedata']) && $_GET['merge_pagedata'] == 0) {
    $merge_pagedata = false;
}

$delete_unreferenced_pagedata = true;
if (isset($_GET['delete_unreferenced_pagedata']) && $_GET['delete_unreferenced_pagedata'] == 0) {
    $delete_unreferenced_pagedata = false;
}

$structure_filename = TemplateHandler::getStructureFilename($page_template);
$structure_request = TemplateHandler::getStructure($structure_filename, $twig_loader);

if ($structure_request['result'] === false) {
    exit(
        json_encode($structure_request)
    );
}

foreach ($pages as $page) {
    $pagedata = new Pagedata();
    $pagedata->page_id = $page->id;

    if ($clear_pagedata) {
        $pagedata->delete();
    }

    if ($merge_pagedata) {
        $pagedata->get($page->id); // retrieve existing
        $pagedata->merge($structure_request['structure']['pagedata'], $delete_unreferenced_pagedata);
    } else {
        $pagedata->pagedata = $structure_request['structure']['pagedata'];
    }

    $pagedata->save();
}

exit(
    json_encode([
        "result" => true,
        "message" => "Success!"
    ])
);
