<?php
/**
 * Set what templates clients can switch between
 * @author Rihards Silins
 * @copyright MTC media Ltd
 * @version 1 29/06/2017
 */
$cms_root_path = "../../../";
require_once($cms_root_path . "includes/compatibility_includer.php");

// Check if feature is enabled.
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!"
        ])
    );
}

$pages_to_set = [];

if (!empty($_GET['set_form']) && $_GET['set_form'] == "current" && !empty($_GET['current_page_id'])) {
    $page = ContentManagerPanel::loadPage($_GET['current_page_id'], false);
    if (!empty($page->id)) {
        $pages_to_set = [$page];
    }
} elseif (!empty($_GET['page_ids'])) {
    foreach ($_GET['page_ids'] as $page_id) {
        $page = ContentManagerPanel::loadPage($page_id, false);
        if (empty($page->id)) {
            continue;
        }
        $pages_to_set[] = $page;
    }
}

foreach ($pages_to_set as $page) {
    $page_logic = json_decode($page->logic);

    if (empty($page_logic)) {
        $page_logic = new stdClass();
    }

    if (empty($_GET['templates'])) {
        $page_logic->client_selectable_templates = [];
    } else {
        $page_logic->client_selectable_templates = $_GET['templates'];
    }

    $page->logic = json_encode($page_logic);
    $page->save();
}

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